@toolbox-web/grid 1.21.0 → 1.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/all.js +2 -6850
  2. package/all.js.map +1 -1
  3. package/index.js +1 -4352
  4. package/index.js.map +1 -1
  5. package/lib/core/grid.d.ts +22 -6
  6. package/lib/core/grid.d.ts.map +1 -1
  7. package/lib/core/styles/index.d.ts.map +1 -1
  8. package/lib/plugins/clipboard/index.js +1 -733
  9. package/lib/plugins/clipboard/index.js.map +1 -1
  10. package/lib/plugins/column-virtualization/index.js +1 -560
  11. package/lib/plugins/column-virtualization/index.js.map +1 -1
  12. package/lib/plugins/context-menu/index.js +1 -754
  13. package/lib/plugins/context-menu/index.js.map +1 -1
  14. package/lib/plugins/editing/EditingPlugin.d.ts.map +1 -1
  15. package/lib/plugins/editing/index.d.ts +1 -1
  16. package/lib/plugins/editing/index.d.ts.map +1 -1
  17. package/lib/plugins/editing/index.js +1 -1539
  18. package/lib/plugins/editing/index.js.map +1 -1
  19. package/lib/plugins/editing/types.d.ts +23 -0
  20. package/lib/plugins/editing/types.d.ts.map +1 -1
  21. package/lib/plugins/export/index.js +1 -589
  22. package/lib/plugins/export/index.js.map +1 -1
  23. package/lib/plugins/filtering/FilteringPlugin.d.ts.map +1 -1
  24. package/lib/plugins/filtering/filter-model.d.ts.map +1 -1
  25. package/lib/plugins/filtering/index.js +1 -1283
  26. package/lib/plugins/filtering/index.js.map +1 -1
  27. package/lib/plugins/filtering/types.d.ts +4 -2
  28. package/lib/plugins/filtering/types.d.ts.map +1 -1
  29. package/lib/plugins/grouping-columns/index.js +1 -726
  30. package/lib/plugins/grouping-columns/index.js.map +1 -1
  31. package/lib/plugins/grouping-rows/index.js +2 -905
  32. package/lib/plugins/grouping-rows/index.js.map +1 -1
  33. package/lib/plugins/master-detail/index.js +1 -950
  34. package/lib/plugins/master-detail/index.js.map +1 -1
  35. package/lib/plugins/multi-sort/index.js +1 -553
  36. package/lib/plugins/multi-sort/index.js.map +1 -1
  37. package/lib/plugins/pinned-columns/index.js +1 -688
  38. package/lib/plugins/pinned-columns/index.js.map +1 -1
  39. package/lib/plugins/pinned-rows/index.js +1 -704
  40. package/lib/plugins/pinned-rows/index.js.map +1 -1
  41. package/lib/plugins/pivot/index.js +1 -1191
  42. package/lib/plugins/pivot/index.js.map +1 -1
  43. package/lib/plugins/print/index.js +1 -691
  44. package/lib/plugins/print/index.js.map +1 -1
  45. package/lib/plugins/reorder/index.js +1 -703
  46. package/lib/plugins/reorder/index.js.map +1 -1
  47. package/lib/plugins/responsive/index.js +1 -971
  48. package/lib/plugins/responsive/index.js.map +1 -1
  49. package/lib/plugins/row-reorder/index.js +1 -728
  50. package/lib/plugins/row-reorder/index.js.map +1 -1
  51. package/lib/plugins/selection/index.js +1 -1071
  52. package/lib/plugins/selection/index.js.map +1 -1
  53. package/lib/plugins/server-side/index.js +1 -521
  54. package/lib/plugins/server-side/index.js.map +1 -1
  55. package/lib/plugins/tree/index.js +1 -686
  56. package/lib/plugins/tree/index.js.map +1 -1
  57. package/lib/plugins/undo-redo/index.js +1 -584
  58. package/lib/plugins/undo-redo/index.js.map +1 -1
  59. package/lib/plugins/visibility/index.js +1 -792
  60. package/lib/plugins/visibility/index.js.map +1 -1
  61. package/package.json +4 -5
  62. package/umd/grid.all.umd.js +1 -186
  63. package/umd/grid.all.umd.js.map +1 -1
  64. package/umd/grid.umd.js +1 -90
  65. package/umd/grid.umd.js.map +1 -1
  66. package/umd/plugins/clipboard.umd.js +1 -6
  67. package/umd/plugins/clipboard.umd.js.map +1 -1
  68. package/umd/plugins/column-virtualization.umd.js +1 -1
  69. package/umd/plugins/column-virtualization.umd.js.map +1 -1
  70. package/umd/plugins/context-menu.umd.js +1 -1
  71. package/umd/plugins/context-menu.umd.js.map +1 -1
  72. package/umd/plugins/editing.umd.js +1 -1
  73. package/umd/plugins/editing.umd.js.map +1 -1
  74. package/umd/plugins/export.umd.js +1 -13
  75. package/umd/plugins/export.umd.js.map +1 -1
  76. package/umd/plugins/filtering.umd.js +1 -1
  77. package/umd/plugins/filtering.umd.js.map +1 -1
  78. package/umd/plugins/grouping-columns.umd.js +1 -1
  79. package/umd/plugins/grouping-columns.umd.js.map +1 -1
  80. package/umd/plugins/grouping-rows.umd.js +1 -4
  81. package/umd/plugins/grouping-rows.umd.js.map +1 -1
  82. package/umd/plugins/master-detail.umd.js +1 -1
  83. package/umd/plugins/master-detail.umd.js.map +1 -1
  84. package/umd/plugins/multi-sort.umd.js +1 -1
  85. package/umd/plugins/multi-sort.umd.js.map +1 -1
  86. package/umd/plugins/pinned-columns.umd.js +1 -1
  87. package/umd/plugins/pinned-columns.umd.js.map +1 -1
  88. package/umd/plugins/pinned-rows.umd.js +1 -1
  89. package/umd/plugins/pinned-rows.umd.js.map +1 -1
  90. package/umd/plugins/pivot.umd.js +1 -1
  91. package/umd/plugins/pivot.umd.js.map +1 -1
  92. package/umd/plugins/print.umd.js +1 -75
  93. package/umd/plugins/print.umd.js.map +1 -1
  94. package/umd/plugins/reorder.umd.js +1 -1
  95. package/umd/plugins/reorder.umd.js.map +1 -1
  96. package/umd/plugins/responsive.umd.js +1 -1
  97. package/umd/plugins/responsive.umd.js.map +1 -1
  98. package/umd/plugins/row-reorder.umd.js +1 -1
  99. package/umd/plugins/row-reorder.umd.js.map +1 -1
  100. package/umd/plugins/selection.umd.js +1 -3
  101. package/umd/plugins/selection.umd.js.map +1 -1
  102. package/umd/plugins/server-side.umd.js +1 -1
  103. package/umd/plugins/server-side.umd.js.map +1 -1
  104. package/umd/plugins/tree.umd.js +1 -1
  105. package/umd/plugins/tree.umd.js.map +1 -1
  106. package/umd/plugins/undo-redo.umd.js +1 -1
  107. package/umd/plugins/undo-redo.umd.js.map +1 -1
  108. package/umd/plugins/visibility.umd.js +1 -1
  109. package/umd/plugins/visibility.umd.js.map +1 -1
@@ -1,187 +1,2 @@
1
- (function(S,ue){typeof exports=="object"&&typeof module<"u"?ue(exports):typeof define=="function"&&define.amd?define(["exports"],ue):(S=typeof globalThis<"u"?globalThis:S||self,ue(S.TbwGrid={}))})(this,(function(S){"use strict";function ue(){return{rowCount:-1,colCount:-1,ariaLabel:void 0,ariaDescribedBy:void 0}}function tn(r,e,t,i,n){if(i===r.rowCount&&n===r.colCount)return!1;const o=r.rowCount;return r.rowCount=i,r.colCount=n,e&&(e.setAttribute("aria-rowcount",String(i)),e.setAttribute("aria-colcount",String(n))),i!==o&&t&&(i>0?t.setAttribute("role","rowgroup"):t.removeAttribute("role")),!0}function nn(r,e){const t=r?.gridAriaLabel;return t||(r?.shell?.header?.title??e?.lightDomTitle??void 0)}function rn(r,e,t,i){if(!e)return!1;let n=!1;const o=nn(t,i);o!==r.ariaLabel&&(r.ariaLabel=o,o?e.setAttribute("aria-label",o):e.removeAttribute("aria-label"),n=!0);const s=t?.gridAriaDescribedBy;return s!==r.ariaDescribedBy&&(r.ariaDescribedBy=s,s?e.setAttribute("aria-describedby",s):e.removeAttribute("aria-describedby"),n=!0),n}const ne={STRETCH:"stretch",FIXED:"fixed"},xt={mode:"reduced-motion",duration:200,easing:"ease-out"},Et='<svg viewBox="0 0 16 16" width="12" height="12"><path fill="currentColor" d="M6 10.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/></svg>',K={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:Et,filterActive:Et,print:"🖨️"};function on(r){return Array.from(r.querySelectorAll("tbw-grid-column")).map(t=>{const i=t.getAttribute("field")||"";if(!i)return null;const n=t.getAttribute("type")||void 0,s=n&&new Set(["number","string","date","boolean","select"]).has(n)?n:void 0,l=t.getAttribute("header")||void 0,a=t.hasAttribute("sortable"),c=t.hasAttribute("editable"),d={field:i,type:s,header:l,sortable:a,editable:c},u=t.getAttribute("width");if(u){const m=parseFloat(u);!isNaN(m)&&/^\d+(\.\d+)?$/.test(u.trim())?d.width=m:d.width=u}const h=t.getAttribute("minWidth")||t.getAttribute("min-width");if(h){const m=parseFloat(h);isNaN(m)||(d.minWidth=m)}t.hasAttribute("resizable")&&(d.resizable=!0),t.hasAttribute("sizable")&&(d.resizable=!0);const p=t.getAttribute("editor"),g=t.getAttribute("renderer");p&&(d.__editorName=p),g&&(d.__rendererName=g);const f=t.getAttribute("options");f&&(d.options=f.split(",").map(m=>{const[k,F]=m.includes(":")?m.split(":"):[m.trim(),m.trim()];return{value:k.trim(),label:F?.trim()||k.trim()}}));const w=t.querySelector("tbw-grid-column-view"),y=t.querySelector("tbw-grid-column-editor"),b=t.querySelector("tbw-grid-column-header");w&&(d.__viewTemplate=w),y&&(d.__editorTemplate=y),b&&(d.__headerTemplate=b);const T=globalThis.DataGridElement?.getAdapters?.()??[],A=w??t,C=T.find(m=>m.canHandle(A));if(C){const m=C.createRenderer(A);m&&(d.viewRenderer=m)}const v=y??t,E=T.find(m=>m.canHandle(v));if(E){const m=E.createEditor(v);m&&(d.editor=m)}return d}).filter(t=>!!t)}function Rt(r,e){if((!r||!r.length)&&(!e||!e.length))return[];if(!r||!r.length)return e||[];if(!e||!e.length)return r;const t={};e.forEach(n=>{const o=t[n.field];if(o){n.header&&!o.header&&(o.header=n.header),n.type&&!o.type&&(o.type=n.type),n.sortable&&(o.sortable=!0),n.editable&&(o.editable=!0),n.resizable&&(o.resizable=!0),n.width!=null&&o.width==null&&(o.width=n.width),n.minWidth!=null&&o.minWidth==null&&(o.minWidth=n.minWidth),n.__viewTemplate&&(o.__viewTemplate=n.__viewTemplate),n.__editorTemplate&&(o.__editorTemplate=n.__editorTemplate),n.__headerTemplate&&(o.__headerTemplate=n.__headerTemplate);const s=n.renderer||n.viewRenderer,l=o.renderer||o.viewRenderer;s&&!l&&(o.viewRenderer=s,n.renderer&&(o.renderer=s)),n.editor&&!o.editor&&(o.editor=n.editor)}else t[n.field]={...n}});const i=r.map(n=>{const o=t[n.field];if(!o)return n;const s={...n};o.header&&!s.header&&(s.header=o.header),o.type&&!s.type&&(s.type=o.type),s.sortable=n.sortable||o.sortable,(n.resizable===!0||o.resizable===!0)&&(s.resizable=!0),s.editable=n.editable||o.editable,o.width!=null&&s.width==null&&(s.width=o.width),o.minWidth!=null&&s.minWidth==null&&(s.minWidth=o.minWidth),o.__viewTemplate&&(s.__viewTemplate=o.__viewTemplate),o.__editorTemplate&&(s.__editorTemplate=o.__editorTemplate),o.__headerTemplate&&(s.__headerTemplate=o.__headerTemplate);const l=o.renderer||o.viewRenderer,a=s.renderer||s.viewRenderer;return l&&!a&&(s.viewRenderer=l,o.renderer&&(s.renderer=l)),o.editor&&!s.editor&&(s.editor=o.editor),delete t[n.field],s});return Object.keys(t).forEach(n=>i.push(t[n])),i}function St(r,e){try{r.part?.add?.(e)}catch{}const t=r.getAttribute("part");t?t.split(/\s+/).includes(e)||r.setAttribute("part",t+" "+e):r.setAttribute("part",e)}function _t(r){const e=r.effectiveConfig?.fitMode||r.fitMode||ne.STRETCH;if(e!==ne.STRETCH&&e!==ne.FIXED||r.__didInitialAutoSize||!r.isConnected)return;const t=Array.from(r._headerRowEl?.children||[]);if(!t.length)return;let i=!1;r._visibleColumns.forEach((n,o)=>{if(n.width)return;const s=t[o];let l=s?s.scrollWidth:0;for(const a of r._rowPool){const c=a.children[o];if(c){const d=c.scrollWidth;d>l&&(l=d)}}l>0&&(n.width=l+2,n.__autoSized=!0,i=!0)}),i&&he(r),r.__didInitialAutoSize=!0}const sn=/^(?:\d+(?:\.\d+)?(?:px|%|fr|em|rem|ch|vw|vh|vmin|vmax)|calc\(.+\)|min-content|max-content|minmax\(.+\)|fit-content\(.+\)|auto)$/i;function At(r,e){return typeof r=="number"?`${r}px`:(sn.test(r)||console.warn(`[tbw-grid] Column '${e??"?"}' has an invalid CSS width value: '${r}'. Expected a number (px) or a valid CSS unit string (e.g. '30%', '2fr', 'calc(...)').`),r)}function he(r){(r.effectiveConfig?.fitMode||r.fitMode||ne.STRETCH)===ne.STRETCH?r._gridTemplate=r._visibleColumns.map(t=>{if(t.width!=null)return At(t.width,t.field);const i=t.minWidth;return i!=null?`minmax(${i}px, 1fr)`:"1fr"}).join(" ").trim():r._gridTemplate=r._visibleColumns.map(t=>t.width!=null?At(t.width,t.field):"max-content").join(" "),r.style.setProperty("--tbw-column-template",r._gridTemplate)}function ln(r){return r==null?"string":typeof r=="number"?"number":typeof r=="boolean"?"boolean":r instanceof Date||typeof r=="string"&&/\d{4}-\d{2}-\d{2}/.test(r)&&!isNaN(Date.parse(r))?"date":"string"}function an(r,e){const t=r[0]||{},i=Object.keys(t).map(o=>{const s=t[o],l=ln(s);return{field:o,header:o.charAt(0).toUpperCase()+o.slice(1),type:l}}),n={};return i.forEach(o=>{n[o.field]=o.type||"string"}),{columns:i,typeMap:n}}const cn=/{{\s*([^}]+)\s*}}/g,B="__DG_EMPTY__",dn=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,un=/__(proto|defineGetter|defineSetter)|constructor|window|globalThis|global|process|Function|import|eval|Reflect|Proxy|Error|arguments|document|location|cookie|localStorage|sessionStorage|indexedDB|fetch|XMLHttpRequest|WebSocket|Worker|SharedWorker|ServiceWorker|opener|parent|top|frames|self|this\b/;function hn(r){return!r||typeof r!="string"?"":r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const fn=new Set(["script","iframe","object","embed","form","input","button","textarea","select","link","meta","base","style","template","slot","portal","frame","frameset","applet","noscript","noembed","plaintext","xmp","listing"]),kt=/^on\w+$/i,gn=new Set(["href","src","action","formaction","data","srcdoc","xlink:href","poster","srcset"]),pn=/^\s*(javascript|vbscript|data|blob):/i;function U(r){if(!r||typeof r!="string")return"";if(r.indexOf("<")===-1)return r;const e=document.createElement("template");return e.innerHTML=r,wn(e.content),e.innerHTML}function wn(r){const e=[],t=r.querySelectorAll("*");for(const i of t){const n=i.tagName.toLowerCase();if(fn.has(n)){e.push(i);continue}if((n==="svg"||i.namespaceURI==="http://www.w3.org/2000/svg")&&Array.from(i.attributes).some(l=>kt.test(l.name)||l.name==="href"||l.name==="xlink:href")){e.push(i);continue}const o=[];for(const s of i.attributes){const l=s.name.toLowerCase();if(kt.test(l)){o.push(s.name);continue}if(gn.has(l)&&pn.test(s.value)){o.push(s.name);continue}if(l==="style"&&/expression\s*\(|javascript:|behavior\s*:/i.test(s.value)){o.push(s.name);continue}}o.forEach(s=>i.removeAttribute(s))}e.forEach(i=>i.remove())}function fe(r,e){if(!r||r.indexOf("{{")===-1)return r;const t=[],i=r.replace(cn,(l,a)=>{const c=mn(a,e);return t.push({expr:a.trim(),result:c}),c}),n=bn(i),o=t.length&&t.every(l=>l.result===""||l.result===B);return J.test(r)||o?"":n}function mn(r,e){if(r=(r||"").trim(),!r||J.test(r))return B;if(r==="value")return e.value==null?B:String(e.value);if(r.startsWith("row.")&&!/[()?]/.test(r)&&!r.includes(":")){const i=r.slice(4),n=e.row?e.row[i]:void 0;return n==null?B:String(n)}if(r.length>80||!dn.test(r)||un.test(r))return B;const t=r.match(/\./g);if(t&&t.length>1)return B;try{const n=new Function("value","row",`return (${r});`)(e.value,e.row),o=n==null?"":String(n);return J.test(o)?B:o||B}catch{return B}}const J=/Reflect|Proxy|ownKeys/;function bn(r){return r&&r.replace(new RegExp(B,"g"),"").replace(/Reflect\.[^<>{}\s]+|\bProxy\b|ownKeys\([^)]*\)/g,"")}function Ne(r){if(J.test(r.textContent||"")){for(const e of r.childNodes)e.nodeType===Node.TEXT_NODE&&J.test(e.textContent||"")&&(e.textContent="");J.test(r.textContent||"")&&(r.textContent="")}}function Tt(r){const e=J.test(r),t=(i=>e?"":fe(r,i));return t.__blocked=e,t}const vn=100;class yn{#t;#e;#u;#c;#r;#l={};#i={};#h=!0;#w=[];#y;#d;#g;#a;#f;constructor(e){this.#a=e}get original(){return this.#l}get effective(){return this.#i}get columns(){return this.#i.columns??[]}set columns(e){this.#i.columns=e}get lightDomColumnsCache(){return this.#c}set lightDomColumnsCache(e){this.#c=e}get originalColumnNodes(){return this.#r}set originalColumnNodes(e){this.#r=e}get lightDomTitle(){return this.#f}set lightDomTitle(e){this.#f=e}get initialColumnState(){return this.#g}set initialColumnState(e){this.#g=e}get sourcesChanged(){return this.#h}markSourcesChanged(){this.#h=!0}setGridConfig(e){this.#t=e,this.#h=!0,this.#c=void 0}getGridConfig(){return this.#t}setColumns(e){this.#e=e,this.#h=!0}getColumns(){return this.#e}setFitMode(e){this.#u=e,this.#h=!0}getFitMode(){return this.#u}merge(){const e=(this.#i.columns?.length??0)>0;if(!this.#h&&e)return;const t=this.#_();this.#h=!1,this.#l=t,Object.freeze(this.#l),this.#l.columns&&Object.freeze(this.#l.columns),this.#i=this.#C(this.#l),this.#p()}#C(e){const t={...e};return e.columns&&(t.columns=e.columns.map(i=>({...i}))),e.shell&&(t.shell={...e.shell,header:e.shell.header?{...e.shell.header}:void 0,toolPanel:e.shell.toolPanel?{...e.shell.toolPanel}:void 0,toolPanels:e.shell.toolPanels?.map(i=>({...i})),headerContents:e.shell.headerContents?.map(i=>({...i}))}),t}#p(){const e=this.#i;this.#R(),typeof e.rowHeight=="number"&&e.rowHeight>0&&this.#a.setRowHeight(e.rowHeight),e.fitMode==="fixed"&&this.columns.forEach(i=>{i.width==null&&(i.width=80)}),this.#a.applyAnimationConfig(e)}#R(){const e=this.#i.typeDefaults;if(!e)return;const t=this.columns;for(const i of t){if(!i.type)continue;const n=e[i.type];n&&(!i.renderer&&!i.viewRenderer&&n.renderer&&(i.renderer=n.renderer),!i.format&&n.format&&(i.format=n.format),!i.editor&&n.editor&&(i.editor=n.editor),!i.editorParams&&n.editorParams&&(i.editorParams=n.editorParams))}}#_(){const e=this.#t?{...this.#t}:{},t=Array.isArray(e.columns)?[...e.columns]:[],i=(this.#c??[]).map(s=>({...s}));let n=Rt(t,i);this.#e&&this.#e.length&&(n=Rt(this.#e,i));const o=this.#a.getRows();return n.length===0&&o.length&&(n=an(o).columns),n.length&&(n.forEach(s=>{s.sortable===void 0&&(s.sortable=!0),s.resizable===void 0&&(s.resizable=!0),s.__originalWidth===void 0&&typeof s.width=="number"&&(s.__originalWidth=s.width)}),n.forEach(s=>{s.__viewTemplate&&!s.__compiledView&&(s.__compiledView=Tt(s.__viewTemplate.innerHTML)),s.__editorTemplate&&!s.__compiledEditor&&(s.__compiledEditor=Tt(s.__editorTemplate.innerHTML))}),e.columns=n),this.#u&&(e.fitMode=this.#u),e.fitMode||(e.fitMode="stretch"),this.#x(e),e.columnState&&!this.#g&&(this.#g=e.columnState),e}#x(e){e.shell=e.shell?{...e.shell}:{},e.shell.header=e.shell.header?{...e.shell.header}:{};const t=this.#a.getShellLightDomTitle();t&&(this.#f=t),this.#f&&!e.shell.header.title&&(e.shell.header.title=this.#f);const i=this.#a.getShellLightDomHeaderContent();i?.length>0&&(e.shell.header.lightDomContent=i),this.#a.getShellHasToolButtonsContainer()&&(e.shell.header.hasToolButtonsContainer=!0);const n=this.#a.getShellToolPanels();if(n.size>0){const u=Array.from(n.values());u.sort((h,p)=>(h.order??100)-(p.order??100)),e.shell.toolPanels=u}const o=this.#a.getShellHeaderContents();if(o.size>0){const u=Array.from(o.values());u.sort((h,p)=>(h.order??100)-(p.order??100)),e.shell.headerContents=u}const s=this.#a.getShellToolbarContents(),l=Array.from(s.values()),a=this.#t?.shell?.header?.toolbarContents??[],c=new Set(a.map(u=>u.id)),d=[...a];for(const u of l)c.has(u.id)||d.push(u);d.sort((u,h)=>(u.order??0)-(h.order??0)),e.shell.header.toolbarContents=d}collectState(e){const t=this.columns,i=this.#E();return{columns:t.map((n,o)=>{const s={field:n.field,order:o,visible:!n.hidden},l=n;l.__renderedWidth!==void 0?s.width=l.__renderedWidth:n.width!==void 0&&(s.width=typeof n.width=="string"?parseFloat(n.width):n.width);const a=i.get(n.field);a&&(s.sort=a);for(const c of e)if(c.getColumnState){const d=c.getColumnState(n.field);d&&Object.assign(s,d)}return s})}}applyState(e,t){if(!e.columns||e.columns.length===0)return;const i=this.columns,n=new Map(e.columns.map(l=>[l.field,l])),o=i.map(l=>{const a=n.get(l.field);if(!a)return l;const c={...l};return a.width!==void 0&&(c.width=a.width,c.__renderedWidth=a.width),a.visible!==void 0&&(c.hidden=!a.visible),c});o.sort((l,a)=>{const c=n.get(l.field)?.order??1/0,d=n.get(a.field)?.order??1/0;return c-d}),this.columns=o;const s=e.columns.filter(l=>l.sort!==void 0).sort((l,a)=>(l.sort?.priority??0)-(a.sort?.priority??0));if(s.length>0){const l=s[0];l.sort&&this.#a.setSortState({field:l.field,direction:l.sort.direction==="asc"?1:-1})}else this.#a.setSortState(null);for(const l of t)if(l.applyColumnState)for(const a of e.columns)l.applyColumnState(a.field,a)}resetState(e){this.#g=void 0,this.#a.setSortState(null),this.#i=this.#C(this.#l),this.#p();for(const t of e)if(t.applyColumnState)for(const i of this.columns)t.applyColumnState(i.field,{field:i.field,order:0,visible:!0});this.requestStateChange(e)}#E(){const e=new Map,t=this.#a.getSortState();return t&&e.set(t.field,{direction:t.direction===1?"asc":"desc",priority:0}),e}requestStateChange(e){this.#d&&clearTimeout(this.#d),this.#d=setTimeout(()=>{this.#d=void 0;const t=this.collectState(e);this.#a.emit("column-state-change",t)},vn)}setColumnVisible(e,t){const i=this.columns,n=i.find(s=>s.field===e);return!n||!t&&n.lockVisible||!t&&i.filter(l=>!l.hidden&&l.field!==e).length===0||!!n.hidden===!t?!1:(n.hidden=!t,this.#a.emit("column-visibility",{field:e,visible:t,visibleColumns:i.filter(s=>!s.hidden).map(s=>s.field)}),this.#a.clearRowPool(),this.#a.setup(),!0)}toggleColumnVisibility(e){const t=this.columns.find(i=>i.field===e);return t?this.setColumnVisible(e,!!t.hidden):!1}isColumnVisible(e){const t=this.columns.find(i=>i.field===e);return t?!t.hidden:!1}showAllColumns(){const e=this.columns;e.some(t=>t.hidden)&&(e.forEach(t=>t.hidden=!1),this.#a.emit("column-visibility",{visibleColumns:e.map(t=>t.field)}),this.#a.clearRowPool(),this.#a.setup())}getAllColumns(){return this.columns.map(e=>({field:e.field,header:e.header||e.field,visible:!e.hidden,lockVisible:e.lockVisible,utility:e.meta?.utility===!0}))}getColumnOrder(){return this.columns.map(e=>e.field)}setColumnOrder(e){if(!e.length)return;const t=new Map(this.columns.map(n=>[n.field,n])),i=[];for(const n of e){const o=t.get(n);o&&(i.push(o),t.delete(n))}for(const n of t.values())i.push(n);this.columns=i,this.#a.renderHeader(),this.#a.updateTemplate(),this.#a.refreshVirtualWindow()}parseLightDomColumns(e){this.#c||(this.#r=Array.from(e.querySelectorAll("tbw-grid-column")),this.#c=this.#r.length?on(e):[])}clearLightDomCache(){this.#c=void 0}#v=new Map;registerLightDomHandler(e,t){this.#v.set(e.toLowerCase(),t)}unregisterLightDomHandler(e){this.#v.delete(e.toLowerCase())}observeLightDOM(e){this.#y&&this.#y.disconnect();const t=new Set;let i=null;const n=()=>{i=null;for(const o of t)this.#v.get(o)?.();t.clear()};this.#y=new MutationObserver(o=>{for(const s of o){for(const l of s.addedNodes){if(l.nodeType!==Node.ELEMENT_NODE)continue;const c=l.tagName.toLowerCase();this.#v.has(c)&&t.add(c)}if(s.type==="attributes"&&s.target.nodeType===Node.ELEMENT_NODE){const a=s.target.tagName.toLowerCase();this.#v.has(a)&&t.add(a)}}t.size>0&&!i&&(i=setTimeout(n,0))}),this.#y.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["title","field","header","width","hidden","id","icon","tooltip","order"]})}onChange(e){this.#w.push(e)}notifyChange(){for(const e of this.#w)e()}dispose(){this.#y?.disconnect(),this.#w=[],this.#d&&clearTimeout(this.#d)}}function qe(){if(typeof window<"u"&&window.location){const r=window.location.hostname;if(r==="localhost"||r==="127.0.0.1"||r==="::1")return!0}return typeof process<"u"&&process.env?.NODE_ENV!=="production"}function Lt(r){return`<span role="checkbox" aria-checked="${r}" aria-label="${r}">${r?"&#x1F5F9;":"&#9744;"}</span>`}function Pt(r){if(r==null||r==="")return"";if(r instanceof Date)return isNaN(r.getTime())?"":r.toLocaleDateString();if(typeof r=="number"||typeof r=="string"){const e=new Date(r);return isNaN(e.getTime())?"":e.toLocaleDateString()}return""}function Se(r){if(!r)return-1;const e=r.getAttribute("data-row");if(e)return parseInt(e,10);const t=r.closest(".data-grid-row");if(!t)return-1;const i=t.parentElement;if(!i)return-1;const n=i.querySelectorAll(":scope > .data-grid-row");for(let o=0;o<n.length;o++)if(n[o]===t)return o;return-1}function Cn(r){if(!r)return-1;const e=r.getAttribute("data-col");return e?parseInt(e,10):-1}function ge(r){r&&r.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function pe(r){try{if(getComputedStyle(r).direction==="rtl")return"rtl"}catch{}try{if(r.closest?.("[dir]")?.getAttribute("dir")==="rtl")return"rtl"}catch{}return"ltr"}function Ht(r){return pe(r)==="rtl"}function xn(r,e){return r==="left"||r==="right"?r:e==="rtl"?r==="start"?"right":"left":r==="start"?"left":"right"}function It(r,e){const t=e.renderer||e.viewRenderer;if(t)return t;if(!e.type)return;const i=r.__frameworkAdapter;if(i?.getTypeDefault){const n=i.getTypeDefault(e.type);if(n?.renderer)return n.renderer}}function Dt(r,e){if(e.format)return e.format;if(!e.type)return;const t=r.__frameworkAdapter;if(t?.getTypeDefault){const i=t.getTypeDefault(e.type);if(i?.format)return i.format}}const V='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function Ge(r){return(r.__editingCellCount??0)>0}function Be(r){r.__editingCellCount=0,r.removeAttribute("data-has-editing"),r.querySelectorAll(".cell.editing").forEach(t=>t.classList.remove("editing"))}const Mt=document.createElement("template");Mt.innerHTML='<div class="cell" role="gridcell" part="cell"></div>';const zt=document.createElement("template");zt.innerHTML='<div class="data-grid-row" role="row" part="row"></div>';function En(){return Mt.content.firstElementChild.cloneNode(!0)}function Rn(){return zt.content.firstElementChild.cloneNode(!0)}function re(r){r.__cellDisplayCache=void 0,r.__cellCacheEpoch=void 0,r.__hasSpecialColumns=void 0}function Sn(r,e,t,i,n){const o=Math.max(0,t-e),s=r._bodyEl,l=r._visibleColumns,a=l.length;let c=r.__cachedHeaderRowCount;for(c===void 0&&(c=r.querySelector(".header-group-row")?2:1,r.__cachedHeaderRowCount=c);r._rowPool.length<o;){const h=Rn();r._rowPool.push(h)}if(r._rowPool.length>o){for(let h=o;h<r._rowPool.length;h++){const p=r._rowPool[h];p.parentNode===s&&p.remove()}r._rowPool.length=o}const d=n&&r.__hasRenderRowPlugins!==!1,u=r._hasAfterRowRenderHook?.()??!1;for(let h=0;h<o;h++){const p=e+h,g=r._rows[p],f=r._rowPool[h];if(f.setAttribute("aria-rowindex",String(p+c+1)),d&&n(g,f,p)){f.__epoch=i,f.__rowDataRef=g,f.parentNode!==s&&s.appendChild(f);continue}const w=f.__epoch,y=f.__rowDataRef;let b=f.children.length;b>a&&f.lastElementChild?.classList.contains("tbw-row-loading-overlay")&&b--;const T=w===i&&b===a,A=y!==g,C=!!r._isGridEditMode;let v=!1;if(T&&A){for(let x=0;x<a;x++)if(l[x].externalView&&!f.querySelector(`.cell[data-col="${x}"] [data-external-view]`)){v=!0;break}}if(!T||v){const x=Ge(f),R=C||r._activeEditRows===p;x&&!R?(f.__isCustomRow&&(f.className="data-grid-row",f.setAttribute("role","row"),f.__isCustomRow=!1),Be(f),we(r,f,g,p),f.__epoch=i,f.__rowDataRef=g):x&&R?($e(r,f,g,p),f.__rowDataRef=g):(f.__isCustomRow&&(f.className="data-grid-row",f.setAttribute("role","row"),f.__isCustomRow=!1),we(r,f,g,p),f.__epoch=i,f.__rowDataRef=g)}else if(A){const x=Ge(f),R=C||r._activeEditRows===p;x&&!R?(Be(f),we(r,f,g,p),f.__epoch=i,f.__rowDataRef=g):($e(r,f,g,p),f.__rowDataRef=g)}else{const x=Ge(f),R=C||r._activeEditRows===p;x&&!R?(Be(f),we(r,f,g,p),f.__epoch=i,f.__rowDataRef=g):$e(r,f,g,p)}let E=!1;const m=r.changedRowIds;if(m&&m.length>0)try{const x=r.getRowId?.(g);x&&(E=m.includes(x))}catch{}const k=f.classList.contains("changed");E!==k&&f.classList.toggle("changed",E);const F=r.effectiveConfig?.rowClass;if(F){const x=f.getAttribute("data-dynamic-classes");x&&x.split(" ").forEach(R=>R&&f.classList.remove(R));try{const R=F(g);if(R&&R.length>0){const I=R.filter(P=>P&&typeof P=="string");I.forEach(P=>f.classList.add(P)),f.setAttribute("data-dynamic-classes",I.join(" "))}else f.removeAttribute("data-dynamic-classes")}catch(R){console.warn("[tbw-grid] rowClass callback error:",R),f.removeAttribute("data-dynamic-classes")}}u&&r._afterRowRender?.({row:g,rowIndex:p,rowElement:f}),f.parentNode!==s&&s.appendChild(f)}}function $e(r,e,t,i){const n=e.children,o=r._visibleColumns,s=o.length,l=n.length,a=s<l?s:l,c=r._focusRow,d=r._focusCol,u=r._hasAfterCellRenderHook?.()??!1;let h=r.__hasSpecialColumns;if(h===void 0){h=!1;const g=r.__frameworkAdapter;for(let f=0;f<s;f++){const w=o[f];if(w.__viewTemplate||w.__compiledView||w.renderer||w.viewRenderer||w.externalView||w.format||w.type==="date"||w.type==="boolean"||w.type&&g?.getTypeDefault?.(w.type)?.renderer||w.type&&g?.getTypeDefault?.(w.type)?.format){h=!0;break}}r.__hasSpecialColumns=h}const p=String(i);if(!h){for(let g=0;g<a;g++){const f=n[g];if(f.classList.contains("editing"))continue;f.firstElementChild&&r.__frameworkAdapter?.releaseCell?.(f);const w=o[g],y=t[w.field];f.textContent=y==null?"":String(y),f.getAttribute("data-row")!==p&&f.setAttribute("data-row",p);const b=c===i&&d===g,_=f.classList.contains("cell-focus");b!==_&&(f.classList.toggle("cell-focus",b),f.setAttribute("aria-selected",String(b))),u&&r._afterCellRender?.({row:t,rowIndex:i,column:w,colIndex:g,value:y,cellElement:f,rowElement:e})}return}for(let g=0;g<a;g++)if(o[g].externalView&&!n[g].querySelector("[data-external-view]")){we(r,e,t,i);return}for(let g=0;g<a;g++){const f=o[g],w=n[g];w.getAttribute("data-row")!==p&&w.setAttribute("data-row",p);const y=c===i&&d===g,b=w.classList.contains("cell-focus");y!==b&&(w.classList.toggle("cell-focus",y),w.setAttribute("aria-selected",String(y)));const _=f.cellClass;if(_){const E=w.getAttribute("data-dynamic-classes");E&&E.split(" ").forEach(m=>m&&w.classList.remove(m));try{const m=t[f.field],k=_(m,t,f);if(k&&k.length>0){const F=k.filter(x=>x&&typeof x=="string");F.forEach(x=>w.classList.add(x)),w.setAttribute("data-dynamic-classes",F.join(" "))}else w.removeAttribute("data-dynamic-classes")}catch(m){console.warn(`[tbw-grid] cellClass callback error for column '${f.field}':`,m),w.removeAttribute("data-dynamic-classes")}}if(w.classList.contains("editing"))continue;const T=It(r,f);if(T){const E=t[f.field],m=T({row:t,value:E,field:f.field,column:f,cellEl:w});typeof m=="string"?(r.__frameworkAdapter?.releaseCell?.(w),w.innerHTML=U(m)):m instanceof Node?m.parentElement!==w&&(r.__frameworkAdapter?.releaseCell?.(w),w.innerHTML="",w.appendChild(m)):m==null&&(r.__frameworkAdapter?.releaseCell?.(w),w.textContent=E==null?"":String(E)),u&&r._afterCellRender?.({row:t,rowIndex:i,column:f,colIndex:g,value:E,cellElement:w,rowElement:e});continue}if(f.__compiledView){const E=t[f.field],m=f.__compiledView({row:t,value:E,field:f.field,column:f});f.__compiledView.__blocked?w.textContent="":(w.firstElementChild&&r.__frameworkAdapter?.releaseCell?.(w),w.innerHTML=U(m),Ne(w)),u&&r._afterCellRender?.({row:t,rowIndex:i,column:f,colIndex:g,value:E,cellElement:w,rowElement:e});continue}if(f.__viewTemplate){const E=t[f.field],m=f.__viewTemplate.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(m)?w.textContent="":(w.firstElementChild&&r.__frameworkAdapter?.releaseCell?.(w),w.innerHTML=U(fe(m,{row:t,value:E})),Ne(w)),u&&r._afterCellRender?.({row:t,rowIndex:i,column:f,colIndex:g,value:E,cellElement:w,rowElement:e});continue}if(f.externalView)continue;const A=t[f.field];let C;const v=Dt(r,f);if(v){try{const E=v(A,t);C=E==null?"":String(E)}catch(E){console.warn(`[tbw-grid] Format error in column '${f.field}':`,E),C=A==null?"":String(A)}w.textContent=C}else f.type==="date"?(C=Pt(A),w.textContent=C):f.type==="boolean"?w.innerHTML=Lt(!!A):(C=A==null?"":String(A),w.textContent=C);u&&r._afterCellRender?.({row:t,rowIndex:i,column:f,colIndex:g,value:A,cellElement:w,rowElement:e})}}function we(r,e,t,i){e.classList.remove("tbw-row-loading"),e.removeAttribute("aria-busy");const n=r.__frameworkAdapter;if(n?.releaseCell){const h=e.children;for(let p=h.length-1;p>=0;p--)n.releaseCell(h[p])}e.innerHTML="";const o=r._visibleColumns,s=o.length,l=r._focusRow,a=r._focusCol,c=r,d=r._hasAfterCellRenderHook?.()??!1,u=document.createDocumentFragment();for(let h=0;h<s;h++){const p=o[h],g=En();g.setAttribute("aria-colindex",String(h+1)),g.setAttribute("data-col",String(h)),g.setAttribute("data-row",String(i)),g.setAttribute("data-field",p.field),g.setAttribute("data-header",p.header??p.field),p.type&&g.setAttribute("data-type",p.type);let f=t[p.field];const w=Dt(r,p);if(w)try{f=w(f,t)}catch(v){console.warn(`[tbw-grid] Format error in column '${p.field}':`,v)}const y=p.__compiledView,b=p.__viewTemplate,_=It(r,p),T=p.externalView;let A=!1;if(_){const v=_({row:t,value:f,field:p.field,column:p,cellEl:g});typeof v=="string"?(g.innerHTML=U(v),A=!0):v instanceof Node?v.parentElement!==g&&(g.textContent="",g.appendChild(v)):v==null&&(g.textContent=f==null?"":String(f))}else if(T){const v=T,E=document.createElement("div");E.setAttribute("data-external-view",""),E.setAttribute("data-field",p.field),g.appendChild(E);const m={row:t,value:f,field:p.field,column:p};if(v.mount)try{v.mount({placeholder:E,context:m,spec:v})}catch(k){console.warn(`[tbw-grid] External view mount error for column '${p.field}':`,k)}else queueMicrotask(()=>{try{c.dispatchEvent(new CustomEvent("mount-external-view",{bubbles:!0,composed:!0,detail:{placeholder:E,spec:v,context:m}}))}catch(k){console.warn(`[tbw-grid] External view event dispatch error for column '${p.field}':`,k)}});E.setAttribute("data-mounted","")}else if(y){const v=y({row:t,value:f,field:p.field,column:p}),E=y.__blocked;g.innerHTML=E?"":U(v),A=!0,E&&(g.textContent="",g.setAttribute("data-blocked-template",""))}else if(b){const v=b.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(v)?(g.textContent="",g.setAttribute("data-blocked-template","")):(g.innerHTML=U(fe(v,{row:t,value:f})),A=!0)}else w?g.textContent=f==null?"":String(f):p.type==="date"?g.textContent=Pt(f):p.type==="boolean"?g.innerHTML=Lt(!!f):g.textContent=f==null?"":String(f);if(A){Ne(g);const v=g.textContent||"";/Proxy|Reflect\.ownKeys/.test(v)&&(g.textContent=v.replace(/Proxy|Reflect\.ownKeys/g,"").trim(),/Proxy|Reflect\.ownKeys/.test(g.textContent||"")&&(g.textContent=""))}g.hasAttribute("data-blocked-template")&&(g.textContent||"").trim().length&&(g.textContent=""),p.editable?g.tabIndex=0:p.type==="boolean"&&(g.hasAttribute("tabindex")||(g.tabIndex=0)),l===i&&a===h?(g.classList.add("cell-focus"),g.setAttribute("aria-selected","true")):g.setAttribute("aria-selected","false");const C=p.cellClass;if(C)try{const v=t[p.field],E=C(v,t,p);if(E&&E.length>0){const m=E.filter(k=>k&&typeof k=="string");m.forEach(k=>g.classList.add(k)),g.setAttribute("data-dynamic-classes",m.join(" "))}}catch(v){console.warn(`[tbw-grid] cellClass callback error for column '${p.field}':`,v)}d&&r._afterCellRender?.({row:t,rowIndex:i,column:p,colIndex:h,value:f,cellElement:g,rowElement:e}),u.appendChild(g)}e.appendChild(u)}function Ot(r,e,t){if(e.target?.closest(".resize-handle"))return;const i=t.querySelector(".cell[data-row]"),n=Se(i);if(n<0)return;const o=r._rows[n];if(!o||r._dispatchRowClick?.(e,n,o,t))return;const s=e.target?.closest(".cell[data-col]");if(s){const l=Number(s.getAttribute("data-col"));if(!isNaN(l)){if(r._dispatchCellClick?.(e,n,l,s))return;const a=r._focusRow!==n||r._focusCol!==l;if(r._focusRow=n,r._focusCol=l,s.classList.contains("editing")){a&&(ge(r._bodyEl??r),s.classList.add("cell-focus"));const c=s.querySelector(V);try{c?.focus({preventScroll:!0})}catch{}return}N(r)}}}function _n(r,e){if(r._dispatchKeyDown?.(e))return;const t=r._rows.length-1,i=r._visibleColumns.length-1,n=r._activeEditRows!==void 0&&r._activeEditRows!==-1,s=r._visibleColumns[r._focusCol]?.type,l=e.composedPath?.()??[],a=l.length?l[0]:e.target,c=d=>{if(!d)return!1;const u=d.tagName;return!!(u==="INPUT"||u==="SELECT"||u==="TEXTAREA"||d.isContentEditable)};if(!(c(a)&&(e.key==="Home"||e.key==="End"))&&!(c(a)&&(e.key==="ArrowUp"||e.key==="ArrowDown")&&a.tagName==="INPUT"&&a.type==="number")&&!(c(a)&&(e.key==="ArrowLeft"||e.key==="ArrowRight"))&&!(c(a)&&(e.key==="Enter"||e.key==="Escape"))&&!(n&&s==="select"&&(e.key==="ArrowDown"||e.key==="ArrowUp"))){switch(e.key){case"Tab":{e.preventDefault(),!e.shiftKey?r._focusCol<i?r._focusCol+=1:(typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow<t&&(r._focusRow+=1,r._focusCol=0)):r._focusCol>0?r._focusCol-=1:r._focusRow>0&&(typeof r.commitActiveRowEdit=="function"&&r._activeEditRows===r._focusRow&&r.commitActiveRowEdit(),r._focusRow-=1,r._focusCol=i),N(r);return}case"ArrowDown":n&&typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow=Math.min(t,r._focusRow+1),e.preventDefault();break;case"ArrowUp":n&&typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow=Math.max(0,r._focusRow-1),e.preventDefault();break;case"ArrowRight":{Ht(r)?r._focusCol=Math.max(0,r._focusCol-1):r._focusCol=Math.min(i,r._focusCol+1),e.preventDefault();break}case"ArrowLeft":{Ht(r)?r._focusCol=Math.min(i,r._focusCol+1):r._focusCol=Math.max(0,r._focusCol-1),e.preventDefault();break}case"Home":(e.ctrlKey||e.metaKey)&&(n&&typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow=0),r._focusCol=0,e.preventDefault(),N(r,{forceScrollLeft:!0});return;case"End":(e.ctrlKey||e.metaKey)&&(n&&typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow=t),r._focusCol=i,e.preventDefault(),N(r,{forceScrollRight:!0});return;case"PageDown":r._focusRow=Math.min(t,r._focusRow+20),e.preventDefault();break;case"PageUp":r._focusRow=Math.max(0,r._focusRow-20),e.preventDefault();break;case"Enter":{const d=r._focusRow,u=r._focusCol,h=r._visibleColumns[u],p=r._rows[d],g=h?.field??"",f=g&&p?p[g]:void 0,w=r.querySelector(`[data-row="${d}"][data-col="${u}"]`),y={rowIndex:d,colIndex:u,column:h,field:g,value:f,row:p,cellEl:w,trigger:"keyboard",originalEvent:e},b=new CustomEvent("cell-activate",{cancelable:!0,detail:y});r.dispatchEvent(b);const _=new CustomEvent("activate-cell",{cancelable:!0,detail:{row:d,col:u}});if(r.dispatchEvent(_),b.defaultPrevented||_.defaultPrevented){e.preventDefault();return}break}default:return}N(r)}}function N(r,e){if(r._virtualization?.enabled){const{rowHeight:s,container:l,viewportEl:a}=r._virtualization,c=l,d=a?.clientHeight??c?.clientHeight??0;if(c&&d>0){const u=r._focusRow*s;u<c.scrollTop?c.scrollTop=u:u+s>c.scrollTop+d&&(c.scrollTop=u-d+s)}}const t=r._activeEditRows!==void 0&&r._activeEditRows!==-1;t||r.refreshVirtualWindow(!1),ge(r._bodyEl),Array.from(r._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(s=>{s.setAttribute("aria-selected","false")});const i=r._focusRow,n=r._virtualization.start??0,o=r._virtualization.end??r._rows.length;if(i>=n&&i<o){const s=r._bodyEl.querySelectorAll(".data-grid-row")[i-n];let l=s?.children[r._focusCol];if((!l||!l.classList?.contains("cell"))&&(l=s?.querySelector(`.cell[data-col="${r._focusCol}"]`)??s?.querySelector(".cell[data-col]")),l){l.classList.add("cell-focus"),l.setAttribute("aria-selected","true");const a=r.querySelector(".tbw-scroll-area");if(a&&l&&(!t||e?.forceHorizontalScroll))if(e?.forceScrollLeft)a.scrollLeft=0;else if(e?.forceScrollRight)a.scrollLeft=a.scrollWidth-a.clientWidth;else{const c=r._getHorizontalScrollOffsets?.(s??void 0,l)??{left:0,right:0};if(!c.skipScroll){const d=l.getBoundingClientRect(),u=a.getBoundingClientRect(),h=d.left-u.left+a.scrollLeft,p=h+d.width,g=a.scrollLeft+c.left,f=a.scrollLeft+a.clientWidth-c.right;h<g?a.scrollLeft=h-c.left:p>f&&(a.scrollLeft=p-a.clientWidth+c.right)}}if(t&&l.classList.contains("editing")){const c=l.querySelector(V);if(c&&document.activeElement!==c)try{c.focus({preventScroll:!0})}catch{}}else if(t&&!l.contains(document.activeElement)){l.hasAttribute("tabindex")||l.setAttribute("tabindex","-1");try{l.focus({preventScroll:!0})}catch{}}else if(!t){const c=r;document.activeElement!==c&&c.focus({preventScroll:!0})}}}}const _e=new WeakMap;function An(r,e){const t=Se(e),i=Cn(e);if(t<0||i<0)return;r._focusRow=t,r._focusCol=i,ge(r._bodyEl),e.classList.add("cell-focus"),e.setAttribute("aria-selected","true");const n=e.closest("tbw-grid");n&&document.activeElement!==n&&n.focus({preventScroll:!0})}function We(r,e,t,i){let n=null;const o=t.composedPath?.();if(o&&o.length>0?n=o[0]:n=t.target,n&&!e.contains(n)){const f=document.elementFromPoint(t.clientX,t.clientY);f&&(n=f)}const s=n?.closest?.("[data-col]"),l=n?.closest?.(".data-grid-row"),a=n?.closest?.(".header-row");let c,d,u,h,p,g;return s&&(c=parseInt(s.getAttribute("data-row")??"-1",10),d=parseInt(s.getAttribute("data-col")??"-1",10),c>=0&&d>=0&&(u=r._rows[c],g=r._visibleColumns[d],h=g?.field,p=u&&h?u[h]:void 0)),{type:i,row:u,rowIndex:c!==void 0&&c>=0?c:void 0,colIndex:d!==void 0&&d>=0?d:void 0,field:h,value:p,column:g,originalEvent:t,cellElement:s??void 0,rowElement:l??void 0,isHeader:!!a,cell:c!==void 0&&d!==void 0&&c>=0&&d>=0?{row:c,col:d}:void 0}}function kn(r,e,t){const i=We(r,e,t,"mousedown");(r._dispatchCellMouseDown?.(i)??!1)&&_e.set(r,!0)}function Tn(r,e,t){if(!_e.get(r))return;const i=We(r,e,t,"mousemove");r._dispatchCellMouseMove?.(i)}function Ln(r,e,t){if(!_e.get(r))return;const i=We(r,e,t,"mouseup");r._dispatchCellMouseUp?.(i),_e.set(r,!1)}function Pn(r,e,t){e.addEventListener("mousedown",i=>{const n=i.target.closest(".cell[data-col]");n&&(n.classList.contains("editing")||(i.preventDefault(),An(r,n)))},{signal:t}),e.addEventListener("click",i=>{const n=i.target.closest(".data-grid-row");if(n&&Ot(r,i,n),!document.activeElement?.closest(".cell.editing")){const o=i.target.closest("tbw-grid");o&&o.focus({preventScroll:!0})}},{signal:t}),e.addEventListener("dblclick",i=>{const n=i.target.closest(".data-grid-row");n&&Ot(r,i,n)},{signal:t})}function Hn(r,e,t,i){e.addEventListener("keydown",n=>_n(r,n),{signal:i}),t.addEventListener("mousedown",n=>kn(r,t,n),{signal:i}),document.addEventListener("mousemove",n=>Tn(r,t,n),{signal:i}),document.addEventListener("mouseup",n=>Ln(r,t,n),{signal:i})}function Ft(r,e){return r==null&&e==null?0:r==null?-1:e==null||r>e?1:r<e?-1:0}function Ke(r,e,t){const n=t.find(l=>l.field===e.field)?.sortComparator??Ft,{field:o,direction:s}=e;return[...r].sort((l,a)=>n(l[o],a[o],l,a)*s)}function Nt(r,e,t,i){r._rows=e,r.__rowRenderEpoch++,r._rowPool.forEach(n=>n.__epoch=-1),Pe(r),r.refreshVirtualWindow(!0),r.dispatchEvent(new CustomEvent("sort-change",{detail:{field:t.field,direction:i}})),r.requestStateChange?.()}function qt(r,e){!r._sortState||r._sortState.field!==e.field?(r._sortState||(r.__originalOrder=r._rows.slice()),Gt(r,e,1)):r._sortState.direction===1?Gt(r,e,-1):(r._sortState=null,r.__rowRenderEpoch++,r._rowPool.forEach(i=>i.__epoch=-1),r._rows=r.__originalOrder.slice(),Pe(r),r._headerRowEl?.querySelectorAll('[role="columnheader"].sortable')?.forEach(i=>{i.getAttribute("aria-sort")?(i.getAttribute("aria-sort")==="ascending"||i.getAttribute("aria-sort")==="descending")&&(r._sortState||i.setAttribute("aria-sort","none")):i.setAttribute("aria-sort","none")}),r.refreshVirtualWindow(!0),r.dispatchEvent(new CustomEvent("sort-change",{detail:{field:e.field,direction:0}})),r.requestStateChange?.())}function In(r,e){if(!r._sortState)return e;r.__originalOrder=[...e];const i=(r.effectiveConfig?.sortHandler??Ke)(e,r._sortState,r._columns);return i&&typeof i.then=="function"?e:i}function Gt(r,e,t){r._sortState={field:e.field,direction:t};const i={field:e.field,direction:t},n=r._columns,s=(r.effectiveConfig?.sortHandler??Ke)(r._rows,i,n);s&&typeof s.then=="function"?s.then(l=>{Nt(r,l,e,t)}):Nt(r,s,e,t)}function me(r,e){return r.effectiveConfig?.sortable!==!1&&e.sortable===!0}function Ae(r,e){return r.effectiveConfig?.resizable!==!1&&e.resizable!==!1}function Dn(r,e){typeof e=="string"?r.textContent=e:e instanceof HTMLElement&&(r.innerHTML="",r.appendChild(e.cloneNode(!0)))}function ke(r,e){const t=document.createElement("span");St(t,"sort-indicator");const i=r._sortState?.field===e.field?r._sortState.direction:0,n={...K,...r.icons},o=i===1?n.sortAsc:i===-1?n.sortDesc:n.sortNone;return Dn(t,o),t}function Te(r,e,t){const i=document.createElement("div");return i.className="resize-handle",i.setAttribute("aria-hidden","true"),i.addEventListener("mousedown",n=>{n.stopPropagation(),n.preventDefault(),r._resizeController.start(n,e,t)}),i.addEventListener("dblclick",n=>{n.stopPropagation(),n.preventDefault(),r._resizeController.resetColumn(e)}),i}function Le(r,e,t,i){i.classList.add("sortable"),i.tabIndex=0;const n=r._sortState?.field===e.field?r._sortState.direction:0;i.setAttribute("aria-sort",n===0?"none":n===1?"ascending":"descending"),i.addEventListener("click",o=>{r._resizeController?.isResizing||r._dispatchHeaderClick?.(o,e,i)||qt(r,e)}),i.addEventListener("keydown",o=>{if(o.key==="Enter"||o.key===" "){if(o.preventDefault(),r._dispatchHeaderClick?.(o,e,i))return;qt(r,e)}})}function Mn(r,e){if(e!=null)if(typeof e=="string"){const t=document.createElement("span");for(t.innerHTML=U(e);t.firstChild;)r.appendChild(t.firstChild)}else e instanceof Node&&r.appendChild(e)}function Pe(r){r._headerRowEl=r.findHeaderRow();const e=r._headerRowEl;e&&(e.innerHTML="",r._visibleColumns.forEach((t,i)=>{const n=document.createElement("div");n.className="cell",St(n,"header-cell"),n.setAttribute("role","columnheader"),n.setAttribute("aria-colindex",String(i+1)),n.setAttribute("data-field",t.field),n.setAttribute("data-col",String(i)),t.type&&n.setAttribute("data-type",t.type);const o=t.header??t.field,s=r._sortState?.field===t.field?r._sortState.direction:0,l=s===1?"asc":s===-1?"desc":null;if(t.headerRenderer){const a={column:t,value:o,sortState:l,filterActive:!1,cellEl:n,renderSortIcon:()=>me(r,t)?ke(r,t):null,renderFilterButton:()=>null},c=t.headerRenderer(a);Mn(n,c),me(r,t)&&Le(r,t,i,n),Ae(r,t)&&(n.classList.add("resizable"),n.appendChild(Te(r,i,n)))}else if(t.headerLabelRenderer){const a={column:t,value:o},c=t.headerLabelRenderer(a),d=document.createElement("span");c==null?d.textContent=o:typeof c=="string"?d.innerHTML=U(c):c instanceof Node&&d.appendChild(c),n.appendChild(d),me(r,t)&&(Le(r,t,i,n),n.appendChild(ke(r,t))),Ae(r,t)&&(n.classList.add("resizable"),n.appendChild(Te(r,i,n)))}else if(t.__headerTemplate)Array.from(t.__headerTemplate.childNodes).forEach(a=>n.appendChild(a.cloneNode(!0))),me(r,t)&&(Le(r,t,i,n),n.appendChild(ke(r,t))),Ae(r,t)&&(n.classList.add("resizable"),n.appendChild(Te(r,i,n)));else{const a=document.createElement("span");a.textContent=o,n.appendChild(a),me(r,t)&&(Le(r,t,i,n),n.appendChild(ke(r,t))),Ae(r,t)&&(n.classList.add("resizable"),n.appendChild(Te(r,i,n)))}e.appendChild(n)}),e.querySelectorAll(".cell.sortable").forEach(t=>{t.getAttribute("aria-sort")||t.setAttribute("aria-sort","none")}),e.children.length>0?(e.setAttribute("role","row"),e.setAttribute("aria-rowindex","1")):(e.removeAttribute("role"),e.removeAttribute("aria-rowindex")))}const Bt=typeof requestIdleCallback=="function";function zn(r,e){return Bt?requestIdleCallback(r,e):window.setTimeout(()=>{const t=Date.now();r({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})},1)}function $t(r){Bt?cancelIdleCallback(r):clearTimeout(r)}function On(r){const e=document.createElement("div");return e.className=`tbw-spinner tbw-spinner--${r}`,e.setAttribute("role","progressbar"),e.setAttribute("aria-label","Loading"),e}function Fn(r,e){if(e){const i=e({size:r});if(typeof i=="string"){const n=document.createElement("div");return n.innerHTML=i,n}return i}return On(r)}function Nn(r){const e=document.createElement("div");return e.className="tbw-loading-overlay",e.setAttribute("role","status"),e.setAttribute("aria-live","polite"),e.appendChild(Fn("large",r)),e}function qn(r,e){r.appendChild(e)}function Gn(r){r?.remove()}function Bn(r,e){if(e){if(r.classList.add("tbw-row-loading"),r.setAttribute("aria-busy","true"),!r.querySelector(".tbw-row-loading-overlay")){const t=document.createElement("div");t.className="tbw-row-loading-overlay",t.setAttribute("aria-hidden","true");const i=document.createElement("div");i.className="tbw-row-loading-spinner",t.appendChild(i),r.appendChild(t)}}else r.classList.remove("tbw-row-loading"),r.removeAttribute("aria-busy"),r.querySelector(".tbw-row-loading-overlay")?.remove()}function $n(r,e){e?(r.classList.add("tbw-cell-loading"),r.setAttribute("aria-busy","true")):(r.classList.remove("tbw-cell-loading"),r.removeAttribute("aria-busy"))}var O=(r=>(r[r.STYLE=1]="STYLE",r[r.VIRTUALIZATION=2]="VIRTUALIZATION",r[r.HEADER=3]="HEADER",r[r.ROWS=4]="ROWS",r[r.COLUMNS=5]="COLUMNS",r[r.FULL=6]="FULL",r))(O||{});class Wn{#t;#e=0;#u=0;#c=null;#r=null;#l=null;#i=!1;constructor(e){this.#t=e}requestPhase(e,t){e>this.#e&&(this.#e=e),this.#u===0&&(this.#h(),this.#u=requestAnimationFrame(()=>this.#w()))}whenReady(){return this.#c?this.#c:Promise.resolve()}setInitialReadyResolver(e){this.#l=e}cancel(){this.#u!==0&&(cancelAnimationFrame(this.#u),this.#u=0),this.#e=0,this.#r&&(this.#r(),this.#r=null,this.#c=null)}get isPending(){return this.#e!==0}get pendingPhase(){return this.#e}#h(){this.#c||(this.#c=new Promise(e=>{this.#r=e}))}#w(){if(this.#u=0,!this.#t.isConnected()){this.#e=0,this.#r&&(this.#r(),this.#r=null,this.#c=null);return}const e=this.#e;this.#e=0,e>=5&&this.#t.mergeConfig(),e>=4&&this.#t.processRows(),e>=5&&(this.#t.processColumns(),this.#t.updateTemplate()),e>=3&&this.#t.renderHeader(),e>=2&&this.#t.renderVirtualWindow(),e>=1&&this.#t.afterRender(),!this.#i&&this.#l&&(this.#i=!0,this.#l()),this.#r&&(this.#r(),this.#r=null,this.#c=null)}}function Wt(r){let e=null,t=null,i=null,n=null;const o=a=>{if(!e)return;const c=a.clientX-e.startX,d=Math.max(40,e.startWidth+c),u=r._visibleColumns[e.colIndex];u.width=d,u.__userResized=!0,u.__renderedWidth=d,t==null&&(t=requestAnimationFrame(()=>{t=null,r.updateTemplate?.()})),r.dispatchEvent(new CustomEvent("column-resize",{detail:{field:u.field,width:d}}))};let s=!1;const l=()=>{const a=e!==null;a&&(s=!0,requestAnimationFrame(()=>{s=!1})),window.removeEventListener("mousemove",o),window.removeEventListener("mouseup",l),i!==null&&(document.documentElement.style.cursor=i,i=null),n!==null&&(document.body.style.userSelect=n,n=null),e=null,a&&r.requestStateChange&&r.requestStateChange()};return{get isResizing(){return e!==null||s},start(a,c,d){a.preventDefault();const u=r._visibleColumns[c],h=typeof u?.width=="number"?u.width:void 0,p=u?.__renderedWidth??h??d.getBoundingClientRect().width;e={startX:a.clientX,colIndex:c,startWidth:p},window.addEventListener("mousemove",o),window.addEventListener("mouseup",l),i===null&&(i=document.documentElement.style.cursor),document.documentElement.style.cursor="e-resize",n===null&&(n=document.body.style.userSelect),document.body.style.userSelect="none"},resetColumn(a){const c=r._visibleColumns[a];c&&(c.__userResized=!1,c.__renderedWidth=void 0,c.width=c.__originalWidth,r.updateTemplate?.(),r.requestStateChange?.(),r.dispatchEvent(new CustomEvent("column-resize-reset",{detail:{field:c.field,width:c.width}})))},dispose(){l()}}}const Ve="data-animating",Kn={change:"--tbw-row-change-duration",insert:"--tbw-row-insert-duration",remove:"--tbw-row-remove-duration"},Vn={change:500,insert:300,remove:200};function Un(r){const e=r.trim().toLowerCase();return e.endsWith("ms")?parseFloat(e):e.endsWith("s")?parseFloat(e)*1e3:parseFloat(e)}function jn(r,e){const t=Kn[e],i=getComputedStyle(r).getPropertyValue(t);if(i){const n=Un(i);if(!isNaN(n)&&n>0)return n}return Vn[e]}function Yn(r,e,t){r.removeAttribute(Ve),r.offsetWidth,r.setAttribute(Ve,e);const i=jn(r,e);setTimeout(()=>{e!=="remove"&&r.removeAttribute(Ve),t?.()},i)}function Ue(r,e,t){if(e<0)return Promise.resolve(!1);const i=r.findRenderedRowElement?.(e);return i?new Promise(n=>{Yn(i,t,()=>n(!0))}):Promise.resolve(!1)}function Xn(r,e,t){return Promise.all(e.map(i=>Ue(r,i,t))).then(i=>i.filter(Boolean).length)}function Qn(r,e,t){const i=r._rows??[],n=r.getRowId;if(!n)return Promise.resolve(!1);const o=i.findIndex(s=>{if(s==null)return!1;try{return n(s)===e}catch{return!1}});return o<0?Promise.resolve(!1):Ue(r,o,t)}function He(r,e,t){const i=document.createElement(r);if(e)for(const n in e){const o=e[n];o!=null&&i.setAttribute(n,o)}return i}function G(r,e){const t=document.createElement("div");if(r&&(t.className=r),e)for(const i in e){const n=e[i];n!=null&&t.setAttribute(i,n)}return t}function Kt(r,e,t){const i=document.createElement("button");if(r&&(i.className=r),e)for(const n in e){const o=e[n];o!=null&&i.setAttribute(n,o)}return i}const Vt=document.createElement("template");Vt.innerHTML=`
2
- <div class="tbw-scroll-area">
3
- <div class="rows-body-wrapper">
4
- <div class="rows-body" role="grid">
5
- <div class="header" role="rowgroup">
6
- <div class="header-row" role="row" part="header-row"></div>
7
- </div>
8
- <div class="rows-container" role="presentation">
9
- <div class="rows-viewport" role="presentation">
10
- <div class="rows"></div>
11
- </div>
12
- </div>
13
- </div>
14
- </div>
15
- </div>
16
- <div class="faux-vscroll">
17
- <div class="faux-vscroll-spacer"></div>
18
- </div>
19
- `;function Ut(){return Vt.content.cloneNode(!0)}function jt(r){const e=document.createDocumentFragment(),t=G(r.hasShell?"tbw-grid-root has-shell":"tbw-grid-root");if(r.hasShell&&r.shellHeader&&r.shellBody)t.appendChild(r.shellHeader),t.appendChild(r.shellBody);else{const i=G("tbw-grid-content");i.appendChild(Ut()),t.appendChild(i)}return e.appendChild(t),e}function Zn(r){const e=G("tbw-shell-header",{part:"shell-header",role:"presentation"});if(r.title){const o=G("tbw-shell-title");o.textContent=r.title,e.appendChild(o)}const t=G("tbw-shell-content",{part:"shell-content",role:"presentation","data-light-dom-header-content":""});e.appendChild(t);const i=G("tbw-shell-toolbar",{part:"shell-toolbar",role:"presentation"});for(const o of r.configButtons)o.hasRender&&i.appendChild(G("tbw-toolbar-content-slot",{"data-toolbar-content":o.id}));for(const o of r.apiButtons)o.hasRender&&i.appendChild(G("tbw-toolbar-content-slot",{"data-toolbar-content":o.id}));if((r.configButtons.some(o=>o.hasRender)||r.apiButtons.some(o=>o.hasRender))&&r.hasPanels&&i.appendChild(G("tbw-toolbar-separator")),r.hasPanels){const o=Kt(r.isPanelOpen?"tbw-toolbar-btn active":"tbw-toolbar-btn",{"data-panel-toggle":"",title:"Settings","aria-label":"Toggle settings panel","aria-pressed":String(r.isPanelOpen),"aria-controls":"tbw-tool-panel"});o.innerHTML=r.toolPanelIcon,i.appendChild(o)}return e.appendChild(i),e}function Jn(r){const e=G("tbw-shell-body"),t=r.panels.length>0,i=r.panels.length===1,n=G("tbw-grid-content");n.appendChild(Ut());let o=null;if(t){o=He("aside",{class:r.isPanelOpen?"tbw-tool-panel open":"tbw-tool-panel",part:"tool-panel","data-position":r.position,role:"presentation",id:"tbw-tool-panel"});const s=r.position==="left"?"right":"left";o.appendChild(G("tbw-tool-panel-resize",{"data-resize-handle":"","data-handle-position":s,"aria-hidden":"true"}));const l=G("tbw-tool-panel-content",{role:"presentation"}),a=G("tbw-accordion");for(const c of r.panels){const d=`tbw-accordion-section${c.isExpanded?" expanded":""}${i?" single":""}`,u=G(d,{"data-section":c.id}),h=Kt("tbw-accordion-header",{"aria-expanded":String(c.isExpanded),"aria-controls":`tbw-section-${c.id}`});if(i&&h.setAttribute("aria-disabled","true"),c.icon){const g=He("span",{class:"tbw-accordion-icon"});g.innerHTML=c.icon,h.appendChild(g)}const p=He("span",{class:"tbw-accordion-title"});if(p.textContent=c.title,h.appendChild(p),!i){const g=He("span",{class:"tbw-accordion-chevron"});g.innerHTML=c.isExpanded?r.collapseIcon:r.expandIcon,h.appendChild(g)}u.appendChild(h),u.appendChild(G("tbw-accordion-content",{id:`tbw-section-${c.id}`,role:"presentation"})),a.appendChild(u)}l.appendChild(a),o.appendChild(l)}return r.position==="left"&&o?(e.appendChild(o),e.appendChild(n)):(e.appendChild(n),o&&e.appendChild(o)),e}function ee(r){return r?typeof r=="string"?r:r.outerHTML:""}function er(){return{toolPanels:new Map,headerContents:new Map,toolbarContents:new Map,hasToolButtonsContainer:!1,lightDomHeaderContent:[],lightDomTitle:null,lightDomToolPanelIds:new Set,lightDomToolbarContentIds:new Set,apiToolPanelIds:new Set,isPanelOpen:!1,expandedSections:new Set,headerContentCleanups:new Map,panelCleanups:new Map,toolbarContentCleanups:new Map,lightDomContentMoved:!1}}function Yt(r){return!!(r?.header?.title||r?.header?.toolbarContents?.length||r?.toolPanels?.length||r?.headerContents?.length||r?.header?.lightDomContent?.length||r?.header?.hasToolButtonsContainer)}function tr(r,e,t="☰"){const i=r?.header?.title??e.lightDomTitle??"",n=!!i,o=ee(t),s=r?.header?.toolbarContents??[],l=[...e.toolbarContents.values()],a=new Set(s.map(f=>f.id)),c=[...s];for(const f of l)a.has(f.id)||c.push(f);const d=c.length>0,u=e.toolPanels.size>0,h=d&&u,p=[...c].sort((f,w)=>(f.order??0)-(w.order??0));let g="";for(const f of p)g+=`<div class="tbw-toolbar-content-slot" data-toolbar-content="${f.id}"></div>`;if(h&&(g+='<div class="tbw-toolbar-separator"></div>'),u){const f=e.isPanelOpen;g+=`<button class="${f?"tbw-toolbar-btn active":"tbw-toolbar-btn"}" data-panel-toggle title="Settings" aria-label="Toggle settings panel" aria-pressed="${f}" aria-controls="tbw-tool-panel">${o}</button>`}return`
20
- <div class="tbw-shell-header" part="shell-header" role="presentation">
21
- ${n?`<div class="tbw-shell-title">${hn(i)}</div>`:""}
22
- <div class="tbw-shell-content" part="shell-content" role="presentation" data-light-dom-header-content></div>
23
- <div class="tbw-shell-toolbar" part="shell-toolbar" role="presentation">
24
- ${g}
25
- </div>
26
- </div>
27
- `}function Xt(r,e){const t=r.querySelector("tbw-grid-header");if(!t)return;if(!e.lightDomTitle){const n=t.getAttribute("title");n&&(e.lightDomTitle=n)}const i=t.querySelectorAll("tbw-grid-header-content");i.length>0&&e.lightDomHeaderContent.length===0&&(e.lightDomHeaderContent=Array.from(i)),t.style.display="none"}function Qt(r,e,t){const i=r.querySelector(":scope > tbw-grid-tool-buttons");if(!i)return;e.hasToolButtonsContainer=!0;const n="light-dom-toolbar-content";if(e.lightDomToolbarContentIds.has(n))return;const o={id:n,order:0,render:(s=>{for(;i.firstChild;)s.appendChild(i.firstChild);return()=>{for(;s.firstChild;)i.appendChild(s.firstChild)}})};e.toolbarContents.set(n,o),e.lightDomToolbarContentIds.add(n),i.style.display="none"}function Zt(r,e,t){r.querySelectorAll(":scope > tbw-grid-tool-panel").forEach(n=>{const o=n,s=o.getAttribute("id"),l=o.getAttribute("title");if(!s||!l){console.warn(`[parseLightDomToolPanels] Tool panel missing required id or title attribute: id="${s??""}", title="${l??""}"`);return}const a=o.getAttribute("icon")??void 0,c=o.getAttribute("tooltip")??void 0,d=parseInt(o.getAttribute("order")??"100",10);let u;const h=t?.(o);if(h)u=h;else{const f=o.innerHTML.trim();u=w=>{const y=document.createElement("div");return y.innerHTML=f,w.appendChild(y),()=>y.remove()}}const p=e.toolPanels.get(s);if(p){if(h){p.render=u,p.order=d,p.icon=a,p.tooltip=c;const f=e.panelCleanups.get(s);f&&(f(),e.panelCleanups.delete(s))}return}const g={id:s,title:l,icon:a,tooltip:c,order:d,render:u};e.toolPanels.set(s,g),e.lightDomToolPanelIds.add(s),o.style.display="none"})}function ir(r,e,t,i){const n=r.querySelector(".tbw-shell-toolbar");n&&n.addEventListener("click",s=>{if(s.target.closest("[data-panel-toggle]")){i.onPanelToggle();return}});const o=r.querySelector(".tbw-accordion");o&&o.addEventListener("click",s=>{const a=s.target.closest(".tbw-accordion-header");if(a){const d=a.closest("[data-section]")?.getAttribute("data-section");d&&i.onSectionToggle(d)}})}function nr(r,e,t,i){if(!e?.toolPanel?.closeOnClickOutside)return()=>{};const n=o=>{if(!t.isPanelOpen)return;const s=o.target;s&&(s.closest(".tbw-tool-panel")||s.closest("[data-panel-toggle]")||i())};return r.addEventListener("mousedown",n),()=>r.removeEventListener("mousedown",n)}function rr(r,e,t){const i=r.querySelector(".tbw-tool-panel"),n=r.querySelector("[data-resize-handle]"),o=r.querySelector(".tbw-shell-body");if(!i||!n||!o)return()=>{};const s=e?.toolPanel?.position??"right",l=200;let a=0,c=0,d=0,u=!1;const h=f=>{if(!u)return;f.preventDefault();const w=s==="left"?f.clientX-a:a-f.clientX,y=Math.min(d,Math.max(l,c+w));i.style.width=`${y}px`},p=()=>{if(!u)return;u=!1,n.classList.remove("resizing"),i.style.transition="",document.body.style.cursor="",document.body.style.userSelect="";const f=i.getBoundingClientRect().width;t(f),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",p)},g=f=>{f.preventDefault(),u=!0,a=f.clientX,c=i.getBoundingClientRect().width,d=o.getBoundingClientRect().width-20,n.classList.add("resizing"),i.style.transition="none",document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",h),document.addEventListener("mouseup",p)};return n.addEventListener("mousedown",g),()=>{n.removeEventListener("mousedown",g),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",p)}}function je(r,e,t){const i=e?.header?.toolbarContents??[],n=[...t.toolbarContents.values()],o=new Set(i.map(l=>l.id)),s=[...i];for(const l of n)o.has(l.id)||s.push(l);for(const l of s){if(t.toolbarContentCleanups.has(l.id)||!l.render)continue;const a=r.querySelector(`[data-toolbar-content="${l.id}"]`);if(!a)continue;const c=l.render(a);c&&t.toolbarContentCleanups.set(l.id,c)}}function Ye(r,e){const t=e.lightDomHeaderContent.length>0&&!e.lightDomContentMoved,i=e.headerContents.size>0;if(!t&&!i)return;const n=r.querySelector(".tbw-shell-content");if(!n)return;if(t){for(const s of e.lightDomHeaderContent)s.style.display="",n.appendChild(s);e.lightDomContentMoved=!0}const o=[...e.headerContents.values()].sort((s,l)=>(s.order??100)-(l.order??100));for(const s of o){const l=e.headerContentCleanups.get(s.id);l&&(l(),e.headerContentCleanups.delete(s.id));let a=n.querySelector(`[data-header-content="${s.id}"]`);a||(a=document.createElement("div"),a.setAttribute("data-header-content",s.id),n.appendChild(a));const c=s.render(a);c&&e.headerContentCleanups.set(s.id,c)}}function or(r,e,t){if(!e.isPanelOpen)return;const i=ee(t?.expand??K.expand),n=ee(t?.collapse??K.collapse);for(const[o,s]of e.toolPanels){const l=e.expandedSections.has(o),a=r.querySelector(`[data-section="${o}"]`),c=a?.querySelector(".tbw-accordion-content");if(!a||!c)continue;a.classList.toggle("expanded",l);const d=a.querySelector(".tbw-accordion-header");d&&d.setAttribute("aria-expanded",String(l));const u=a.querySelector(".tbw-accordion-chevron");if(u&&(u.innerHTML=l?n:i),l){if(c.children.length===0){const h=s.render(c);h&&e.panelCleanups.set(o,h)}}else{const h=e.panelCleanups.get(o);h&&(h(),e.panelCleanups.delete(o)),c.innerHTML=""}}}function Jt(r,e){const t=r.querySelector("[data-panel-toggle]");t&&(t.classList.toggle("active",e.isPanelOpen),t.setAttribute("aria-pressed",String(e.isPanelOpen)))}function ei(r,e){const t=r.querySelector(".tbw-tool-panel");t&&(t.classList.toggle("open",e.isPanelOpen),e.isPanelOpen||(t.style.width=""))}function Xe(r){for(const e of r.toolbarContentCleanups.values())e();r.toolbarContentCleanups.clear()}function sr(r){for(const e of r.headerContentCleanups.values())e();r.headerContentCleanups.clear();for(const e of r.panelCleanups.values())e();r.panelCleanups.clear();for(const e of r.toolbarContentCleanups.values())e();r.toolbarContentCleanups.clear();for(const e of r.toolbarContents.values())e.onDestroy?.();if(r.isPanelOpen)for(const e of r.expandedSections)r.toolPanels.get(e)?.onClose?.();r.isPanelOpen=!1,r.expandedSections.clear(),r.toolPanels.clear(),r.headerContents.clear(),r.toolbarContents.clear(),r.lightDomHeaderContent=[],r.lightDomToolPanelIds.clear(),r.lightDomToolbarContentIds.clear(),r.lightDomContentMoved=!1}function lr(r,e){let t=!1;const i={get isInitialized(){return t},setInitialized(n){t=n},get isPanelOpen(){return r.isPanelOpen},get activePanel(){return r.isPanelOpen&&r.expandedSections.size>0?[...r.expandedSections][0]:null},get expandedSections(){return[...r.expandedSections]},openToolPanel(){if(r.isPanelOpen)return;if(r.toolPanels.size===0){console.warn("[tbw-grid] No tool panels registered");return}if(r.isPanelOpen=!0,r.expandedSections.size===0&&r.toolPanels.size>0){const s=[...r.toolPanels.values()].sort((l,a)=>(l.order??100)-(a.order??100))[0];s&&r.expandedSections.add(s.id)}const n=e.getShadow();Jt(n,r),ei(n,r),or(n,r,e.getAccordionIcons()),e.emit("tool-panel-open",{sections:i.expandedSections})},closeToolPanel(){if(!r.isPanelOpen)return;for(const o of r.panelCleanups.values())o();r.panelCleanups.clear();for(const o of r.toolPanels.values())o.onClose?.();r.isPanelOpen=!1;const n=e.getShadow();Jt(n,r),ei(n,r),e.emit("tool-panel-close",{})},toggleToolPanel(){r.isPanelOpen?i.closeToolPanel():i.openToolPanel()},toggleToolPanelSection(n){const o=r.toolPanels.get(n);if(!o){console.warn(`[tbw-grid] Tool panel section "${n}" not found`);return}if(r.toolPanels.size===1)return;const s=e.getShadow(),l=r.expandedSections.has(n);if(l){const a=r.panelCleanups.get(n);a&&(a(),r.panelCleanups.delete(n)),o.onClose?.(),r.expandedSections.delete(n),Qe(s,n,!1)}else{for(const[a,c]of r.toolPanels)if(a!==n&&r.expandedSections.has(a)){const d=r.panelCleanups.get(a);d&&(d(),r.panelCleanups.delete(a)),c.onClose?.(),r.expandedSections.delete(a),Qe(s,a,!1);const u=s.querySelector(`[data-section="${a}"] .tbw-accordion-content`);u&&(u.innerHTML="")}r.expandedSections.add(n),Qe(s,n,!0),ar(s,r,n)}e.emit("tool-panel-section-toggle",{id:n,expanded:!l})},getToolPanels(){return[...r.toolPanels.values()]},registerToolPanel(n){if(r.toolPanels.has(n.id)){console.warn(`[tbw-grid] Tool panel "${n.id}" already registered`);return}r.toolPanels.set(n.id,n),t&&e.refreshShellHeader()},unregisterToolPanel(n){if(r.expandedSections.has(n)){const o=r.panelCleanups.get(n);o&&(o(),r.panelCleanups.delete(n)),r.expandedSections.delete(n)}r.toolPanels.delete(n),t&&e.refreshShellHeader()},getHeaderContents(){return[...r.headerContents.values()]},registerHeaderContent(n){if(r.headerContents.has(n.id)){console.warn(`[tbw-grid] Header content "${n.id}" already registered`);return}r.headerContents.set(n.id,n),t&&Ye(e.getShadow(),r)},unregisterHeaderContent(n){const o=r.headerContentCleanups.get(n);o&&(o(),r.headerContentCleanups.delete(n)),r.headerContents.get(n)?.onDestroy?.(),r.headerContents.delete(n),e.getShadow().querySelector(`[data-header-content="${n}"]`)?.remove()},getToolbarContents(){return[...r.toolbarContents.values()].sort((n,o)=>(n.order??0)-(o.order??0))},registerToolbarContent(n){if(r.toolbarContents.has(n.id)){console.warn(`[tbw-grid] Toolbar content "${n.id}" already registered`);return}r.toolbarContents.set(n.id,n),t&&e.refreshShellHeader()},unregisterToolbarContent(n){const o=r.toolbarContentCleanups.get(n);o&&(o(),r.toolbarContentCleanups.delete(n));const s=r.toolbarContents.get(n);s?.onDestroy&&s.onDestroy(),r.toolbarContents.delete(n),t&&e.refreshShellHeader()}};return i}function Qe(r,e,t){const i=r.querySelector(`[data-section="${e}"]`);i&&i.classList.toggle("expanded",t)}function ar(r,e,t){const i=e.toolPanels.get(t);if(!i?.render)return;const n=r.querySelector(`[data-section="${t}"] .tbw-accordion-content`);if(!n)return;const o=i.render(n);o&&e.panelCleanups.set(t,o)}function cr(r,e,t,i){const n=Yt(e),o=[],s=["tbw-grid-header","tbw-grid-tool-buttons","tbw-grid-tool-panel","tbw-grid-column","tbw-grid-detail","tbw-grid-responsive-card"];for(const l of s)r.querySelectorAll(`:scope > ${l}`).forEach(c=>o.push(c));r.replaceChildren();for(const l of o)r.appendChild(l);if(n){const l=ee(i?.toolPanel??K.toolPanel),a=ee(i?.expand??K.expand),c=ee(i?.collapse??K.collapse),u=[...e?.header?.toolbarContents??[]].sort((_,T)=>(_.order??0)-(T.order??0)),p=[...e?.toolPanels??[]].sort((_,T)=>(_.order??100)-(T.order??100)),g={title:e?.header?.title??void 0,hasPanels:p.length>0,isPanelOpen:t.isPanelOpen,toolPanelIcon:l,configButtons:u.map(_=>({id:_.id,hasElement:!1,hasRender:!!_.render})),apiButtons:[]},f={position:e?.toolPanel?.position??"right",isPanelOpen:t.isPanelOpen,expandIcon:a,collapseIcon:c,panels:p.map(_=>({id:_.id,title:_.title,icon:ee(_.icon),isExpanded:t.expandedSections.has(_.id)}))},w=Zn(g),y=Jn(f),b=jt({hasShell:!0,shellHeader:w,shellBody:y});r.appendChild(b)}else{const l=jt({hasShell:!1});r.appendChild(l)}return n}const ti="tbw-grid-styles";let Ie="";const Ze=new Map;function dr(){let r=document.getElementById(ti);return r||(r=document.createElement("style"),r.id=ti,r.setAttribute("data-tbw-grid","true"),document.head.appendChild(r)),r}function Je(){const r=dr(),e=Array.from(Ze.values()).join(`
28
- `);r.textContent=`${Ie}
29
-
30
- /* Plugin Styles */
31
- ${e}`}function ur(r){let e=!1;for(const{name:t,styles:i}of r)Ze.has(t)||(Ze.set(t,i),e=!0);return e&&Je(),e}function hr(){try{for(const r of Array.from(document.styleSheets))try{const t=Array.from(r.cssRules||[]).map(i=>i.cssText).join(`
32
- `);if(t.includes(".tbw-grid-root")&&t.includes("tbw-grid"))return t}catch{continue}}catch(r){console.warn("[tbw-grid] Failed to extract grid.css from document stylesheets:",r)}return null}async function fr(r){if(Ie)return;if(typeof r=="string"&&r.length>0){Ie=r,Je();return}await new Promise(t=>setTimeout(t,50));const e=hr();e?(Ie=e,Je()):(typeof process>"u"||process.env?.NODE_ENV!=="test")&&console.warn("[tbw-grid] Could not find grid.css in document.styleSheets. Grid styling will not work.","Available stylesheets:",Array.from(document.styleSheets).map(t=>t.href||"(inline)"))}function gr(){return{startY:null,startX:null,scrollTop:null,scrollLeft:null,lastY:null,lastX:null,lastTime:null,velocityY:0,velocityX:0,momentumRaf:0}}function pr(r){r.startY=null,r.startX=null,r.scrollTop=null,r.scrollLeft=null,r.lastY=null,r.lastX=null,r.lastTime=null}function ii(r){r.momentumRaf&&(cancelAnimationFrame(r.momentumRaf),r.momentumRaf=0)}function wr(r,e,t){if(r.touches.length!==1)return;ii(e);const i=r.touches[0];e.startY=i.clientY,e.startX=i.clientX,e.lastY=i.clientY,e.lastX=i.clientX,e.lastTime=performance.now(),e.scrollTop=t.fauxScrollbar.scrollTop,e.scrollLeft=t.scrollArea?.scrollLeft??0,e.velocityY=0,e.velocityX=0}function mr(r,e,t){if(r.touches.length!==1||e.startY===null||e.startX===null||e.scrollTop===null||e.scrollLeft===null)return!1;const i=r.touches[0],n=i.clientY,o=i.clientX,s=performance.now(),l=e.startY-n,a=e.startX-o;if(e.lastTime!==null&&e.lastY!==null&&e.lastX!==null){const f=s-e.lastTime;f>0&&(e.velocityY=(e.lastY-n)/f,e.velocityX=(e.lastX-o)/f)}e.lastY=n,e.lastX=o,e.lastTime=s;const{scrollTop:c,scrollHeight:d,clientHeight:u}=t.fauxScrollbar,h=d-u,p=l>0&&c<h||l<0&&c>0;let g=!1;if(t.scrollArea){const{scrollLeft:f,scrollWidth:w,clientWidth:y}=t.scrollArea,b=w-y;g=a>0&&f<b||a<0&&f>0}return p&&(t.fauxScrollbar.scrollTop=e.scrollTop+l),g&&t.scrollArea&&(t.scrollArea.scrollLeft=e.scrollLeft+a),p||g}function br(r,e){(Math.abs(r.velocityY)>.1||Math.abs(r.velocityX)>.1)&&vr(r,e),pr(r)}function vr(r,e){const n=()=>{r.velocityY*=.95,r.velocityX*=.95;const o=r.velocityY*16,s=r.velocityX*16;Math.abs(r.velocityY)>.01&&(e.fauxScrollbar.scrollTop+=o),Math.abs(r.velocityX)>.01&&e.scrollArea&&(e.scrollArea.scrollLeft+=s),Math.abs(r.velocityY)>.01||Math.abs(r.velocityX)>.01?r.momentumRaf=requestAnimationFrame(n):r.momentumRaf=0};r.momentumRaf=requestAnimationFrame(n)}function yr(r,e,t,i){r.addEventListener("touchstart",n=>wr(n,e,t),{passive:!0,signal:i}),r.addEventListener("touchmove",n=>{mr(n,e,t)&&n.preventDefault()},{passive:!1,signal:i}),r.addEventListener("touchend",()=>br(e,t),{passive:!0,signal:i})}const Cr=[{property:"editable",pluginName:"editing",level:"column",description:'the "editable" column property',isUsed:r=>r===!0},{property:"editor",pluginName:"editing",level:"column",description:'the "editor" column property'},{property:"editorParams",pluginName:"editing",level:"column",description:'the "editorParams" column property'},{property:"group",pluginName:"groupingColumns",level:"column",description:'the "group" column property'},{property:"pinned",pluginName:"pinnedColumns",level:"column",description:'the "pinned" column property',isUsed:r=>r==="left"||r==="right"||r==="start"||r==="end"},{property:"sticky",pluginName:"pinnedColumns",level:"column",description:'the "sticky" column property (deprecated, use "pinned")',isUsed:r=>r==="left"||r==="right"||r==="start"||r==="end"}],xr=[{property:"columnGroups",pluginName:"groupingColumns",level:"config",description:'the "columnGroups" config property',isUsed:r=>Array.isArray(r)&&r.length>0}];function Er(r){return r.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function et(r){return`import { ${$(r)}Plugin } from '@toolbox-web/grid/plugins/${Er(r)}';`}function $(r){return r.charAt(0).toUpperCase()+r.slice(1)}function ni(r,e){return r.some(t=>t.name===e)}function Rr(r,e){const t=Cr,i=xr,n=new Map;function o(l,a,c,d,u=!1){n.has(l)||n.set(l,{description:a,importHint:c,fields:[],isConfigProperty:u});const h=n.get(l);h.fields.includes(d)||h.fields.push(d)}for(const l of i){const a=r[l.property];(l.isUsed?l.isUsed(a):a!==void 0)&&!ni(e,l.pluginName)&&o(l.pluginName,l.description,et(l.pluginName),l.property,!0)}const s=r.columns;if(s&&s.length>0)for(const l of s)for(const a of t){const c=l[a.property];if((a.isUsed?a.isUsed(c):c!==void 0)&&!ni(e,a.pluginName)){const u=l.field||"<unknown>";o(a.pluginName,a.description,et(a.pluginName),u)}}if(n.size>0){const l=[];for(const[a,{description:c,importHint:d,fields:u,isConfigProperty:h}]of n)if(h)l.push(`Config uses ${c}, but the required plugin is not loaded.
33
- → Add the plugin to your gridConfig.plugins array:
34
- ${d}
35
- plugins: [new ${$(a)}Plugin(), ...]`);else{const p=u.slice(0,3).join(", ")+(u.length>3?`, ... (${u.length} total)`:"");l.push(`Column(s) [${p}] use ${c}, but the required plugin is not loaded.
36
- → Add the plugin to your gridConfig.plugins array:
37
- ${d}
38
- plugins: [new ${$(a)}Plugin(), ...]`)}throw new Error(`[tbw-grid] Configuration error:
39
-
40
- ${l.join(`
41
-
42
- `)}
43
-
44
- This validation helps catch misconfigurations early. The properties listed above require their respective plugins to function.`)}}function Sr(r){const e=[],t=[];for(const i of r){const o=i.constructor.manifest;if(o?.configRules)for(const s of o.configRules){const l=i.config;if(s.check(l)){const c=`${`[tbw-grid:${$(i.name)}Plugin]`} Configuration warning: ${s.message}`;s.severity==="error"?e.push(c):t.push(c)}}}if(t.length>0&&qe())for(const i of t)console.warn(i);if(e.length>0)throw new Error(`[tbw-grid] Configuration error:
45
-
46
- ${e.join(`
47
-
48
- `)}`)}function _r(r,e){const t=r.name,n=r.constructor.dependencies??[];for(const o of n){const s=o.name,l=o.required??!0,a=o.reason;if(!e.some(d=>d.name===s)){const d=a??`${$(t)}Plugin requires ${$(s)}Plugin`,u=et(s);if(l)throw new Error(`[tbw-grid] Plugin dependency error:
49
-
50
- ${d}.
51
-
52
- → Add the plugin to your gridConfig.plugins array BEFORE ${$(t)}Plugin:
53
- ${u}
54
- plugins: [new ${$(s)}Plugin(), new ${$(t)}Plugin()]`);console.info(`[tbw-grid] ${$(t)}Plugin: Optional "${s}" plugin not found. Some features may be unavailable.`)}}}function Ar(r){if(!qe())return;const e=new Set(r.map(i=>i.name)),t=new Set;for(const i of r){const o=i.constructor.manifest;if(o?.incompatibleWith){for(const s of o.incompatibleWith)if(e.has(s.name)){const l=[i.name,s.name].sort().join("↔");if(t.has(l))continue;t.add(l),console.warn(`[tbw-grid] Plugin incompatibility warning:
55
-
56
- ${$(i.name)}Plugin and ${$(s.name)}Plugin are both loaded, but they are currently incompatible.
57
-
58
- → ${s.reason}
59
-
60
- Consider removing one of these plugins to avoid unexpected behavior.`)}}}}function ri(r,e){return!r||typeof r!="object"?r:"__rowCacheKey"in r?r.__rowCacheKey:"rowId"in r&&r.rowId!=null?`id:${r.rowId}`:e?`id:${e(r)}`:r}function kr(r,e,t){const i=ri(e,t);if(typeof i=="string")return r.byKey.get(i);if(i&&typeof i=="object")return r.byRef.get(i)}function Tr(r,e,t,i){const n=ri(e,i);typeof n=="string"?r.byKey.set(n,t):n&&typeof n=="object"&&r.byRef.set(n,t)}function Lr(r,e,t,i,n){const o=new Array(r.length);let s=0;for(let l=0;l<r.length;l++){const a=r[l];let c=n?.(a,l),d=c!==void 0;c===void 0&&(c=kr(e,a,i.rowId),d=c!==void 0),c===void 0&&(c=t,d=!1),o[l]={offset:s,height:c,measured:d},s+=c}return o}function tt(r,e,t){if(e<0||e>=r.length)return;const i=r[e],n=t-i.height;if(n!==0){i.height=t,i.measured=!0;for(let o=e+1;o<r.length;o++)r[o].offset+=n}}function Pr(r){if(r.length===0)return 0;const e=r[r.length-1];return e.offset+e.height}function oi(r,e){if(r.length===0)return-1;if(e<=0)return 0;let t=0,i=r.length-1;for(;t<=i;){const n=Math.floor((t+i)/2),o=r[n],s=o.offset+o.height;if(e<o.offset)i=n-1;else if(e>=s)t=n+1;else return n}return Math.max(0,Math.min(t,r.length-1))}function Hr(r,e){let t=0,i=0;for(const n of r)n.measured&&(t+=n.height,i++);return i>0?t/i:e}function Ir(r){let e=0;for(const t of r)t.measured&&e++;return e}function Dr(r,e){const{positionCache:t,heightCache:i,rows:n,start:o,end:s,getPluginHeight:l,getRowId:a}=r;let c=!1;e.forEach(h=>{const p=h.dataset.rowIndex;if(!p)return;const g=parseInt(p,10);if(g<o||g>=s||g>=n.length)return;const f=n[g],w=l?.(f,g);if(w!==void 0){const b=t[g];(!b.measured||Math.abs(b.height-w)>1)&&(tt(t,g,w),c=!0);return}const y=h.offsetHeight;if(y>0){const b=t[g];(!b.measured||Math.abs(b.height-y)>1)&&(tt(t,g,y),Tr(i,f,y,a),c=!0)}});const d=c?Ir(t):0,u=c?Hr(t,r.defaultHeight):0;return{hasChanges:c,measuredCount:d,averageHeight:u}}function Mr(r,e,t,i){let n=0,o=0;for(let s=0;s<r.length;s++){const l=r[s];l.measured&&i?.(e[s],s)===void 0&&(o+=l.height,n++)}return{measuredCount:n,averageHeight:n>0?o/n:t}}function zr(r){const{totalRows:e,viewportHeight:t,scrollTop:i,rowHeight:n,overscan:o}=r,s=Math.ceil(t/n);let l=Math.floor(i/n)-o;l<0&&(l=0);let a=l+s+o*2;return a>e&&(a=e),a===e&&l>0&&(l=Math.max(0,a-s-o*2)),{start:l,end:a,offsetY:l*n,totalHeight:e*n}}function Or(r,e){return r<=e}class be{constructor(e){this.grid=e}plugins=[];getPlugins(){return this.plugins}pluginMap=new Map;cellRenderers=new Map;headerRenderers=new Map;cellEditors=new Map;eventListeners=new Map;queryHandlers=new Map;static deprecationWarned=new WeakSet;attachAll(e){for(const t of e)this.attach(t)}attach(e){if(_r(e,this.plugins),this.pluginMap.set(e.constructor,e),this.plugins.push(e),e.cellRenderers)for(const[t,i]of Object.entries(e.cellRenderers))this.cellRenderers.set(t,i);if(e.headerRenderers)for(const[t,i]of Object.entries(e.headerRenderers))this.headerRenderers.set(t,i);if(e.cellEditors)for(const[t,i]of Object.entries(e.cellEditors))this.cellEditors.set(t,i);this.registerQueryHandlers(e),this.warnDeprecatedHooks(e),e.attach(this.grid);for(const t of this.plugins)t!==e&&t.onPluginAttached&&t.onPluginAttached(e.name,e)}registerQueryHandlers(e){const i=e.constructor.manifest;if(i?.queries)for(const n of i.queries){let o=this.queryHandlers.get(n.type);o||(o=new Set,this.queryHandlers.set(n.type,o)),o.add(e)}}warnDeprecatedHooks(e){const t=e.constructor;if(be.deprecationWarned.has(t)||!qe())return;const i=typeof e.getExtraHeight=="function"||typeof e.getExtraHeightBefore=="function",n=typeof e.getRowHeight=="function";i&&!n&&(be.deprecationWarned.add(t),console.warn(`[tbw-grid] Deprecation warning: "${e.name}" uses getExtraHeight() / getExtraHeightBefore() which are deprecated and will be removed in v3.0.
61
- → Migrate to getRowHeight(row, index) for better variable row height support.
62
- → See: https://toolbox-web.dev/docs/grid/plugins/migration#row-height-hooks`))}unregisterQueryHandlers(e){for(const[t,i]of this.queryHandlers)i.delete(e),i.size===0&&this.queryHandlers.delete(t)}detachAll(){for(const e of this.plugins)for(const t of this.plugins)t!==e&&t.onPluginDetached&&t.onPluginDetached(e.name);for(let e=this.plugins.length-1;e>=0;e--){const t=this.plugins[e];this.unsubscribeAll(t),this.unregisterQueryHandlers(t),t.detach()}this.plugins=[],this.pluginMap.clear(),this.cellRenderers.clear(),this.headerRenderers.clear(),this.cellEditors.clear(),this.eventListeners.clear(),this.queryHandlers.clear()}getPlugin(e){return this.pluginMap.get(e)}getPluginByName(e){return this.plugins.find(t=>t.name===e)}hasPlugin(e){return this.pluginMap.has(e)}getAll(){return this.plugins}getRegisteredPluginNames(){return this.plugins.map(e=>e.name)}getCellRenderer(e){return this.cellRenderers.get(e)}getHeaderRenderer(e){return this.headerRenderers.get(e)}getCellEditor(e){return this.cellEditors.get(e)}getPluginStyles(){return this.plugins.filter(e=>e.styles).map(e=>({name:e.name,styles:e.styles}))}processRows(e){let t=[...e];for(const i of this.plugins)i.processRows&&(t=i.processRows(t));return t}processColumns(e){let t=[...e];for(const i of this.plugins)i.processColumns&&(t=i.processColumns(t));return t}beforeRender(){for(const e of this.plugins)e.beforeRender?.()}afterRender(){for(const e of this.plugins)e.afterRender?.()}afterCellRender(e){for(const t of this.plugins)t.afterCellRender?.(e)}hasAfterCellRenderHook(){return this.plugins.some(e=>typeof e.afterCellRender=="function")}afterRowRender(e){for(const t of this.plugins)t.afterRowRender?.(e)}hasAfterRowRenderHook(){return this.plugins.some(e=>typeof e.afterRowRender=="function")}onScrollRender(){for(const e of this.plugins)e.onScrollRender?.()}getExtraHeight(){let e=0;for(const t of this.plugins)typeof t.getExtraHeight=="function"&&(e+=t.getExtraHeight());return e}hasExtraHeight(){for(const e of this.plugins)if(typeof e.getExtraHeight=="function"&&e.getExtraHeight()>0)return!0;return!1}getExtraHeightBefore(e){let t=0;for(const i of this.plugins)typeof i.getExtraHeightBefore=="function"&&(t+=i.getExtraHeightBefore(e));return t}getRowHeight(e,t){for(const i of this.plugins)if(typeof i.getRowHeight=="function"){const n=i.getRowHeight(e,t);if(n!==void 0)return n}}hasRowHeightPlugin(){for(const e of this.plugins)if(typeof e.getRowHeight=="function")return!0;return!1}adjustVirtualStart(e,t,i){let n=e;for(const o of this.plugins)if(typeof o.adjustVirtualStart=="function"){const s=o.adjustVirtualStart(e,t,i);s<n&&(n=s)}return n}renderRow(e,t,i){for(const n of this.plugins)if(n.renderRow?.(e,t,i))return!0;return!1}queryPlugins(e){const t=[],i=this.queryHandlers.get(e.type);if(i&&i.size>0){for(const n of i){const o=n.handleQuery?.(e)??n.onPluginQuery?.(e);o!==void 0&&t.push(o)}return t}for(const n of this.plugins){const o=n.handleQuery?.(e)??n.onPluginQuery?.(e);o!==void 0&&t.push(o)}return t}subscribe(e,t,i){let n=this.eventListeners.get(t);n||(n=new Map,this.eventListeners.set(t,n)),n.set(e,i)}unsubscribe(e,t){const i=this.eventListeners.get(t);i&&(i.delete(e),i.size===0&&this.eventListeners.delete(t))}unsubscribeAll(e){for(const[t,i]of this.eventListeners)i.delete(e),i.size===0&&this.eventListeners.delete(t)}emitPluginEvent(e,t){const i=this.eventListeners.get(e);if(i)for(const n of i.values())try{n(t)}catch(o){console.error(`[tbw-grid] Error in plugin event handler for "${e}":`,o)}}onKeyDown(e){for(const t of this.plugins)if(t.onKeyDown?.(e))return!0;return!1}onCellClick(e){for(const t of this.plugins)if(t.onCellClick?.(e))return!0;return!1}onRowClick(e){for(const t of this.plugins)if(t.onRowClick?.(e))return!0;return!1}onHeaderClick(e){for(const t of this.plugins)if(t.onHeaderClick?.(e))return!0;return!1}onScroll(e){for(const t of this.plugins)t.onScroll?.(e)}onCellMouseDown(e){for(const t of this.plugins)if(t.onCellMouseDown?.(e))return!0;return!1}onCellMouseMove(e){for(const t of this.plugins)if(t.onCellMouseMove?.(e))return!0;return!1}onCellMouseUp(e){for(const t of this.plugins)if(t.onCellMouseUp?.(e))return!0;return!1}getHorizontalScrollOffsets(e,t){let i=0,n=0,o=!1;for(const s of this.plugins){const l=s.getHorizontalScrollOffsets?.(e,t);l&&(i+=l.left,n+=l.right,l.skipScroll&&(o=!0))}return{left:i,right:n,skipScroll:o}}getToolPanels(){const e=[];for(const t of this.plugins){const i=t.getToolPanel?.();i&&e.push({plugin:t,panel:i})}return e.sort((t,i)=>(t.panel.order??0)-(i.panel.order??0))}getHeaderContents(){const e=[];for(const t of this.plugins){const i=t.getHeaderContent?.();i&&e.push({plugin:t,content:i})}return e.sort((t,i)=>(t.content.order??0)-(i.content.order??0))}}const Fr=`/**
63
- * tbw-grid Light DOM Styles
64
- *
65
- * This stylesheet uses CSS nesting to scope all styles to the tbw-grid element.
66
- * All selectors are automatically prefixed with \`tbw-grid\` for encapsulation.
67
- *
68
- * CSS Cascade Layers are used to control style priority:
69
- * - tbw-base: Core grid styles (lowest priority)
70
- * - tbw-plugins: Plugin styles (override base)
71
- * - tbw-theme: Theme overrides (override plugins)
72
- * - Unlayered CSS: User customizations (highest priority - always wins)
73
- *
74
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_nesting
75
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@layer
76
- */
77
-
78
- /* Declare layer order - earlier layers have lower priority */
79
- @layer tbw-base, tbw-plugins, tbw-theme;
80
-
81
- @layer tbw-base{tbw-grid{--tbw-base-icon-size: 1em;--tbw-base-radius: .25em;--tbw-font-size: 1em;--tbw-font-size-sm: .9285em;--tbw-font-size-xs: .7857em;--tbw-font-size-2xs: .7142em;--tbw-spacing-xs: .25em;--tbw-spacing-sm: .375em;--tbw-spacing-md: .5em;--tbw-spacing-lg: .75em;--tbw-spacing-xl: 1em;--tbw-icon-size: var(--tbw-base-icon-size);--tbw-icon-size-sm: .875em;--tbw-checkbox-size: var(--tbw-base-icon-size);--tbw-toggle-size: 1.25em;--tbw-border-radius: var(--tbw-base-radius);--tbw-color-bg: transparent;--tbw-color-panel-bg: light-dark(#eeeeee, #222222);--tbw-color-fg: light-dark(#222222, #eeeeee);--tbw-color-fg-muted: light-dark(#555555, #aaaaaa);--tbw-color-accent: light-dark(#3b82f6, #3b82f6);--tbw-color-accent-fg: light-dark(#ffffff, #000000);--tbw-color-success: light-dark(hsl(122, 39%, 40%), hsl(122, 39%, 49%));--tbw-color-warning: light-dark(hsl(38, 92%, 50%), hsl(38, 92%, 50%));--tbw-color-error: light-dark(hsl(0, 65%, 51%), hsl(0, 65%, 55%));--tbw-color-danger: var(--tbw-color-error);--tbw-color-selection: light-dark(#fff7d6, #333333);--tbw-color-row-alt: var(--tbw-color-bg);--tbw-color-row-hover: light-dark(#f0f6ff, #1c1c1c);--tbw-color-header-bg: color-mix(in hsl, var(--tbw-color-panel-bg) 85%, var(--tbw-color-fg));--tbw-color-header-fg: color-mix(in hsl, var(--tbw-color-fg) 75%, var(--tbw-color-panel-bg));--tbw-color-border: light-dark(#d0d0d4, #454545);--tbw-color-border-strong: light-dark(#777777, #666666);--tbw-color-border-cell: var(--tbw-color-border);--tbw-color-border-header: var(--tbw-color-border);--tbw-color-shadow: light-dark(rgba(0, 0, 0, .1), rgba(0, 0, 0, .3));--tbw-font-family: inherit;--tbw-font-size-header: var(--tbw-font-size);--tbw-font-weight-header: bold;--tbw-cell-padding-header: var(--tbw-spacing-xs) var(--tbw-spacing-md);--tbw-cell-padding-v: var(--tbw-spacing-xs);--tbw-cell-padding-h: var(--tbw-spacing-md);--tbw-cell-padding: var(--tbw-cell-padding-v) var(--tbw-cell-padding-h);--tbw-cell-padding-input: var(--tbw-spacing-xs) var(--tbw-spacing-sm);--tbw-row-height: 1.75em;--tbw-header-height: 1.875em;--tbw-cell-white-space: nowrap;--tbw-border-width: 1px;--tbw-border-style: solid;--tbw-border-input: var(--tbw-border-width) var(--tbw-border-style) var(--tbw-color-border-strong);--tbw-border-header: var(--tbw-border-width) var(--tbw-border-style) var(--tbw-color-border-header);--tbw-row-divider: var(--tbw-border-width) var(--tbw-border-style) var(--tbw-color-border-cell);--tbw-row-hover-outline: 0;--tbw-color-active-row-bg: var(--tbw-color-selection);--tbw-active-row-outline: 0;--tbw-focus-outline-width: 2px;--tbw-focus-outline: var(--tbw-focus-outline-width) var(--tbw-border-style) var(--tbw-color-accent);--tbw-focus-outline-offset: -2px;--tbw-focus-background: rgba(from var(--tbw-color-accent) r g b / 12%);--tbw-range-border-color: var(--tbw-color-accent);--tbw-range-selection-bg: rgba(from var(--tbw-range-border-color) r g b / 12%);--tbw-resize-handle-width: var(--tbw-spacing-sm);--tbw-resize-handle-color: transparent;--tbw-resize-handle-color-hover: var(--tbw-color-accent);--tbw-resize-handle-border-radius: 0;--tbw-resize-indicator-width: 2px;--tbw-resize-indicator-color: var(--tbw-color-accent);--tbw-resize-indicator-opacity: .6;--tbw-transition-duration: .12s;--tbw-transition-ease: ease;--tbw-animation-duration: .2s;--tbw-animation-easing: ease-out;--tbw-animation-enabled: 1;--tbw-row-change-duration: .5s;--tbw-row-insert-duration: .3s;--tbw-row-remove-duration: .2s;--tbw-row-change-color: rgba(from var(--tbw-color-accent) r g b / 25%);--tbw-sort-indicator-color: var(--tbw-color-fg-muted);--tbw-sort-indicator-active-color: var(--tbw-color-accent);--tbw-sort-indicator-display: inline-flex;--tbw-sort-indicator-visibility: visible;--tbw-header-text-transform: none;--tbw-header-letter-spacing: normal;--tbw-color-header-separator: var(--tbw-color-border-cell);--tbw-density-scale: 1;--tbw-shell-header-height: 2.75em;--tbw-shell-header-bg: var(--tbw-color-panel-bg);--tbw-shell-header-border: var(--tbw-color-border);--tbw-shell-title-font-size: var(--tbw-font-size);--tbw-shell-title-font-weight: 600;--tbw-tool-panel-width: 17.5em;--tbw-tool-panel-bg: var(--tbw-color-panel-bg);--tbw-tool-panel-border: var(--tbw-color-border);--tbw-tool-panel-header-height: 2.5em;--tbw-tool-panel-transition: var(--tbw-animation-duration) var(--tbw-animation-easing);--tbw-toolbar-button-size: 2em;--tbw-toolbar-button-gap: var(--tbw-spacing-xs);--tbw-panel-padding: var(--tbw-spacing-lg);--tbw-panel-gap: var(--tbw-spacing-md);--tbw-menu-item-padding: var(--tbw-spacing-sm) var(--tbw-spacing-lg);--tbw-menu-item-gap: var(--tbw-spacing-md);--tbw-menu-min-width: 10rem;--tbw-button-padding: var(--tbw-spacing-sm) var(--tbw-spacing-lg);--tbw-button-padding-sm: var(--tbw-spacing-xs) var(--tbw-spacing-md);--tbw-input-height: var(--tbw-row-height);--tbw-input-padding: 0 var(--tbw-spacing-md);--tbw-detail-padding: var(--tbw-spacing-xl);--tbw-detail-max-height: 31.25rem;--tbw-indicator-size: var(--tbw-spacing-sm)}}
82
- @layer tbw-base{tbw-grid{color-scheme:inherit;position:relative;display:block;width:100%;height:100%;min-height:0;contain:content;font-family:var(--tbw-font-family);font-size:var(--tbw-font-size);font-feature-settings:"tnum","lnum";background:var(--tbw-color-bg);color:var(--tbw-color-fg);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);overflow:clip;outline:none}tbw-grid,tbw-grid *{box-sizing:border-box}tbw-grid .tbw-grid-root{position:relative;display:flex;flex-direction:column;height:100%}tbw-grid .tbw-grid-root.has-shell{display:flex;flex-direction:column;height:100%}tbw-grid .tbw-grid-root:has(.selected){-webkit-user-select:none;user-select:none}tbw-grid .rows-body-wrapper{flex:1;min-height:0;display:flex;flex-direction:row;width:100%;min-width:fit-content}tbw-grid .rows-body{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:visible}tbw-grid .rows-container{display:flex;flex-direction:row;flex:1;min-height:0;overflow:visible}tbw-grid .rows-viewport{flex:1;min-width:0;position:relative;display:block;overflow:clip}tbw-grid .rows-viewport .rows{position:absolute;top:0;left:0;min-width:100%;will-change:transform;z-index:var(--tbw-z-layer-rows, 1)}tbw-grid .faux-vscroll{position:sticky;inset-inline-end:0;flex-shrink:0;width:auto;overflow-y:auto;overflow-x:hidden;z-index:var(--tbw-z-layer-header, 30)}tbw-grid .faux-vscroll-spacer{width:1px}tbw-grid[data-has-focus] .cell-focus,tbw-grid[data-has-focus] .row-focus{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}tbw-grid .sticky-left,tbw-grid .sticky-right{position:sticky;z-index:25}tbw-grid .sticky-left{box-shadow:1px 0 0 var(--tbw-color-border)}tbw-grid .sticky-right{box-shadow:-1px 0 0 var(--tbw-color-border)}}
83
- @layer tbw-base{tbw-grid .header{display:block;flex-shrink:0;z-index:var(--tbw-z-layer-header, 30);background:var(--tbw-color-header-bg);overflow:visible}tbw-grid .header-group-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-color-header-bg);z-index:var(--tbw-z-layer-header, 30)}tbw-grid .header-group-cell{display:flex;align-items:center;justify-content:flex-start;padding:var(--tbw-cell-padding-header, 2px 8px);color:var(--tbw-color-header-group-fg, var(--tbw-color-header-fg));font-weight:var(--tbw-font-weight-header-group, var(--tbw-font-weight-header));justify-content:var(--tbw-align-header-group, var(--tbw-align-header, flex-start))}tbw-grid .header-group-cell:not(:last-child){border-right:2px solid var(--tbw-color-border)}tbw-grid .header-row{display:grid;grid-template-columns:var(--tbw-column-template);color:var(--tbw-color-header-fg);font-size:var(--tbw-font-size-header);min-height:var(--tbw-header-height);border-bottom:var(--tbw-border-header);z-index:var(--tbw-z-layer-header, 30);text-transform:var(--tbw-header-text-transform);letter-spacing:var(--tbw-header-letter-spacing)}tbw-grid .header-row>.cell{display:flex;align-items:center;gap:4px;padding:var(--tbw-cell-padding-header, 2px 8px);background-color:var(--tbw-color-header-bg);font-weight:var(--tbw-font-weight-header);border-right:1px solid var(--tbw-color-border-cell);overflow:visible;min-width:0}tbw-grid .header-row>.cell>span:first-child{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:inherit}tbw-grid .header-row>.cell>span[part~=sort-indicator]{flex-shrink:0;opacity:.6;color:var(--tbw-sort-indicator-color);display:var(--tbw-sort-indicator-display, inline-flex);visibility:var(--tbw-sort-indicator-visibility, visible);transition:opacity .15s,visibility 0s,display 0s allow-discrete;transition-behavior:allow-discrete}tbw-grid .header-row>.cell:hover>span[part~=sort-indicator]{display:inline-flex;visibility:visible}tbw-grid .header-row>.cell[aria-sort=ascending]>span[part~=sort-indicator],tbw-grid .header-row>.cell[aria-sort=descending]>span[part~=sort-indicator]{display:inline-flex;visibility:visible;opacity:1;color:var(--tbw-sort-indicator-active-color)}tbw-grid .header-row>.cell:last-child{border-right:0}tbw-grid .header-row>.cell:last-child .resize-handle{right:0;width:calc(var(--tbw-resize-handle-width) / 2)}tbw-grid .header-row>.cell.grouped.group-end:not(:last-child){border-right:2px solid var(--tbw-color-border)}tbw-grid .header-row>.cell.resizable{position:relative}tbw-grid .header-row>.cell.sticky-left,tbw-grid .header-row>.cell.sticky-right{background:var(--tbw-color-header-bg);z-index:35}tbw-grid .sortable{cursor:pointer;-webkit-user-select:none;user-select:none}tbw-grid .resize-handle{position:absolute;top:0;right:calc(var(--tbw-resize-handle-width) / -2);width:var(--tbw-resize-handle-width);height:100%;cursor:e-resize;-webkit-user-select:none;user-select:none;touch-action:none;z-index:20;background:var(--tbw-resize-handle-color);transition:background .12s ease;border-radius:var(--tbw-resize-handle-border-radius)}tbw-grid .resize-handle:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);width:var(--tbw-resize-indicator-width, 2px);height:0;background:var(--tbw-resize-indicator-color, var(--tbw-color-accent));opacity:0;pointer-events:none;transition:opacity .12s ease,height 0s .12s;z-index:1000}tbw-grid .resize-handle:hover{background:var(--tbw-resize-handle-color-hover)}tbw-grid .resize-handle:hover:after{height:100vh;opacity:var(--tbw-resize-indicator-opacity, .6);transition:opacity .12s ease,height 0s}}
84
- @layer tbw-base{tbw-grid .data-grid-row{display:grid;grid-template-columns:var(--tbw-column-template);contain:layout style}tbw-grid .data-grid-row:nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid .data-grid-row:hover{background:var(--tbw-color-row-hover)}tbw-grid .data-grid-row>.cell{display:block;padding:var(--tbw-cell-padding, 2px 8px);border-bottom:var(--tbw-row-divider);min-height:var(--tbw-row-height);align-content:center;border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;min-width:0;white-space:var(--tbw-cell-white-space, nowrap);text-overflow:ellipsis}tbw-grid .data-grid-row>.cell>*{overflow:hidden;text-overflow:ellipsis;white-space:inherit;min-width:0}tbw-grid .data-grid-row>.cell:last-child{border-right:0}tbw-grid .data-grid-row>.cell[data-type=boolean]{text-align:center}tbw-grid .data-grid-row>.cell[data-type=boolean] input[type=checkbox]{margin:0;width:var(--tbw-checkbox-size);height:var(--tbw-checkbox-size);vertical-align:middle}tbw-grid .data-grid-row>.cell.selected:focus-visible,tbw-grid .data-grid-row>.cell:focus-visible:not(.cell-focus){outline:none}tbw-grid .data-grid-row>.cell.sticky-left,tbw-grid .data-grid-row>.cell.sticky-right{background:var(--tbw-color-panel-bg)}tbw-grid .selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}}
85
- @layer tbw-base{tbw-grid .tbw-shell-header{display:flex;align-items:center;gap:8px;min-height:var(--tbw-shell-header-height);padding:0 8px;background:var(--tbw-shell-header-bg);border-bottom:1px solid var(--tbw-shell-header-border);flex-shrink:0}tbw-grid .tbw-shell-title{font-size:var(--tbw-shell-title-font-size);font-weight:var(--tbw-shell-title-font-weight);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}tbw-grid .tbw-shell-content{flex:1;display:flex;align-items:center;gap:12px;min-width:0;overflow:hidden}tbw-grid .tbw-shell-toolbar{display:flex;align-items:center;gap:var(--tbw-toolbar-button-gap);flex-shrink:0}tbw-grid .tbw-toolbar-btn{display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-toolbar-button-size);height:var(--tbw-toolbar-button-size);padding:0;border:1px solid transparent;border-radius:var(--tbw-border-radius);background:transparent;color:var(--tbw-color-fg);cursor:pointer;font-size:16px;transition:background var(--tbw-transition-duration) var(--tbw-transition-ease),border-color var(--tbw-transition-duration) var(--tbw-transition-ease)}tbw-grid .tbw-toolbar-btn:hover{background:var(--tbw-color-row-hover)}tbw-grid .tbw-toolbar-btn:focus-visible{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}tbw-grid .tbw-toolbar-btn.active{background:var(--tbw-focus-background);border-color:var(--tbw-color-accent)}tbw-grid .tbw-toolbar-btn:disabled{opacity:.5;cursor:not-allowed}tbw-grid .tbw-toolbar-separator{width:1px;height:20px;background:var(--tbw-color-border);margin:0 4px}tbw-grid .tbw-shell-body{position:relative;display:flex;flex:1;min-height:0;overflow:visible}tbw-grid .tbw-grid-content{flex:1;min-width:0;min-height:0;display:flex;flex-direction:row;overflow:hidden}tbw-grid .tbw-scroll-area{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow-x:auto;overflow-y:hidden;overflow-anchor:none}}
86
- @layer tbw-base{tbw-grid .tbw-tool-panel{position:absolute;top:0;bottom:0;right:0;width:0;overflow:hidden;background:var(--tbw-tool-panel-bg);border-left:1px solid var(--tbw-tool-panel-border);transition:width var(--tbw-tool-panel-transition);display:flex;flex-direction:column;z-index:30;box-shadow:-2px 0 8px var(--tbw-color-shadow)}tbw-grid .tbw-tool-panel[data-position=left]{right:auto;left:0;border-left:none;border-right:1px solid var(--tbw-tool-panel-border);box-shadow:2px 0 8px var(--tbw-color-shadow)}tbw-grid .tbw-tool-panel.open{width:var(--tbw-tool-panel-width)}tbw-grid .tbw-tool-panel-resize{position:absolute;top:0;bottom:0;width:6px;cursor:col-resize;background:transparent;z-index:10;transition:background var(--tbw-transition-duration) var(--tbw-transition-ease)}tbw-grid .tbw-tool-panel-resize[data-handle-position=left]{left:0}tbw-grid .tbw-tool-panel-resize[data-handle-position=right]{right:0}tbw-grid .tbw-tool-panel-resize:hover,tbw-grid .tbw-tool-panel-resize.resizing{background:var(--tbw-color-accent)}tbw-grid .tbw-tool-panel-header{display:flex;align-items:center;justify-content:space-between;min-height:var(--tbw-tool-panel-header-height);padding:0 12px;border-bottom:1px solid var(--tbw-tool-panel-border);flex-shrink:0}tbw-grid .tbw-tool-panel-title{font-weight:600;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}tbw-grid .tbw-tool-panel-close{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:none;border-radius:var(--tbw-border-radius);background:transparent;color:var(--tbw-color-fg-muted);cursor:pointer;font-size:14px}tbw-grid .tbw-tool-panel-close:hover{background:var(--tbw-color-row-hover);color:var(--tbw-color-fg)}tbw-grid .tbw-tool-panel-content{flex:1;overflow:auto}tbw-grid .tbw-accordion{display:flex;flex-direction:column;gap:0}tbw-grid .tbw-accordion-section{border-bottom:1px solid var(--tbw-tool-panel-border)}tbw-grid .tbw-accordion-section:last-child{border-bottom:none}tbw-grid .tbw-accordion-section.single .tbw-accordion-header{cursor:default}tbw-grid .tbw-accordion-section.single .tbw-accordion-header:hover{background:transparent}tbw-grid .tbw-accordion-section.expanded .tbw-accordion-chevron{transform:rotate(90deg)}tbw-grid .tbw-accordion-section.expanded .tbw-accordion-content{display:block}tbw-grid .tbw-accordion-header{display:flex;align-items:center;gap:8px;width:100%;padding:10px 12px;border:none;background:transparent;color:var(--tbw-color-fg);font-size:13px;font-weight:600;text-align:start;cursor:pointer;-webkit-user-select:none;user-select:none}tbw-grid .tbw-accordion-header:hover{background:var(--tbw-color-row-hover)}tbw-grid .tbw-accordion-chevron{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;font-size:10px;color:var(--tbw-color-fg-muted);transition:transform .15s ease;flex-shrink:0}tbw-grid .tbw-accordion-icon{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;font-size:14px;flex-shrink:0}tbw-grid .tbw-accordion-title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}tbw-grid .tbw-accordion-content{display:none}}
87
- @layer tbw-base{.tbw-loading-overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:1000;pointer-events:all;animation:tbw-fade-in .15s ease-out}.tbw-spinner{--tbw-spinner-size: 48px;--tbw-spinner-border-width: 3px;--tbw-spinner-color: var(--tbw-color-accent);--tbw-spinner-track-color: var(--tbw-color-border);width:var(--tbw-spinner-size);height:var(--tbw-spinner-size);border:var(--tbw-spinner-border-width) solid var(--tbw-spinner-track-color);border-top-color:var(--tbw-spinner-color);border-radius:50%;animation:tbw-spin .8s linear infinite}.tbw-spinner--large{--tbw-spinner-size: min(48px, calc(100% - 16px) )}.tbw-spinner--small{--tbw-spinner-size: calc(var(--tbw-row-height, 28px) * .6);--tbw-spinner-border-width: 2px}.data-grid-row.tbw-row-loading{position:relative;pointer-events:none}.tbw-row-loading-overlay{position:absolute;inset:0;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:26;animation:tbw-fade-in .15s ease-out;pointer-events:none;display:flex;align-items:center}.tbw-row-loading-spinner{--_spinner-size: calc(var(--tbw-row-height, 28px) * .6);margin-left:var(--tbw-spacing-md);width:var(--_spinner-size);height:var(--_spinner-size);border:2px solid var(--tbw-spinner-track-color, var(--tbw-color-border));border-top-color:var(--tbw-spinner-color, var(--tbw-color-accent));border-radius:50%;animation:tbw-spin .8s linear infinite}.cell.tbw-cell-loading{position:relative;pointer-events:none}.cell.tbw-cell-loading:before{content:"";position:absolute;inset:0;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:26;animation:tbw-fade-in .15s ease-out}.cell.tbw-cell-loading:after{--_spinner-size: calc(var(--tbw-row-height, 28px) * .5);content:"";position:absolute;left:var(--tbw-spacing-sm);top:0;bottom:0;margin:auto 0;width:var(--_spinner-size);height:var(--_spinner-size);border:2px solid var(--tbw-spinner-track-color, var(--tbw-color-border));border-top-color:var(--tbw-spinner-color, var(--tbw-color-accent));border-radius:50%;animation:tbw-spin .8s linear infinite;z-index:27}}
88
- @layer tbw-base{tbw-grid .tbw-expanding{animation:tbw-expand var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}tbw-grid .tbw-collapsing{animation:tbw-collapse var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}tbw-grid[data-animation-mode=off]{--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}tbw-grid[data-animation-mode=off] .data-grid-row[data-animating]{animation:none}tbw-grid .data-grid-row[data-animating=change]{animation:tbw-row-change var(--tbw-row-change-duration) ease-out}tbw-grid .data-grid-row[data-animating=insert]{animation:tbw-row-insert var(--tbw-row-insert-duration) ease-out;will-change:max-height,opacity}tbw-grid .data-grid-row[data-animating=remove]{animation:tbw-row-remove var(--tbw-row-remove-duration) ease-out forwards;will-change:max-height,opacity,transform;pointer-events:none}}@keyframes tbw-expand{0%{opacity:0;max-height:0;transform:translateY(-8px)}to{opacity:1;max-height:500px;transform:translateY(0)}}@keyframes tbw-collapse{0%{opacity:1;max-height:500px;transform:translateY(0)}to{opacity:0;max-height:0;transform:translateY(-8px)}}@keyframes tbw-row-change{0%{background-color:transparent}20%{background-color:var(--tbw-row-change-color)}to{background-color:transparent}}@keyframes tbw-row-insert{0%{opacity:0;max-height:0;overflow:hidden}to{opacity:1;max-height:var(--tbw-row-height, 28px);overflow:hidden}}@keyframes tbw-row-remove{0%{opacity:1;transform:translateY(0);max-height:var(--tbw-row-height, 28px)}to{opacity:0;max-height:0;transform:translateY(-8px)}}@keyframes tbw-spin{to{transform:rotate(360deg)}}@keyframes tbw-fade-in{0%{opacity:0}to{opacity:1}}
89
- @layer tbw-base{@media(forced-colors:active){tbw-grid{--tbw-color-border: CanvasText;--tbw-color-border-strong: CanvasText;--tbw-color-border-cell: CanvasText;--tbw-color-border-header: CanvasText;--tbw-color-fg: CanvasText;--tbw-color-bg: Canvas;--tbw-color-panel-bg: Canvas;--tbw-color-header-bg: Canvas;--tbw-color-header-fg: CanvasText;--tbw-color-accent: Highlight;--tbw-color-accent-fg: HighlightText;--tbw-color-selection: Highlight;--tbw-color-row-hover: Highlight;--tbw-focus-outline: 2px solid Highlight;--tbw-range-border-color: Highlight}tbw-grid .cell:focus,tbw-grid .cell.active-cell{outline:2px solid Highlight!important;outline-offset:-2px}tbw-grid .data-grid-row[aria-selected=true]{background:Highlight!important;color:HighlightText!important}}@media(prefers-reduced-motion:reduce){tbw-grid[data-animation-mode=reduced-motion]{--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}tbw-grid[data-animation-mode=reduced-motion] .data-grid-row[data-animating]{animation:none}}}
90
- `;class j extends HTMLElement{static tagName="tbw-grid";static version=typeof __GRID_VERSION__<"u"?__GRID_VERSION__:"dev";static#t=0;static adapters=[];static registerAdapter(e){this.adapters.push(e)}static getAdapters(){return this.adapters}static clearAdapters(){this.adapters=[]}static get observedAttributes(){return["rows","columns","grid-config","fit-mode","loading"]}get#e(){return this}#u=!1;#c;#r;#l=[];get#i(){return this.#s?.effective??{}}#h=!1;#w=!1;#y={rows:!1,columns:!1,gridConfig:!1,fitMode:!1};#d;#g=0;#a=null;#f=!1;#C=!1;#p=0;#R;#_=gr();#x;#E;#v;#m;#A={scrollTop:0,scrollLeft:0,scrollHeight:0,scrollWidth:0,clientHeight:0,clientWidth:0};#n;#S;#I=!1;#k;#U;#F;#s;#o=er();#b;#G;#B;#N=!1;#T=new Set;#D=new Map;#$;#L=new Map;_rows=[];#j=[];get _columns(){return this.#i.columns??[]}set _columns(e){this.#i.columns=e}get _visibleColumns(){return this._columns.filter(e=>!e.hidden)}_headerRowEl;_bodyEl;_rowPool=[];_resizeController;_virtualization={enabled:!0,rowHeight:28,bypassThreshold:24,start:0,end:0,container:null,viewportEl:null,totalHeightEl:null,positionCache:null,heightCache:{byKey:new Map,byRef:new WeakMap},averageHeight:28,measuredCount:0,variableHeights:!1,cachedViewportHeight:0,cachedFauxHeight:0,cachedScrollAreaHeight:0,scrollAreaEl:null};_focusRow=0;_focusCol=0;_restoreFocusAfterRender=!1;_sortState=null;_gridTemplate="";__rowRenderEpoch=0;__didInitialAutoSize=!1;get __lightDomColumnsCache(){return this.#s?.lightDomColumnsCache}set __lightDomColumnsCache(e){this.#s&&(this.#s.lightDomColumnsCache=e)}get __originalColumnNodes(){return this.#s?.originalColumnNodes}set __originalColumnNodes(e){this.#s&&(this.#s.originalColumnNodes=e)}__originalOrder=[];__frameworkAdapter;__rowsBodyEl=null;get rows(){return this._rows}set rows(e){const t=this.#l;this.#l=e,t!==e&&this.#V("rows")}get sourceRows(){return this.#l}get columns(){return[...this._columns]}set columns(e){const t=this.#s?.getColumns();this.#s?.setColumns(e),t!==e&&this.#V("columns")}get gridConfig(){return this.#i}set gridConfig(e){const t=this.#s?.getGridConfig();this.#s?.setGridConfig(e),t!==e&&(this.#s.clearLightDomCache(),this.#V("gridConfig"))}get fitMode(){return this.#i.fitMode??"stretch"}set fitMode(e){const t=this.#s?.getFitMode();this.#s?.setFitMode(e),t!==e&&this.#V("fitMode")}get loading(){return this.#N}set loading(e){const t=this.#N;this.#N=e,e?this.setAttribute("loading",""):this.removeAttribute("loading"),t!==e&&this.#he()}setRowLoading(e,t){const i=this.#T.has(e);t?this.#T.add(e):this.#T.delete(e),i!==t&&this.#Q(e,t)}setCellLoading(e,t,i){let n=this.#D.get(e);const o=n?.has(t)??!1;i?(n||(n=new Set,this.#D.set(e,n)),n.add(t)):(n?.delete(t),n?.size===0&&this.#D.delete(e)),o!==i&&this.#fe(e,t,i)}isRowLoading(e){return this.#T.has(e)}isCellLoading(e,t){return this.#D.get(e)?.has(t)??!1}clearAllLoading(){this.loading=!1;for(const e of this.#T)this.#Q(e,!1);this.#T.clear();for(const[e,t]of this.#D)for(const i of t)this.#fe(e,i,!1);this.#D.clear()}get effectiveConfig(){return this.#i}get disconnectSignal(){return this.#x||(this.#x=new AbortController),this.#x.signal}constructor(){super(),this.#be(),this.#c=new Promise(e=>this.#r=e),this.#d=new Wn({mergeConfig:()=>{this.#s.parseLightDomColumns(this),this.#s.merge(),this.#ie(),Rr(this.#i,this.#n?.getPlugins()??[]),Sr(this.#n?.getPlugins()??[]),Ar(this.#n?.getPlugins()??[]),this.#Ie(),this.#j=[...this._columns]},processColumns:()=>this.#Te(),processRows:()=>this.#Pe(),renderHeader:()=>Pe(this),updateTemplate:()=>he(this),renderVirtualWindow:()=>this.refreshVirtualWindow(!0,!0),afterRender:()=>{this.#n?.afterRender(),this._virtualization.enabled&&this._virtualization.totalHeightEl&&queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const t=this.#H(this._rows.length);this._virtualization.totalHeightEl.style.height=`${t}px`}),this.#i.fitMode==="fixed"&&!this.__didInitialAutoSize&&(this.__didInitialAutoSize=!0,_t(this)),this._restoreFocusAfterRender&&(this._restoreFocusAfterRender=!1,N(this)),this._virtualization.enabled&&!this.#K&&this.#Ce(),this.#C&&(this.#C=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.#ye()})})),this.#N&&this.#he()},isConnected:()=>this.isConnected&&this.#h}),this.#d.setInitialReadyResolver(()=>this.#r?.()),this.#b=lr(this.#o,{getShadow:()=>this.#e,getShellConfig:()=>this.#i?.shell,getAccordionIcons:()=>({expand:this.#i?.icons?.expand??K.expand,collapse:this.#i?.icons?.collapse??K.collapse}),emit:(e,t)=>this.#M(e,t),refreshShellHeader:()=>this.refreshShellHeader()}),this.#s=new yn({getRows:()=>this.#l,getSortState:()=>this._sortState,setSortState:e=>{this._sortState=e},onConfigChange:()=>{this.#d.requestPhase(O.FULL,"configChange")},emit:(e,t)=>this.#M(e,t),clearRowPool:()=>{this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++},setup:()=>this.#O(),renderHeader:()=>Pe(this),updateTemplate:()=>he(this),refreshVirtualWindow:()=>this.#d.requestPhase(O.VIRTUALIZATION,"configManager"),getVirtualization:()=>this._virtualization,setRowHeight:e=>{this._virtualization.rowHeight=e},applyAnimationConfig:e=>this.#He(e),getShellLightDomTitle:()=>this.#o.lightDomTitle,getShellToolPanels:()=>this.#o.toolPanels,getShellHeaderContents:()=>this.#o.headerContents,getShellToolbarContents:()=>this.#o.toolbarContents,getShellLightDomHeaderContent:()=>this.#o.lightDomHeaderContent,getShellHasToolButtonsContainer:()=>this.#o.hasToolButtonsContainer})}async#be(){await fr(Fr)}getPlugin(e){return this.#n?.getPlugin(e)}getPluginByName(e){return this.#n?.getPluginByName(e)}requestRender(){this.#d.requestPhase(O.ROWS,"plugin:requestRender")}requestColumnsRender(){this.#d.requestPhase(O.COLUMNS,"plugin:requestColumnsRender")}requestRenderWithFocus(){this._restoreFocusAfterRender=!0,this.#d.requestPhase(O.ROWS,"plugin:requestRenderWithFocus")}updateTemplate(){he(this)}requestAfterRender(){this.#d.requestPhase(O.STYLE,"plugin:requestAfterRender")}#te(){this.#n=new be(this);const e=this.#i?.plugins,t=Array.isArray(e)?e:[];this.#n.attachAll(t)}#W(){const e=this.#n?.getPluginStyles()??[];ur(e)}#ie(){const e=this.#i?.plugins,t=Array.isArray(e)?e:[];if(this.#S===t)return;if(this.#S&&this.#S.length===t.length&&this.#S.every((n,o)=>n===t[o])){this.#S=t;return}this.#n&&this.#n.detachAll();for(const n of this.#o.toolPanels.keys()){const o=this.#o.lightDomToolPanelIds.has(n),s=this.#o.apiToolPanelIds.has(n);if(!o&&!s){const l=this.#o.panelCleanups.get(n);l&&(l(),this.#o.panelCleanups.delete(n)),this.#o.toolPanels.delete(n)}}for(const n of this.#o.headerContents.keys()){const o=this.#o.headerContentCleanups.get(n);o&&(o(),this.#o.headerContentCleanups.delete(n)),this.#o.headerContents.delete(n)}this.#te(),this.#W(),this.#S=t,this.#se(),this.#ne();const i=this.#f;if(this.#f=this.#n?.getAll().some(n=>n.onScroll)??!1,!i&&this.#f){const o=this.#e.querySelector(".tbw-grid-content")??this.#e.querySelector(".tbw-grid-root");this.#Y(o)}}#ve(){this.#n?.detachAll()}#ne(){if(!this.#n)return;const e=this.#n.getToolPanels();for(const{panel:i}of e)this.#o.toolPanels.has(i.id)||this.#o.toolPanels.set(i.id,i);const t=this.#n.getHeaderContents();for(const{content:i}of t)this.#o.headerContents.has(i.id)||this.#o.headerContents.set(i.id,i)}#re(){const e=j.getAdapters();if(e.length===0&&!this.__frameworkAdapter)return;const t=this.__frameworkAdapter;return i=>{if(t?.createToolPanelRenderer){const n=t.createToolPanelRenderer(i);if(n)return n}for(const n of e)if(n.createToolPanelRenderer){const o=n.createToolPanelRenderer(i);if(o)return o}}}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=0),this.hasAttribute("version")||this.setAttribute("version",j.version),this.id||(this.id=`tbw-grid-${++j.#t}`),this._rows=Array.isArray(this.#l)?[...this.#l]:[],this.#x&&(this.#x.abort(),this.#I=!1),this.#x=new AbortController,this.#m&&($t(this.#m),this.#m=void 0),this.#q(),this.#s.parseLightDomColumns(this),this.#s.merge(),this.#te();const e=this.#i?.plugins;this.#S=Array.isArray(e)?e:[],this.#ne(),this.#u||(this.#ee(),this.#W(),this.#u=!0),this.#oe(),this.#m=zn(()=>{this.#Oe()},{timeout:100})}disconnectedCallback(){this.#m&&($t(this.#m),this.#m=void 0),this.#p&&(clearTimeout(this.#p),this.#p=0),this.#ve(),sr(this.#o),this.#b.setInitialized(!1),this.#G?.(),this.#G=void 0,this.#B?.(),this.#B=void 0,ii(this.#_),this.#x&&(this.#x.abort(),this.#x=void 0),this.#k?.abort(),this.#k=void 0,this.#I=!1,this._resizeController&&this._resizeController.dispose(),this.#E&&(this.#E.disconnect(),this.#E=void 0),this.#v&&(this.#v.disconnect(),this.#v=void 0,this.#K=!1),re(this),this.#P.clear(),this.#S=void 0;for(const e of this._rowPool)e.remove();this._rowPool.length=0,this.__rowsBodyEl=null,this.#h=!1}attributeChangedCallback(e,t,i){if(e==="loading"){const n=i!==null&&i!=="false";this.loading!==n&&(this.loading=n);return}if(!(t===i||!i||i==="null"||i==="undefined"))if(e==="rows"||e==="columns"||e==="grid-config")try{const n=JSON.parse(i);e==="rows"?this.rows=n:e==="columns"?this.columns=n:e==="grid-config"&&(this.gridConfig=n)}catch{console.warn(`[tbw-grid] Invalid JSON for '${e}' attribute:`,i)}else e==="fit-mode"&&(this.fitMode=i)}#oe(){const t=this.#e.querySelector(".tbw-grid-content")??this.#e.querySelector(".tbw-grid-root");if(this._headerRowEl=t?.querySelector(".header-row"),this._virtualization.totalHeightEl=t?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=t?.querySelector(".rows-viewport"),this._bodyEl=t?.querySelector(".rows"),this.__rowsBodyEl=t?.querySelector(".rows-body"),this.#b.isInitialized){Ye(this.#e,this.#o),je(this.#e,this.#i?.shell,this.#o);const n=this.#i?.shell?.toolPanel?.defaultOpen;n&&this.#o.toolPanels.has(n)&&(this.openToolPanel(),this.#o.expandedSections.add(n))}if(this.setAttribute("data-upgraded",""),this.#h=!0,this._resizeController=Wt(this),this.#O(),this.#Y(t),this.#I)return;this.#I=!0;const i=this.disconnectSignal;Hn(this,this,this.#e,i),this.#se(),queueMicrotask(()=>this.#xe()),this.#d.requestPhase(O.FULL,"afterConnect")}#se(){const e=this.#i.rowHeight,t=this.#n.hasRowHeightPlugin();typeof e=="function"||t?this._virtualization.variableHeights||(this._virtualization.variableHeights=!0,this._virtualization.rowHeight=typeof e=="number"&&e>0?e:this._virtualization.rowHeight||28,this.#J(),typeof e!="function"&&(this.#C=!0)):!t&&typeof e!="function"&&this._virtualization.variableHeights?(this._virtualization.variableHeights=!1,this._virtualization.positionCache=null):typeof e=="number"&&e>0?(this._virtualization.rowHeight=e,this._virtualization.variableHeights=!1):requestAnimationFrame(()=>this.#le())}#le(){if(this.#n.hasExtraHeight())return;const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;const t=e.querySelectorAll(".cell");let i=0;t.forEach(s=>{const l=s.offsetHeight;l>i&&(i=l)});const n=e.getBoundingClientRect(),o=Math.max(n.height,i);o>0&&Math.abs(o-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=o,this.#d.requestPhase(O.VIRTUALIZATION,"measureRowHeight"))}#ye(){const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;const t=e.querySelectorAll(".cell");let i=0;t.forEach(s=>{const l=s.offsetHeight;l>i&&(i=l)});const n=e.getBoundingClientRect(),o=Math.max(n.height,i);if(o>0&&(Math.abs(o-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=o),this.#J(),this._virtualization.totalHeightEl)){const l=this.#H(this._rows.length);this._virtualization.totalHeightEl.style.height=`${l}px`}}#Y(e){this.#k?.abort(),this.#k=new AbortController;const t=this.#k.signal,i=e?.querySelector(".faux-vscroll"),n=e?.querySelector(".rows");if(this._virtualization.container=i??this,this.#f=this.#n?.getAll().some(o=>o.onScroll)??!1,i&&n){i.addEventListener("scroll",()=>{if(!this._virtualization.enabled&&!this.#f)return;const a=i.scrollTop,c=this._virtualization.rowHeight;if(this._rows.length<=this._virtualization.bypassThreshold)n.style.transform=`translateY(${-a}px)`;else{const d=this._virtualization.positionCache;let u,h;if(this._virtualization.variableHeights&&d&&d.length>0){u=oi(d,a),u===-1&&(u=0);const g=u-u%2;h=d[g]?.offset??g*c}else u=Math.floor(a/c),h=(u-u%2)*c;const p=-(a-h);n.style.transform=`translateY(${p}px)`}this.#a=a,this.#g||(this.#g=requestAnimationFrame(()=>{this.#g=0,this.#a!==null&&(this.#De(this.#a),this.#a=null)}))},{passive:!0,signal:t});const o=this.#e.querySelector(".tbw-scroll-area");this.#U=o,this._virtualization.scrollAreaEl=o,o&&this.#f&&o.addEventListener("scroll",()=>{const a=this.#A;a.scrollTop=i.scrollTop,a.scrollLeft=o.scrollLeft,a.scrollHeight=i.scrollHeight,a.scrollWidth=o.scrollWidth,a.clientHeight=i.clientHeight,a.clientWidth=o.clientWidth,this.#n?.onScroll(a)},{passive:!0,signal:t});const s=this.#e.querySelector(".tbw-grid-content"),l=this.#U;s&&(s.addEventListener("wheel",a=>{const c=a.shiftKey||Math.abs(a.deltaX)>Math.abs(a.deltaY);if(c&&l){const d=a.shiftKey?a.deltaY:a.deltaX,{scrollLeft:u,scrollWidth:h,clientWidth:p}=l;(d>0&&u<h-p||d<0&&u>0)&&(a.preventDefault(),l.scrollLeft+=d)}else if(!c){const{scrollTop:d,scrollHeight:u,clientHeight:h}=i;(a.deltaY>0&&d<u-h||a.deltaY<0&&d>0)&&(a.preventDefault(),i.scrollTop+=a.deltaY)}},{passive:!1,signal:t}),yr(s,this.#_,{fauxScrollbar:i,scrollArea:l},t))}this._bodyEl&&Pn(this,this._bodyEl,t),this.#E?.disconnect(),this._virtualization.viewportEl&&(this.#E=new ResizeObserver(()=>{this.#Fe(),this.#d.requestPhase(O.VIRTUALIZATION,"resize-observer")}),this.#E.observe(this._virtualization.viewportEl)),this.#e.addEventListener("focusin",()=>{this.dataset.hasFocus=""},{signal:t}),this.#e.addEventListener("focusout",o=>{const s=o.relatedTarget;(!s||!this.#e.contains(s))&&delete this.dataset.hasFocus},{signal:t})}#K=!1;#Ce(){if(this.#K)return;const e=this._bodyEl?.querySelector(".data-grid-row");e&&(this.#K=!0,this.#v?.disconnect(),this.#v=new ResizeObserver(()=>{this.#le()}),this.#v.observe(e))}addEventListener(e,t,i){super.addEventListener(e,t,i)}removeEventListener(e,t,i){super.removeEventListener(e,t,i)}#M(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}#xe(){this._bodyEl?.querySelectorAll(".data-grid-row")?.forEach((t,i)=>{const n=i===this._focusRow;t.setAttribute("aria-selected",String(n)),t.querySelectorAll(".cell").forEach((o,s)=>{o.setAttribute("aria-selected",String(n&&s===this._focusCol))})})}#V(e){this.#y[e]=!0,!this.#w&&(this.#w=!0,queueMicrotask(()=>this.#Ee()))}#Ee(){if(!this.#w||!this.#h){this.#w=!1;return}const e=this.#y;if(this.#w=!1,this.#y={rows:!1,columns:!1,gridConfig:!1,fitMode:!1},e.gridConfig){this.#Ae(),e.rows&&this.#ae();return}e.columns&&this.#Se(),e.rows&&this.#ae(),e.fitMode&&this.#_e()}#ae(){this._rows=Array.isArray(this.#l)?[...this.#l]:[],this.#z(),this.#d.requestPhase(O.ROWS,"applyRowsUpdate")}#z(){this.#L.clear();const e=this.#i.getRowId;this._rows.forEach((t,i)=>{const n=this.#ce(t,e);n!==void 0&&this.#L.set(n,{row:t,index:i})})}#ce(e,t){if(t)return t(e);const i=e;if("id"in i&&i.id!=null)return String(i.id);if("_id"in i&&i._id!=null)return String(i._id)}#Re(e,t){const i=this.#ce(e,t);if(i===void 0)throw new Error('[tbw-grid] Cannot determine row ID. Configure getRowId in gridConfig or ensure rows have an "id" property.');return i}#Se(){re(this),this.#s.merge(),this.#O()}#_e(){this.#s.merge(),this.#i.fitMode==="fixed"?(this.__didInitialAutoSize=!1,_t(this)):(this._columns.forEach(t=>{!t.__userResized&&t.__autoSized&&delete t.width}),he(this))}#Ae(){Xt(this,this.#o),Qt(this,this.#o);const e=!!this.#e.querySelector(".has-shell"),t=!!this.#e.querySelector(".tbw-tool-panel"),i=this.#e.querySelectorAll(".tbw-accordion-section").length;this.#s.parseLightDomColumns(this),this.#s.merge(),this.#ie(),Zt(this,this.#o,this.#re()),this.#s.markSourcesChanged(),this.#s.merge();const n=Yt(this.#i?.shell),o=(this.#i?.shell?.toolPanels?.length??0)>0,s=this.#i?.shell?.toolPanels?.length??0;if(e!==n||!t&&o||t&&s!==i){Xe(this.#o),this.#ee(),this.#W(),this.#oe(),this.#z();return}e&&this.#ke(),this.#z(),this.#d.requestPhase(O.COLUMNS,"applyGridConfigUpdate")}#ke(){const e=this.#e.querySelector(".tbw-shell-header");if(!e)return;const t=this.#i.shell?.header?.title??this.#o.lightDomTitle;let i=e.querySelector(".tbw-shell-title");t?(i||(i=document.createElement("h2"),i.className="tbw-shell-title",i.setAttribute("part","shell-title"),e.insertBefore(i,e.firstChild)),i.textContent=t):i&&i.remove()}#Te(){if(this.__rowRenderEpoch++,this.#n){const e=this.#j.length>0?this.#j:this._columns,t=e.filter(o=>!o.hidden),i=e.filter(o=>o.hidden),n=this.#n.processColumns([...t]);if(n!==t){const o=new Set(n.map(l=>l.field));!t.some(l=>o.has(l.field))&&n.length>0?this._columns=[...n,...i]:this._columns=this.#Le(e,n,i)}else this._columns=[...e]}}#Le(e,t,i){if(i.length===0)return t;const n=new Map;for(const a of t)n.set(a.field,a);const o=new Set(e.map(a=>a.field)),s=[];for(const a of t)o.has(a.field)||s.push(a);const l=[];for(const a of e){const c=n.get(a.field);c?l.push(c):a.hidden&&l.push(a)}return l.push(...s),l}#Pe(){re(this);const e=Array.isArray(this.#l)?[...this.#l]:[],t=In(this,e),i=this.#n?.processRows(t)??t;this._rows=i,this.#z(),this._virtualization.variableHeights&&this.#J()}#He(e){const t={...xt,...e.animation},i=t.mode??"reduced-motion";let n=1;i===!1||i==="off"?n=0:(i===!0||i==="on")&&(n=1),this.style.setProperty("--tbw-animation-duration",`${t.duration}ms`),this.style.setProperty("--tbw-animation-easing",t.easing??"ease-out"),this.style.setProperty("--tbw-animation-enabled",String(n)),this.dataset.animationMode=typeof i=="boolean"?i?"on":"off":i}#X(e,t,i=this.__rowRenderEpoch){if(this.#R||(this.#R=(n,o,s)=>this.#n?.renderRow(n,o,s)??!1),Sn(this,e,t,i,this.#R),this.#T.size>0)for(const n of this.#T)this.#Q(n,!0)}#de=ue();#ue(e,t){tn(this.#de,this.__rowsBodyEl,this._bodyEl,e,t)}#Ie(){rn(this.#de,this.__rowsBodyEl,this.#i,this.#o)}#he(){const e=this.querySelector(".tbw-grid-root");e&&(this.#N?(this.#$||(this.#$=Nn(this.#i?.loadingRenderer)),qn(e,this.#$)):Gn(this.#$))}#Q(e,t){const i=this.#L.get(e);if(!i)return;const n=this.findRenderedRowElement?.(i.index);n&&Bn(n,t)}#fe(e,t,i){const n=this.#L.get(e);if(!n)return;const o=this.findRenderedRowElement?.(n.index);if(!o)return;const s=this._visibleColumns.findIndex(a=>a.field===t);if(s<0)return;const l=o.children[s];l&&$n(l,i)}#O(){if(this.isConnected&&!(!this._headerRowEl||!this._bodyEl)){if(this.#s.parseLightDomColumns(this),this.#F){const e=this.#F;this.#F=void 0,this.#s.merge();const t=this.#n?.getAll()??[];this.#s.applyState(e,t)}this._bodyEl&&(this._bodyEl.style.display="",this._bodyEl.style.gridTemplateColumns=""),this.#d.requestPhase(O.FULL,"setup")}}#De(e){let t=0,i=0,n=0,o=0,s=0;if(this.#f){const a=this._virtualization.container,c=this.#U;t=c?.scrollLeft??0,i=a?.scrollHeight??0,n=c?.scrollWidth??0,o=a?.clientHeight??0,s=c?.clientWidth??0}if(this.refreshVirtualWindow(!1)&&this.#n?.onScrollRender(),this._virtualization.variableHeights&&(this.#p&&clearTimeout(this.#p),this.#p=window.setTimeout(()=>{this.#p=0,this.#we(this._virtualization.start,this._virtualization.end)},100)),this.#f){const a=this.#A;a.scrollTop=e,a.scrollLeft=t,a.scrollHeight=i,a.scrollWidth=n,a.clientHeight=o,a.clientWidth=s,this.#n?.onScroll(a)}}findHeaderRow(){return this.#e.querySelector(".header-row")}findRenderedRowElement(e){return Array.from(this._bodyEl.querySelectorAll(".data-grid-row")).find(t=>{const i=t.querySelector(".cell[data-row]");return i&&Number(i.getAttribute("data-row"))===e})||null}_dispatchCellClick(e,t,i,n){const o=this._rows[t],s=this._visibleColumns[i];if(!o||!s)return!1;const l=s.field,a=o[l],c=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,composed:!0,detail:{rowIndex:t,colIndex:i,column:s,field:l,value:a,row:o,cellEl:n,trigger:"pointer",originalEvent:e}});if(this.dispatchEvent(c),c.defaultPrevented)return!0;const d={row:o,rowIndex:t,colIndex:i,column:s,field:l,value:a,cellEl:n,originalEvent:e},u=this.#n?.onCellClick(d)??!1;return this.#M("cell-click",d),u}_dispatchRowClick(e,t,i,n){if(!i)return!1;const o={rowIndex:t,row:i,rowEl:n,originalEvent:e},s=this.#n?.onRowClick(o)??!1;return this.#M("row-click",o),s}_dispatchHeaderClick(e,t,i){if(!t)return!1;const n={colIndex:this._columns.indexOf(t),field:t.field,column:t,headerEl:i,originalEvent:e};return this.#n?.onHeaderClick(n)??!1}_dispatchKeyDown(e){return this.#n?.onKeyDown(e)??!1}_getHorizontalScrollOffsets(e,t){return this.#n?.getHorizontalScrollOffsets(e,t)??{left:0,right:0}}queryPlugins(e){return this.#n?.queryPlugins(e)??[]}query(e,t){return this.#n?.queryPlugins({type:e,context:t})??[]}_dispatchCellMouseDown(e){return this.#n?.onCellMouseDown(e)??!1}_dispatchCellMouseMove(e){this.#n?.onCellMouseMove(e)}_dispatchCellMouseUp(e){this.#n?.onCellMouseUp(e)}_afterCellRender(e){this.#n?.afterCellRender(e)}_hasAfterCellRenderHook(){return this.#n?.hasAfterCellRenderHook()??!1}_afterRowRender(e){this.#n?.afterRowRender(e)}_hasAfterRowRenderHook(){return this.#n?.hasAfterRowRenderHook()??!1}async ready(){return this.#c}async forceLayout(){return this.#d.requestPhase(O.FULL,"forceLayout"),this.#d.whenReady()}async getConfig(){return Object.freeze({...this.#i||{}})}getRowId(e){return this.#Re(e,this.#i.getRowId)}getRow(e){return this.#L.get(e)?.row}_getRowEntry(e){return this.#L.get(e)}updateRow(e,t,i="api"){const n=this.#L.get(e);if(!n)throw new Error(`[tbw-grid] Row with ID "${e}" not found. Ensure the row exists and getRowId is correctly configured.`);const{row:o,index:s}=n,l=[];for(const[a,c]of Object.entries(t)){const d=o[a];d!==c&&(l.push({field:a,oldValue:d,newValue:c}),o[a]=c)}for(const{field:a,oldValue:c,newValue:d}of l)this.#M("cell-change",{row:o,rowId:e,rowIndex:s,field:a,oldValue:c,newValue:d,changes:t,source:i});l.length>0&&this.#d.requestPhase(O.ROWS,"updateRow")}updateRows(e,t="api"){let i=!1;for(const{id:n,changes:o}of e){const s=this.#L.get(n);if(!s)throw new Error(`[tbw-grid] Row with ID "${n}" not found. Ensure the row exists and getRowId is correctly configured.`);const{row:l,index:a}=s;for(const[c,d]of Object.entries(o)){const u=l[c];u!==d&&(i=!0,l[c]=d,this.#M("cell-change",{row:l,rowId:n,rowIndex:a,field:c,oldValue:u,newValue:d,changes:o,source:t}))}}i&&this.#d.requestPhase(O.ROWS,"updateRows")}animateRow(e,t){return Ue(this,e,t)}animateRows(e,t){return Xn(this,e,t)}animateRowById(e,t){return Qn(this,e,t)}async insertRow(e,t,i=!0){const n=Math.max(0,Math.min(e,this._rows.length));this.#l=[...this.#l,t];const o=[...this._rows];o.splice(n,0,t),this._rows=o,this._sortState&&(this.__originalOrder=[...this.__originalOrder,t]),re(this),this.#z(),this.__rowRenderEpoch++;for(const s of this._rowPool)s.__epoch=-1;this.refreshVirtualWindow(!0),i&&(await new Promise(s=>requestAnimationFrame(()=>s())),await this.animateRow(n,"insert"))}async removeRow(e,t=!0){const i=this._rows[e];if(!i)return;t&&await this.animateRow(e,"remove");const n=this._rows.indexOf(i);if(n<0)return i;const o=[...this._rows];o.splice(n,1),this._rows=o;const s=this.#l.indexOf(i);if(s>=0){const l=[...this.#l];l.splice(s,1),this.#l=l}if(this._sortState){const l=this.__originalOrder.indexOf(i);if(l>=0){const a=[...this.__originalOrder];a.splice(l,1),this.__originalOrder=a}}re(this),this.#z(),this.__rowRenderEpoch++;for(const l of this._rowPool)l.__epoch=-1;return this.refreshVirtualWindow(!0),t&&requestAnimationFrame(()=>{this.querySelectorAll('[data-animating="remove"]').forEach(l=>{l.removeAttribute("data-animating")})}),i}suspendProcessing(){}setColumnVisible(e,t){const i=this.#s.setColumnVisible(e,t);return i&&this.requestStateChange(),i}toggleColumnVisibility(e){const t=this.#s.toggleColumnVisibility(e);return t&&this.requestStateChange(),t}isColumnVisible(e){return this.#s.isColumnVisible(e)}showAllColumns(){this.#s.showAllColumns(),this.requestStateChange()}getAllColumns(){return this.#s.getAllColumns()}setColumnOrder(e){this.#s.setColumnOrder(e),this.requestStateChange()}getColumnOrder(){return this.#s.getColumnOrder()}getColumnState(){const e=this.#n?.getAll()??[];return this.#s.collectState(e)}set columnState(e){e&&(this.#F=e,this.#s.initialColumnState=e,this.#u&&this.#Me(e))}get columnState(){return this.getColumnState()}#Me(e){const t=this.#n?.getAll()??[];this.#s.applyState(e,t),this.#O()}requestStateChange(){const e=this.#n?.getAll()??[];this.#s.requestStateChange(e)}resetColumnState(){this.#F=void 0,this.__originalOrder=[];const e=this.#n?.getAll()??[];this.#s.resetState(e),this.#s.merge(),this.#O()}get isToolPanelOpen(){return this.#b.isPanelOpen}get defaultRowHeight(){return this._virtualization.rowHeight}get expandedToolPanelSections(){return this.#b.expandedSections}openToolPanel(){this.#b.openToolPanel()}closeToolPanel(){this.#b.closeToolPanel()}toggleToolPanel(){this.#b.toggleToolPanel()}toggleToolPanelSection(e){this.#b.toggleToolPanelSection(e)}getToolPanels(){return this.#b.getToolPanels()}registerToolPanel(e){this.#o.apiToolPanelIds.add(e.id),this.#b.registerToolPanel(e)}unregisterToolPanel(e){this.#o.apiToolPanelIds.delete(e),this.#b.unregisterToolPanel(e)}getHeaderContents(){return this.#b.getHeaderContents()}registerHeaderContent(e){this.#b.registerHeaderContent(e)}unregisterHeaderContent(e){this.#b.unregisterHeaderContent(e)}getToolbarContents(){return this.#b.getToolbarContents()}registerToolbarContent(e){this.#b.registerToolbarContent(e)}unregisterToolbarContent(e){this.#b.unregisterToolbarContent(e)}#Z=!1;refreshShellHeader(){this.#Z||(this.#Z=!0,queueMicrotask(()=>{this.#Z=!1,this.isConnected&&(this.#q(),this.#s.markSourcesChanged(),this.#s.merge(),Xe(this.#o),this.#ee(),this.#W(),this.#ze())}))}#ze(){const t=this.#e.querySelector(".tbw-grid-content")??this.#e.querySelector(".tbw-grid-root");if(this._headerRowEl=t?.querySelector(".header-row"),this._virtualization.totalHeightEl=t?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=t?.querySelector(".rows-viewport"),this._bodyEl=t?.querySelector(".rows"),this.__rowsBodyEl=t?.querySelector(".rows-body"),this.#b.isInitialized){Ye(this.#e,this.#o),je(this.#e,this.#i?.shell,this.#o);const i=this.#i?.shell?.toolPanel?.defaultOpen;i&&this.#o.toolPanels.has(i)&&(this.openToolPanel(),this.#o.expandedSections.add(i))}this._resizeController=Wt(this),this.#Y(t),this.#d.requestPhase(O.COLUMNS,"shellRefresh")}#P=new Map;registerStyles(e,t){let i=this.#P.get(e);i||(i=new CSSStyleSheet,this.#P.set(e,i)),i.replaceSync(t),this.#ge()}unregisterStyles(e){this.#P.delete(e)&&this.#ge()}getRegisteredStyles(){return Array.from(this.#P.keys())}#ge(){const e=Array.from(this.#P.values()),t=document.adoptedStyleSheets.filter(i=>!Array.from(this.#P.values()).includes(i));document.adoptedStyleSheets=[...t,...e]}#q(){Xt(this,this.#o),Qt(this,this.#o),Zt(this,this.#o,this.#re())}#pe(){const e=this.#e.querySelector(".tbw-shell-header");if(!e)return;Xe(this.#o);const t=tr(this.#i.shell,this.#o,this.#i.icons?.toolPanel),i=document.createElement("div");i.innerHTML=t;const n=i.firstElementChild;n&&(e.replaceWith(n),this.#me(),je(this.#e,this.#i?.shell,this.#o))}#Oe(){const e=()=>{const i=this.#o.lightDomTitle,n=this.#o.hasToolButtonsContainer;this.#q();const o=this.#o.lightDomTitle,s=this.#o.hasToolButtonsContainer;(o&&!i||s&&!n)&&(this.#s.markSourcesChanged(),this.#s.merge(),this.#pe())},t=()=>{this.__lightDomColumnsCache=void 0,this.#O()};this.#s.registerLightDomHandler("tbw-grid-header",e),this.#s.registerLightDomHandler("tbw-grid-tool-buttons",e),this.#s.registerLightDomHandler("tbw-grid-tool-panel",e),this.#s.registerLightDomHandler("tbw-grid-column",t),this.#s.registerLightDomHandler("tbw-grid-detail",t),this.#s.observeLightDOM(this)}refreshColumns(){this.__lightDomColumnsCache=void 0,re(this),this.#s.parseLightDomColumns(this);const e=this.#o.lightDomTitle,t=this.#o.hasToolButtonsContainer;this.#q();const i=this.#o.lightDomTitle,n=this.#o.hasToolButtonsContainer;(i&&!e||n&&!t)&&(this.#s.markSourcesChanged(),this.#s.merge(),this.#pe()),this.#d.requestPhase(O.COLUMNS,"refreshColumns")}#Fe(){const e=this._virtualization.container,t=this._virtualization.viewportEl??e;t&&(this._virtualization.cachedViewportHeight=t.clientHeight),e&&(this._virtualization.cachedFauxHeight=e.clientHeight);const i=this._virtualization.scrollAreaEl;i&&(this._virtualization.cachedScrollAreaHeight=i.clientHeight)}#H(e,t=!1){const i=this._virtualization;let n,o,s;if(t){const h=i.container??this,p=i.viewportEl??h,g=i.scrollAreaEl;n=h.clientHeight,o=p.clientHeight,s=g?g.clientHeight:n,i.cachedFauxHeight=n,i.cachedViewportHeight=o,i.cachedScrollAreaHeight=s}else n=i.cachedFauxHeight,o=i.cachedViewportHeight,s=i.cachedScrollAreaHeight||n;const l=s-o,a=Math.max(0,n-s);let c,d=0;return i.variableHeights&&i.positionCache?c=Pr(i.positionCache):(c=e*i.rowHeight,d=this.#n?.getExtraHeight()??0),c+l+d+a}#J(){if(!this._virtualization.variableHeights)return;const e=this._rows,t=this._virtualization.rowHeight||28,i=this.#i.rowHeight,n=this.#i.getRowId,o=n?l=>n(l):void 0;this._virtualization.positionCache=Lr(e,this._virtualization.heightCache,t,{rowId:o},(l,a)=>{const c=this.#n?.getRowHeight?.(l,a);if(c!==void 0)return c;if(i){const d=i(l,a);if(d!==void 0&&d>0)return d}});const s=Mr(this._virtualization.positionCache,e,t,(l,a)=>this.#n?.getRowHeight?.(l,a));this._virtualization.measuredCount=s.measuredCount,s.measuredCount>0&&(this._virtualization.averageHeight=s.averageHeight)}invalidateRowHeight(e,t){if(!this._virtualization.variableHeights||!this._virtualization.positionCache||e<0||e>=this._rows.length)return;const i=this._virtualization.positionCache,n=this._rows[e];let o=t;o===void 0&&(o=this.#n?.getRowHeight?.(n,e)),o===void 0&&(o=this._virtualization.rowHeight);const s=i[e];if(!(!s||Math.abs(s.height-o)<1)&&(tt(i,e,o),this._virtualization.totalHeightEl)){const l=this.#H(this._rows.length);this._virtualization.totalHeightEl.style.height=`${l}px`}}#we(e,t){if(!this._virtualization.variableHeights||!this._virtualization.positionCache||!this._bodyEl)return;const i=this._bodyEl.querySelectorAll(".data-grid-row"),n=this.#i.getRowId,o=Dr({positionCache:this._virtualization.positionCache,heightCache:this._virtualization.heightCache,rows:this._rows,defaultHeight:this._virtualization.rowHeight,start:e,end:t,getPluginHeight:(s,l)=>this.#n?.getRowHeight?.(s,l),getRowId:n?s=>n(s):void 0},i);if(o.hasChanges&&(this._virtualization.measuredCount=o.measuredCount,this._virtualization.averageHeight=o.averageHeight,this._virtualization.totalHeightEl)){const s=this.#H(this._rows.length);this._virtualization.totalHeightEl.style.height=`${s}px`}}refreshVirtualWindow(e=!1,t=!1){if(!this._bodyEl)return!1;const i=this._rows.length;if(!this._virtualization.enabled)return this.#X(0,i),t||this.#n?.afterRender(),!0;if(this._rows.length<=this._virtualization.bypassThreshold)return this._virtualization.start=0,this._virtualization.end=i,e&&(this._bodyEl.style.transform="translateY(0px)"),this.#X(0,i,this.__rowRenderEpoch),e&&this._virtualization.totalHeightEl&&(this._virtualization.totalHeightEl.style.height=`${this.#H(i,!0)}px`),this.#ue(i,this._visibleColumns.length),t||this.#n?.afterRender(),!0;const n=this._virtualization.container??this,o=this._virtualization.viewportEl??n,s=e?this._virtualization.cachedViewportHeight=o.clientHeight:this._virtualization.cachedViewportHeight||(this._virtualization.cachedViewportHeight=o.clientHeight),l=this._virtualization.rowHeight,a=n.scrollTop;let c;const d=this._virtualization.positionCache;if(this._virtualization.variableHeights&&d&&d.length>0)c=oi(d,a),c===-1&&(c=0);else{c=Math.floor(a/l);let b=0;const _=10;for(;b<_;){const T=this.#n?.getExtraHeightBefore?.(c)??0,A=Math.floor((a-T)/l);if(A>=c||A<0)break;c=A,b++}}c=c-c%2,c<0&&(c=0);const u=this.#n?.adjustVirtualStart(c,a,l);u!==void 0&&u<c&&(c=u,c=c-c%2,c<0&&(c=0));let h;if(this._virtualization.variableHeights&&d&&d.length>0){const b=s+l*3;let _=0;for(h=c;h<i&&_<b;)_+=d[h].height,h++;const T=Math.ceil(s/l)+3;h-c<T&&(h=Math.min(c+T,i))}else{const b=Math.ceil(s/l)+3;h=c+b}h>i&&(h=i);const p=this._virtualization.start,g=this._virtualization.end;if(!e&&c===p&&h===g)return!1;this._virtualization.start=c,this._virtualization.end=h;const f=e?this._virtualization.cachedFauxHeight=n.clientHeight:this._virtualization.cachedFauxHeight||(this._virtualization.cachedFauxHeight=n.clientHeight);if(e){const b=this._virtualization.scrollAreaEl;b&&(this._virtualization.cachedScrollAreaHeight=b.clientHeight)}if(f===0&&s>0)return this.#d.requestPhase(O.VIRTUALIZATION,"stale-refs-retry"),!1;if(e&&this._virtualization.totalHeightEl){const b=this.#H(i);this._virtualization.totalHeightEl.style.height=`${b}px`}let w;if(this._virtualization.variableHeights&&d&&d[c])w=d[c].offset;else{const b=this.#n?.getExtraHeightBefore?.(c)??0;w=c*l+b}const y=-(a-w);return this._bodyEl.style.transform=`translateY(${y}px)`,this.#X(c,h,this.__rowRenderEpoch),e&&this._virtualization.variableHeights&&this.#we(c,h),this.#ue(i,this._visibleColumns.length),e&&!t&&(this.#n?.afterRender(),queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const b=this.#H(i);this._virtualization.cachedFauxHeight===0&&this._virtualization.cachedViewportHeight>0||(this._virtualization.totalHeightEl.style.height=`${b}px`)})),!0}#ee(){this.#q(),this.#s.markSourcesChanged(),this.#s.merge();const e=this.#i?.shell;cr(this.#e,e,{isPanelOpen:this.#o.isPanelOpen,expandedSections:this.#o.expandedSections},this.#i?.icons)&&(this.#me(),this.#b.setInitialized(!0))}#me(){ir(this.#e,this.#i?.shell,this.#o,{onPanelToggle:()=>this.toggleToolPanel(),onSectionToggle:e=>this.toggleToolPanelSection(e)}),this.#G?.(),this.#G=rr(this.#e,this.#i?.shell,e=>{this.style.setProperty("--tbw-tool-panel-width",`${e}px`)}),this.#B?.(),this.#B=nr(this,this.#i?.shell,this.#o,()=>this.closeToolPanel())}}customElements.get(j.tagName)||customElements.define(j.tagName,j),globalThis.DataGridElement=j;const Nr={CAN_MOVE_COLUMN:"canMoveColumn",GET_CONTEXT_MENU_ITEMS:"getContextMenuItems"};class M{static dependencies;static manifest;version=typeof __GRID_VERSION__<"u"?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#t;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}attach(e){this.#t?.abort(),this.#t=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#t?.abort(),this.#t=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const i=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(i),i.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid}get disconnectSignal(){return this.#t?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...K,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(e===!1||e==="off")return!1;if(e===!0||e==="on")return!0;const t=this.gridElement;return t?getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()!=="0":!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),i=parseInt(t,10);if(!isNaN(i))return i}return 200}resolveIcon(e,t){return t!==void 0?t:this.gridIcons[e]}setIcon(e,t){typeof t=="string"?e.innerHTML=t:t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}warn(e){console.warn(`[tbw-grid:${this.name}] ${e}`)}}const q={ROOT:"tbw-grid-root",HEADER:"header",HEADER_ROW:"header-row",HEADER_CELL:"header-cell",ROWS_VIEWPORT:"rows-viewport",ROWS_SPACER:"rows-spacer",ROWS_CONTAINER:"rows",DATA_ROW:"data-row",GROUP_ROW:"group-row",DATA_CELL:"data-cell",SELECTED:"selected",FOCUSED:"focused",EDITING:"editing",EXPANDED:"expanded",COLLAPSED:"collapsed",DRAGGING:"dragging",RESIZING:"resizing",SORTABLE:"sortable",SORTED_ASC:"sorted-asc",SORTED_DESC:"sorted-desc",HIDDEN:"hidden",STICKY_LEFT:"sticky-left",STICKY_RIGHT:"sticky-right",PINNED_TOP:"pinned-top",PINNED_BOTTOM:"pinned-bottom",TREE_TOGGLE:"tree-toggle",TREE_INDENT:"tree-indent",GROUP_TOGGLE:"group-toggle",GROUP_LABEL:"group-label",GROUP_COUNT:"group-count",RANGE_SELECTION:"range-selection",SELECTION_OVERLAY:"selection-overlay"},ve={ROW_INDEX:"data-row-index",COL_INDEX:"data-col-index",FIELD:"data-field",GROUP_KEY:"data-group-key",TREE_LEVEL:"data-tree-level",STICKY:"data-sticky"},qr={ROOT:`.${q.ROOT}`,HEADER:`.${q.HEADER}`,HEADER_ROW:`.${q.HEADER_ROW}`,HEADER_CELL:`.${q.HEADER_CELL}`,ROWS_VIEWPORT:`.${q.ROWS_VIEWPORT}`,ROWS_CONTAINER:`.${q.ROWS_CONTAINER}`,DATA_ROW:`.${q.DATA_ROW}`,DATA_CELL:`.${q.DATA_CELL}`,GROUP_ROW:`.${q.GROUP_ROW}`,ROW_BY_INDEX:r=>`.${q.DATA_ROW}[${ve.ROW_INDEX}="${r}"]`,CELL_BY_FIELD:r=>`.${q.DATA_CELL}[${ve.FIELD}="${r}"]`,CELL_AT:(r,e)=>`.${q.DATA_ROW}[${ve.ROW_INDEX}="${r}"] .${q.DATA_CELL}[${ve.COL_INDEX}="${e}"]`,SELECTED_ROWS:`.${q.DATA_ROW}.${q.SELECTED}`,EDITING_CELL:`.${q.DATA_CELL}.${q.EDITING}`},Gr={COLOR_BG:"--tbw-color-bg",COLOR_FG:"--tbw-color-fg",COLOR_FG_MUTED:"--tbw-color-fg-muted",COLOR_BORDER:"--tbw-color-border",COLOR_ACCENT:"--tbw-color-accent",COLOR_HEADER_BG:"--tbw-color-header-bg",COLOR_HEADER_FG:"--tbw-color-header-fg",COLOR_SELECTION:"--tbw-color-selection",COLOR_ROW_HOVER:"--tbw-color-row-hover",COLOR_ROW_ALT:"--tbw-color-row-alt",ROW_HEIGHT:"--tbw-row-height",HEADER_HEIGHT:"--tbw-header-height",CELL_PADDING:"--tbw-cell-padding",FONT_FAMILY:"--tbw-font-family",FONT_SIZE:"--tbw-font-size",BORDER_RADIUS:"--tbw-border-radius",FOCUS_OUTLINE:"--tbw-focus-outline"};function Br(r){const e=document.createElement("tbw-grid");return r&&(e.gridConfig=r),e}function $r(r,e=document){return e.querySelector(r)}const Wr={CELL_CHANGE:"cell-change",CELL_COMMIT:"cell-commit",ROW_COMMIT:"row-commit",EDIT_OPEN:"edit-open",EDIT_CLOSE:"edit-close",CHANGED_ROWS_RESET:"changed-rows-reset",MOUNT_EXTERNAL_VIEW:"mount-external-view",MOUNT_EXTERNAL_EDITOR:"mount-external-editor",SORT_CHANGE:"sort-change",COLUMN_RESIZE:"column-resize",ACTIVATE_CELL:"activate-cell",CELL_ACTIVATE:"cell-activate",GROUP_TOGGLE:"group-toggle",COLUMN_STATE_CHANGE:"column-state-change"},Kr={SELECTION_CHANGE:"selection-change",TREE_EXPAND:"tree-expand",FILTER_CHANGE:"filter-change",SORT_MODEL_CHANGE:"sort-model-change",EXPORT_START:"export-start",EXPORT_COMPLETE:"export-complete",CLIPBOARD_COPY:"clipboard-copy",CLIPBOARD_PASTE:"clipboard-paste",CONTEXT_MENU_OPEN:"context-menu-open",CONTEXT_MENU_CLOSE:"context-menu-close",HISTORY_CHANGE:"history-change",SERVER_LOADING:"server-loading",SERVER_ERROR:"server-error",COLUMN_VISIBILITY_CHANGE:"column-visibility-change",COLUMN_REORDER:"column-reorder",DETAIL_EXPAND:"detail-expand",GROUP_EXPAND:"group-expand"};function De(r,e,t=!0){let i=r;if(t&&(i=i.filter(n=>!n.hidden&&!n.field.startsWith("__")&&n.meta?.utility!==!0)),e?.length){const n=new Set(e);i=i.filter(o=>n.has(o.field))}return i}function it(r,e){return e?.length?[...e].sort((t,i)=>t-i).map(t=>r[t]).filter(t=>t!=null):r}function Vr(r){return r==null?"":r instanceof Date?r.toISOString():typeof r=="object"?JSON.stringify(r):String(r)}async function Ur(r){try{return await navigator.clipboard.writeText(r),!0}catch(e){console.warn("[copyToClipboard] Clipboard API failed:",e);const t=document.createElement("textarea");t.value=r,t.style.position="fixed",t.style.opacity="0",t.style.pointerEvents="none",document.body.appendChild(t),t.select();const i=document.execCommand("copy");return document.body.removeChild(t),i}}function si(r,e){const t=e.delimiter??" ",i=e.newline??`
91
- `,n=r.replace(/\r\n/g,`
92
- `).replace(/\r/g,`
93
- `),o=[];let s=[],l="",a=!1;for(let c=0;c<n.length;c++){const d=n[c];d==='"'&&!a?a=!0:d==='"'&&a?n[c+1]==='"'?(l+='"',c++):a=!1:d===t&&!a?(s.push(l),l=""):d===i&&!a?(s.push(l),l="",(s.length>1||s.some(u=>u.trim()!==""))&&o.push(s),s=[]):l+=d}return s.push(l),(s.length>1||s.some(c=>c.trim()!==""))&&o.push(s),o}async function jr(){try{return await navigator.clipboard.readText()}catch{return""}}function li(r,e){const{rows:t,target:i,fields:n}=r;if(!i)return;const o=e.rows,s=e.effectiveConfig.columns??[],l=s.map(u=>u.field),a=new Map;s.forEach(u=>{a.set(u.field,u.editable===!0)});const c=[...o],d=i.bounds?i.bounds.endRow:1/0;t.forEach((u,h)=>{const p=i.row+h;if(!(p>d)){if(i.bounds){if(p>=c.length)return}else for(;p>=c.length;){const g={};l.forEach(f=>g[f]=""),c.push(g)}c[p]={...c[p]},u.forEach((g,f)=>{const w=n[f];w&&a.get(w)&&(c[p][w]=g)})}}),e.rows=c}class Yr extends M{static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:" ",newline:`
94
- `,quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e),e.addEventListener("paste",i=>this.#e(i),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(e){return(e.ctrlKey||e.metaKey)&&e.key==="c"?(e.preventDefault(),this.#t(e.target),!0):!1}#t(e){const t=this.#c();if(t&&t.ranges.length===0){const i=this.#i(e);if(!i)return;const n=this.columns[i.col];if(!n)return;this.copy({rowIndices:[i.row],columns:[n.field]});return}this.copy()}#e(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const i=si(t,this.config),n=this.#c(),o=n?.ranges?.[0],s=o?.from.row??0,l=o?.from.col??0,c=o&&(n?.mode==="range"||n?.mode==="row")&&(o.from.row!==o.to.row||o.from.col!==o.to.col)?{endRow:o.to.row,endCol:o.to.col}:null,d=c?.endCol??this.visibleColumns.length-1,u=this.visibleColumns[l],h=u?{row:s,col:l,field:u.field,bounds:c}:null,p=[],g=i[0]?.length??0;for(let w=0;w<g&&l+w<=d;w++){const y=this.visibleColumns[l+w];y&&p.push(y.field)}const f={rows:i,text:t,target:h,fields:p};this.emit("paste",f),this.#u(f)}#u(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(t===null)return;(t??li)(e,this.grid)}#c(){return this.grid?.query("getSelection")?.[0]}#r(e){const t=this.#c();let i;if(e?.columns)i=De(this.columns,e.columns);else if(t?.ranges.length&&t.mode!=="row"){const o=t.ranges[t.ranges.length-1],s=Math.min(o.from.col,o.to.col),l=Math.max(o.from.col,o.to.col);i=De(this.visibleColumns.slice(s,l+1))}else i=De(this.columns);let n;if(e?.rowIndices)n=it(this.rows,e.rowIndices);else if(t?.ranges.length){const o=t.ranges[t.ranges.length-1],s=Math.min(o.from.row,o.to.row),l=Math.max(o.from.row,o.to.row);n=[];for(let a=s;a<=l;a++){const c=this.rows[a];c&&n.push(c)}}else n=this.rows;return{columns:i,rows:n}}#l(e,t,i){const n=i?.delimiter??this.config.delimiter??" ",o=i?.newline??this.config.newline??`
95
- `,s=i?.includeHeaders??this.config.includeHeaders??!1,l=i?.processCell??this.config.processCell,a=[];s&&a.push(e.map(c=>c.header||c.field).join(n));for(const c of t){const d=e.map(u=>{const h=c[u.field];return l?l(h,u.field,c):Vr(h)});a.push(d.join(n))}return a.join(o)}#i(e){const t=e.closest("[data-field-cache]");if(!t)return null;const i=t.dataset.fieldCache,n=t.dataset.row;if(!i||!n)return null;const o=parseInt(n,10);if(isNaN(o))return null;const s=this.columns.findIndex(l=>l.field===i);return s===-1?null:{row:o,col:s}}getSelectionAsText(e){const{columns:t,rows:i}=this.#r(e);return t.length===0||i.length===0?"":this.#l(t,i,e)}async copy(e){const{columns:t,rows:i}=this.#r(e);if(t.length===0||i.length===0)return"";const n=this.#l(t,i,e);return await Ur(n),this.lastCopied={text:n,timestamp:Date.now()},this.emit("copy",{text:n,rowCount:i.length,columnCount:t.length}),n}async copyRows(e,t){return e.length===0?"":this.copy({...t,rowIndices:e})}async paste(){const e=await jr();return e?si(e,this.config):null}getLastCopied(){return this.lastCopied}}const ai=100;function nt(r){if(r==null)return ai;if(typeof r=="number")return r;const e=parseFloat(r);return isNaN(e)?ai:e}function ci(r){return r.map(e=>nt(e.width))}function di(r){const e=[];let t=0;for(const i of r)e.push(t),t+=nt(i.width);return e}function ui(r){return r.reduce((e,t)=>e+nt(t.width),0)}function Xr(r,e,t,i,n){const o=t.length;if(o===0)return{startCol:0,endCol:0,visibleColumns:[]};let s=Qr(r,t,i);s=Math.max(0,s-n);const l=r+e;let a=s;for(let d=s;d<o;d++){if(t[d]>=l){a=d-1;break}a=d}a=Math.min(o-1,a+n);const c=[];for(let d=s;d<=a;d++)c.push(d);return{startCol:s,endCol:a,visibleColumns:c}}function Qr(r,e,t){let i=0,n=e.length-1;for(;i<n;){const o=Math.floor((i+n)/2);e[o]+t[o]<=r?i=o+1:n=o}return i}function Zr(r,e,t){return t?r>e:!1}class Jr extends M{name="columnVirtualization";get defaultConfig(){return{autoEnable:!0,threshold:30,overscan:3}}isVirtualized=!1;startCol=0;endCol=0;scrollLeft=0;totalWidth=0;columnWidths=[];columnOffsets=[];originalColumns=[];attach(e){super.attach(e);const t=this.columns;this.columnWidths=ci(t),this.columnOffsets=di(t),this.totalWidth=ui(t),this.endCol=t.length-1}detach(){this.#t(),this.columnWidths=[],this.columnOffsets=[],this.originalColumns=[],this.isVirtualized=!1,this.startCol=0,this.endCol=0,this.scrollLeft=0,this.totalWidth=0}#t(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".header-row");t&&(t.style.paddingLeft="",t.style.minWidth=""),e.querySelectorAll(".data-grid-row").forEach(s=>{s.style.paddingLeft=""});const n=e.querySelector(".rows-viewport .rows");n&&(n.style.width="");const o=e.querySelector(".rows-body");o&&(o.style.minWidth="")}processColumns(e){(this.originalColumns.length===0||e.length>=this.originalColumns.length)&&(this.originalColumns=e,this.columnWidths=ci(e),this.columnOffsets=di(e),this.totalWidth=ui(e));const i=this.originalColumns,n=Zr(i.length,this.config.threshold??30,this.config.autoEnable??!0);if(this.isVirtualized=n??!1,!n)return this.startCol=0,this.endCol=i.length-1,[...i];const o=this.grid.clientWidth||800,s=Xr(this.scrollLeft,o,this.columnOffsets,this.columnWidths,this.config.overscan??3);return this.startCol=s.startCol,this.endCol=s.endCol,s.visibleColumns.map(l=>i[l])}afterRender(){if(!this.isVirtualized)return;const e=this.gridElement;if(!e)return;const t=this.columnOffsets[this.startCol]??0,i=e.querySelector(".header-row"),n=e.querySelectorAll(".data-grid-row");i&&(i.style.paddingLeft=`${t}px`,i.style.minWidth=`${this.totalWidth}px`),n.forEach(l=>{l.style.paddingLeft=`${t}px`});const o=e.querySelector(".rows-viewport .rows");o&&(o.style.width=`${this.totalWidth}px`);const s=e.querySelector(".rows-body");s&&(s.style.minWidth=`${this.totalWidth}px`)}onScroll(e){!this.isVirtualized||Math.abs(e.scrollLeft-this.scrollLeft)<1||(this.scrollLeft=e.scrollLeft,this.requestColumnsRender())}getIsVirtualized(){return this.isVirtualized}getVisibleColumnRange(){return{start:this.startCol,end:this.endCol}}scrollToColumn(e){const t=this.columnOffsets[e]??0,i=this.grid;i.scrollLeft=t}getColumnOffset(e){return this.columnOffsets[e]??0}getTotalWidth(){return this.totalWidth}}const rt="@layer tbw-plugins{.tbw-context-menu{position:fixed;background:var(--tbw-context-menu-bg, var(--tbw-color-panel-bg));color:var(--tbw-context-menu-fg, var(--tbw-color-fg));border:1px solid var(--tbw-context-menu-border, var(--tbw-color-border));border-radius:var(--tbw-context-menu-radius, var(--tbw-border-radius));box-shadow:var(--tbw-context-menu-shadow, 0 2px 10px var(--tbw-color-shadow));min-width:var(--tbw-context-menu-min-width, var(--tbw-menu-min-width));padding:var(--tbw-spacing-xs) 0;z-index:10000;font-size:var(--tbw-context-menu-font-size, var(--tbw-font-size-sm));font-family:var(--tbw-context-menu-font-family, var(--tbw-font-family))}.tbw-context-menu-item{display:flex;align-items:center;padding:var(--tbw-context-menu-item-padding, var(--tbw-menu-item-padding));cursor:pointer;gap:var(--tbw-context-menu-item-gap, var(--tbw-menu-item-gap))}.tbw-context-menu-item:hover:not(.disabled){background:var(--tbw-context-menu-hover, var(--tbw-color-row-hover))}.tbw-context-menu-item.disabled{opacity:.5;cursor:default}.tbw-context-menu-item.danger{color:var(--tbw-context-menu-danger, var(--tbw-color-danger))}.tbw-context-menu-icon{width:var(--tbw-context-menu-icon-size, var(--tbw-icon-size));text-align:center}.tbw-context-menu-label{flex:1}.tbw-context-menu-shortcut kbd{color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted));font-size:var(--tbw-context-menu-shortcut-size, var(--tbw-font-size-xs))}.tbw-context-menu-arrow{font-size:var(--tbw-context-menu-arrow-size, var(--tbw-font-size-2xs));color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted))}.tbw-context-menu-separator{height:1px;background:var(--tbw-context-menu-border, var(--tbw-color-border));margin:var(--tbw-spacing-xs) 0}}";function ot(r,e){return(typeof r=="function"?r(e):r).filter(i=>!(i.hidden===!0||typeof i.hidden=="function"&&i.hidden(e)))}function hi(r){const e=[];for(const t of r)t.separator&&(e.length===0||e[e.length-1].separator)||e.push(t);return e.length>0&&e[e.length-1].separator&&e.pop(),e}function eo(r,e){return r.disabled===!0?!0:typeof r.disabled=="function"?r.disabled(e):!1}function st(r,e,t,i=K.submenuArrow){const n=document.createElement("div");n.className="tbw-context-menu",n.setAttribute("role","menu");const o=r.some(s=>!s.separator&&s.icon);for(const s of r){if(s.separator){const d=document.createElement("div");d.className="tbw-context-menu-separator",d.setAttribute("role","separator"),n.appendChild(d);continue}const l=document.createElement("div");l.className="tbw-context-menu-item",s.cssClass&&l.classList.add(s.cssClass),l.setAttribute("role","menuitem"),l.setAttribute("data-id",s.id);const a=eo(s,e);if(a&&(l.classList.add("disabled"),l.setAttribute("aria-disabled","true")),s.icon){const d=document.createElement("span");d.className="tbw-context-menu-icon",d.innerHTML=s.icon,l.appendChild(d)}else if(o){const d=document.createElement("span");d.className="tbw-context-menu-icon",d.innerHTML="&nbsp;",l.appendChild(d)}const c=document.createElement("span");if(c.className="tbw-context-menu-label",c.textContent=s.name,l.appendChild(c),s.shortcut){const d=document.createElement("span");if(d.className="tbw-context-menu-shortcut",Array.isArray(s.shortcut))s.shortcut.forEach((u,h)=>{h>0&&d.appendChild(document.createTextNode("+"));const p=document.createElement("kbd");p.textContent=u,d.appendChild(p)});else{const u=document.createElement("kbd");u.textContent=s.shortcut,d.appendChild(u)}l.appendChild(d)}if(s.subMenu?.length){const d=document.createElement("span");d.className="tbw-context-menu-arrow",typeof i=="string"?d.innerHTML=i:i instanceof HTMLElement&&d.appendChild(i.cloneNode(!0)),l.appendChild(d),l.addEventListener("mouseenter",()=>{if(l.querySelector(".tbw-context-menu")||!s.subMenu)return;const h=ot(s.subMenu,e),p=st(h,e,t,i);p.classList.add("tbw-context-submenu"),p.style.position="absolute",p.style.left="100%",p.style.top="0",l.style.position="relative",l.appendChild(p)}),l.addEventListener("mouseleave",()=>{const u=l.querySelector(".tbw-context-menu");u&&u.remove()})}!a&&s.action&&!s.subMenu&&l.addEventListener("click",d=>{d.stopPropagation(),t(s)}),n.appendChild(l)}return n}function fi(r,e,t){r.style.position="fixed",r.style.left=`${e}px`,r.style.top=`${t}px`,r.style.visibility="hidden",r.style.zIndex="10000";const i=r.getBoundingClientRect(),n=window.innerWidth,o=window.innerHeight;let s=e,l=t;e+i.width>n&&(s=e-i.width),t+i.height>o&&(l=t-i.height),s=Math.max(0,s),l=Math.max(0,l),r.style.left=`${s}px`,r.style.top=`${l}px`,r.style.visibility="visible"}const gi="getContextMenuItems";let oe=null,se=null,Q=null,lt=0;const at=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:r=>{r.grid?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:r=>{r.grid?.plugins?.export?.exportCsv?.()}}];class ct extends M{static manifest={queries:[{type:gi,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:at}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),lt++}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,this.uninstallGlobalHandlers()}syncSelectionOnContextMenu(e){if(e<0)return[];const i=this.grid?.query("getSelectedRowIndices")?.[0];return i?i.includes(e)?i:(this.grid?.query("selectRows",[e]),[e]):[e]}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size"];copyGridStyles(e){const t=this.gridElement;if(!t)return;const i=getComputedStyle(t),n=[],o=i.getPropertyValue("color-scheme").trim();o&&n.push(`color-scheme: ${o}`);for(const s of ct.CSS_VARS_TO_COPY){const l=i.getPropertyValue(s).trim();l&&n.push(`${s}: ${l}`)}if(n.length>0){const s=e.getAttribute("style")||"";e.setAttribute("style",s+n.join("; ")+";")}}installGlobalHandlers(){!Q&&typeof document<"u"&&typeof rt=="string"&&rt&&(Q=document.createElement("style"),Q.id="tbw-context-menu-styles",Q.textContent=rt,document.head.appendChild(Q)),oe||(oe=()=>{document.querySelectorAll(".tbw-context-menu").forEach(t=>t.remove())},document.addEventListener("click",oe)),se||(se=e=>{e.key==="Escape"&&document.querySelectorAll(".tbw-context-menu").forEach(i=>i.remove())},document.addEventListener("keydown",se))}uninstallGlobalHandlers(){lt--,!(lt>0)&&(oe&&(document.removeEventListener("click",oe),oe=null),se&&(document.removeEventListener("keydown",se),se=null),Q&&(Q.remove(),Q=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(gi,e),i=[];for(const n of t)Array.isArray(n)&&i.push(...n);return i.sort((n,o)=>(n.order??100)-(o.order??100)),this.insertGroupSeparators(i)}insertGroupSeparators(e){if(e.length<=1)return e;const t=[];let i=-1;for(const n of e){if(n.separator){t.push(n);continue}const o=Math.floor((n.order??100)/10);i>=0&&o!==i&&t.push({id:`__sep-${i}-${o}`,label:"",separator:!0,action:()=>{}}),i=o,t.push(n)}return t}convertPluginItems(e){return e.map(t=>({id:t.id,name:t.label,icon:t.icon,shortcut:t.shortcut,disabled:t.disabled??!1,action:()=>t.action(),separator:t.separator,cssClass:t.cssClass}))}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root");t&&t.getAttribute("data-context-menu-bound")!=="true"&&(t.setAttribute("data-context-menu-bound","true"),t.addEventListener("contextmenu",i=>{const n=i;n.preventDefault();const o=n.target,s=o.closest("[data-row][data-col]"),l=o.closest('[part~="header-cell"]');let a;if(s){const u=parseInt(s.getAttribute("data-row")??"-1",10),h=parseInt(s.getAttribute("data-col")??"-1",10),p=this.visibleColumns[h],g=this.rows[u],f=this.syncSelectionOnContextMenu(u);a={row:g,rowIndex:u,column:p,columnIndex:h,field:p?.field??"",value:g?.[p?.field]??null,isHeader:!1,event:n,selectedRows:f}}else if(l){const u=parseInt(l.getAttribute("data-col")??"-1",10),h=this.visibleColumns[u];a={row:null,rowIndex:-1,column:h,columnIndex:u,field:h?.field??"",value:null,isHeader:!0,event:n,selectedRows:[]}}else return;this.params=a,this.position={x:n.clientX,y:n.clientY};const c=this.collectPluginItems(a);let d=ot(this.config.items??at,a);if(c.length>0){const u=this.convertPluginItems(c);d.length>0&&u.length>0?d=[...d,{id:"__plugin-sep",name:"",separator:!0},...u]:d=[...d,...u]}d=hi(d),d.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=st(d,a,u=>{u.action&&u.action(a),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),fi(this.menuElement,n.clientX,n.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:a,items:d}))}))}showMenu(e,t,i){const n={row:i.row??null,rowIndex:i.rowIndex??-1,column:i.column??null,columnIndex:i.columnIndex??-1,field:i.field??"",value:i.value??null,isHeader:i.isHeader??!1,event:i.event??new MouseEvent("contextmenu"),selectedRows:i.selectedRows??[]},o=this.collectPluginItems(n);let s=ot(this.config.items??at,n);if(o.length>0){const l=this.convertPluginItems(o);s.length>0&&l.length>0?s=[...s,{id:"__plugin-sep",name:"",separator:!0},...l]:s=[...s,...l]}s=hi(s),this.menuElement&&this.menuElement.remove(),this.menuElement=st(s,n,l=>{l.action&&l.action(n),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),fi(this.menuElement,e,t),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}const to="@layer tbw-plugins{tbw-grid{--tbw-editing-bg: var(--tbw-color-selection);--tbw-editing-row-bg: var(--tbw-editing-bg);--tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));--tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);--tbw-font-size-editor: inherit;--tbw-editing-row-outline-color: var(--tbw-color-accent);--tbw-editing-row-outline-width: 1px;--tbw-invalid-bg: light-dark(#fef2f2, #450a0a);--tbw-invalid-border-color: light-dark(#ef4444, #f87171)}tbw-grid:not(.tbw-grid-mode) .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:calc(var(--tbw-row-height) + 2px);align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}tbw-grid .data-grid-row>.cell[data-invalid=true]{background:var(--tbw-invalid-bg);outline:1px solid var(--tbw-invalid-border-color);outline-offset:-1px}}";function io(r){const e=r.options;return e?typeof e=="function"?e():e:[]}function no(r){return e=>{const t=r.editorParams,i=document.createElement("input");i.type="number",i.value=e.value!=null?String(e.value):"",t?.min!==void 0&&(i.min=String(t.min)),t?.max!==void 0&&(i.max=String(t.max)),t?.step!==void 0&&(i.step=String(t.step)),t?.placeholder&&(i.placeholder=t.placeholder);const n=()=>e.commit(i.value===""?null:Number(i.value));return i.addEventListener("blur",n),i.addEventListener("keydown",o=>{o.key==="Enter"&&n(),o.key==="Escape"&&e.cancel()}),i}}function ro(){return r=>{const e=document.createElement("input");return e.type="checkbox",e.checked=!!r.value,e.addEventListener("change",()=>r.commit(e.checked)),e}}function oo(r){return e=>{const t=r.editorParams,i=document.createElement("input");i.type="date",e.value instanceof Date?i.valueAsDate=e.value:typeof e.value=="string"&&e.value&&(i.value=e.value.split("T")[0]),t?.min&&(i.min=t.min),t?.max&&(i.max=t.max),t?.placeholder&&(i.placeholder=t.placeholder);const n=()=>{typeof e.value=="string"?e.commit(i.value):e.commit(i.valueAsDate)};return i.addEventListener("change",n),i.addEventListener("keydown",o=>{o.key==="Escape"&&e.cancel()}),i}}function so(r){return e=>{const t=r.editorParams,i=document.createElement("select");if(r.multi&&(i.multiple=!0),t?.includeEmpty){const s=document.createElement("option");s.value="",s.textContent=t.emptyLabel??"",i.appendChild(s)}io(r).forEach(s=>{const l=document.createElement("option");l.value=String(s.value),l.textContent=s.label,(r.multi&&Array.isArray(e.value)&&e.value.includes(s.value)||!r.multi&&e.value===s.value)&&(l.selected=!0),i.appendChild(l)});const o=()=>{if(r.multi){const s=Array.from(i.selectedOptions).map(l=>l.value);e.commit(s)}else e.commit(i.value)};return i.addEventListener("change",o),i.addEventListener("blur",o),i.addEventListener("keydown",s=>{s.key==="Escape"&&e.cancel()}),i}}function lo(r){return e=>{const t=r.editorParams,i=document.createElement("input");i.type="text",i.value=e.value!=null?String(e.value):"",t?.maxLength!==void 0&&(i.maxLength=t.maxLength),t?.pattern&&(i.pattern=t.pattern),t?.placeholder&&(i.placeholder=t.placeholder);const n=()=>{const o=i.value;(e.value===null||e.value===void 0)&&o===""||typeof e.value=="string"&&o===e.value.replace(/[\n\r]/g,"")||(typeof e.value=="number"&&o!==""?e.commit(Number(o)):e.commit(o))};return i.addEventListener("blur",n),i.addEventListener("keydown",o=>{o.key==="Enter"&&n(),o.key==="Escape"&&e.cancel()}),i}}function pi(r){switch(r.type){case"number":return no(r);case"boolean":return ro();case"date":return oo(r);case"select":return so(r);default:return lo(r)}}function ao(r,e){if(e.editor)return e.editor;if(e.__editorTemplate)return"template";if(!e.type)return;const i=r.effectiveConfig?.typeDefaults;if(i?.[e.type]?.editor)return i[e.type].editor;const n=r.__frameworkAdapter;if(n?.getTypeDefault){const o=n.getTypeDefault(e.type);if(o?.editor)return o.editor}}function ye(r){return!(typeof r!="string"||r==="__proto__"||r==="constructor"||r==="prototype")}function co(r){const e=(r.__editingCellCount??0)+1;r.__editingCellCount=e,r.setAttribute("data-has-editing","")}function uo(r){r.__editingCellCount=0,r.removeAttribute("data-has-editing")}function le(r,e,t){return r instanceof HTMLInputElement?r.type==="checkbox"?r.checked:r.type==="number"?r.value===""?null:Number(r.value):r.type==="date"?typeof t=="string"?r.value:r.valueAsDate:typeof t=="number"?r.value===""?null:Number(r.value):t==null&&r.value===""||typeof t=="string"&&r.value===t.replace(/[\n\r]/g,"")?t:r.value:e?.type==="number"&&r.value!==""||typeof t=="number"&&r.value!==""?Number(r.value):t==null&&r.value===""?t:r.value}function wi(r){}function ho(r,e,t,i){const n=r.querySelector("input,textarea,select");n&&(n.addEventListener("blur",()=>{t(le(n,e,i))}),n instanceof HTMLInputElement&&n.type==="checkbox"?n.addEventListener("change",()=>t(n.checked)):n instanceof HTMLSelectElement&&n.addEventListener("change",()=>t(le(n,e,i))))}class fo extends M{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>e===!0},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'}],events:[{type:"cell-edit-committed",description:"Emitted when a cell edit is committed (for plugin-to-plugin coordination)"}],queries:[{type:"isEditing",description:"Returns whether any cell is currently being edited"}]};name="editing";styles=to;get defaultConfig(){return{mode:"row",editOn:"click"}}get#t(){return this.config.mode==="grid"}#e=-1;#u;#c;#r=-1;#l=new Map;#i=new Set;#h=new Set;#w=new Map;#y=!1;#d=-1;#g=new Map;#a=!1;#f=!1;#C=!1;attach(e){super.attach(e);const t=this.disconnectSignal,i=e;i._activeEditRows=-1,i._rowEditSnapshots=new Map,Object.defineProperty(e,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(e,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),e.resetChangedRows=n=>this.resetChangedRows(n),e.beginBulkEdit=(n,o)=>{o&&this.beginCellEdit(n,o)},document.addEventListener("keydown",n=>{if(!this.#t&&n.key==="Escape"&&this.#e!==-1){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(n)===!1)return;this.#m(this.#e,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",n=>{if(this.#t||this.#e===-1)return;const o=i.findRenderedRowElement?.(this.#e);!o||(n.composedPath&&n.composedPath()||[]).includes(o)||this.config.onBeforeEditClose&&this.config.onBeforeEditClose(n)===!1||queueMicrotask(()=>{this.#e!==-1&&this.#m(this.#e,!1)})},{signal:t}),this.gridElement.addEventListener("cell-change",n=>{const o=n.detail;if(o.source==="user")return;const s=`${o.rowIndex}:${o.field}`,l=this.#w.get(s);l&&l(o.newValue)},{signal:t}),this.#t&&(i._isGridEditMode=!0,this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",n=>{const o=n.target;if(o.matches(V)){if(this.#f){o.blur(),this.gridElement.focus();return}this.#a=!0}},{signal:t}),this.gridElement.addEventListener("focusout",n=>{const o=n.relatedTarget;(!o||!this.gridElement.contains(o)||!o.matches(V))&&(this.#a=!1)},{signal:t}),this.gridElement.addEventListener("keydown",n=>{if(n.key==="Escape"&&this.#a){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(n)===!1)return;const o=document.activeElement;o&&this.gridElement.contains(o)&&(o.blur(),this.gridElement.focus()),this.#a=!1,this.#f=!0,n.preventDefault(),n.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",n=>{n.target.matches(V)&&(this.#f=!1)},{signal:t}))}detach(){const e=this.gridElement;e._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#e=-1,this.#u=void 0,this.#c=void 0,this.#r=-1,this.#l.clear(),this.#i.clear(),this.#h.clear(),this.#w.clear(),this.#a=!1,this.#f=!1,this.#C=!1,super.detach()}handleQuery(e){if(e.type==="isEditing")return this.#t||this.#e!==-1}onCellClick(e){if(this.#t)return!1;const t=this.grid,i=this.config.editOn??t.effectiveConfig?.editOn;if(i===!1||i==="manual"||i!=="click"&&i!=="dblclick")return!1;const n=e.originalEvent.type==="dblclick";if(i==="click"&&n||i==="dblclick"&&!n)return!1;const{rowIndex:o}=e;return t._columns?.some(l=>l.editable)?(e.originalEvent.stopPropagation(),this.beginBulkEdit(o),!0):!1}onKeyDown(e){const t=this.grid;if(e.key==="Escape"){if(this.#t&&this.#a){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1)return!0;const i=document.activeElement;return i&&this.gridElement.contains(i)&&i.blur(),this.#a=!1,this.requestAfterRender(),!0}if(this.#e!==-1&&!this.#t)return this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1||this.#m(this.#e,!0),!0}if(this.#t&&!this.#a&&(e.key==="ArrowUp"||e.key==="ArrowDown"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return!1;if(this.#t&&this.#a&&(e.key==="ArrowUp"||e.key==="ArrowDown"))return!0;if((e.key==="ArrowUp"||e.key==="ArrowDown")&&this.#e!==-1&&!this.#t){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1)return!0;const i=t._rows.length-1,n=this.#e;return this.#m(n,!1),e.key==="ArrowDown"?t._focusRow=Math.min(i,t._focusRow+1):t._focusRow=Math.max(0,t._focusRow-1),e.preventDefault(),N(t),this.requestAfterRender(),!0}if(e.key==="Tab"&&(this.#e!==-1||this.#t)){if(e.preventDefault(),this.#C)return this.#m(this.#e,!1),!0;const i=!e.shiftKey;return this.#x(i),!0}if(e.key===" "||e.key==="Spacebar"){if(this.#e!==-1)return!1;const i=t._focusRow,n=t._focusCol;if(i>=0&&n>=0){const o=t._visibleColumns[n],s=t._rows[i];if(o?.editable&&o.type==="boolean"&&s){const l=o.field;if(ye(l)){const c=!s[l];return this.#A(i,o,c,s),e.preventDefault(),this.requestRender(),!0}}}return!1}if(e.key==="Enter"&&!e.shiftKey&&!e.ctrlKey&&!e.altKey&&!e.metaKey){if(this.#t&&!this.#a)return this.#_(),!0;if(this.#e!==-1)return!!(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1);const i=this.config.editOn??t.effectiveConfig?.editOn;if(i===!1||i==="manual")return!1;const n=t._focusRow,o=t._focusCol;if(n>=0&&t._columns?.some(l=>l.editable)){const l=t._visibleColumns[o],a=t._rows[n],c=l?.field??"",d=c&&a?a[c]:void 0,u=this.gridElement.querySelector(`[data-row="${n}"][data-col="${o}"]`),h=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:n,colIndex:o,field:c,value:d,row:a,cellEl:u,trigger:"keyboard",originalEvent:e}});this.gridElement.dispatchEvent(h);const p=new CustomEvent("activate-cell",{cancelable:!0,bubbles:!0,detail:{row:n,col:o}});return this.gridElement.dispatchEvent(p),h.defaultPrevented||p.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(n),!0)}return!1}if(e.key==="F2"){if(this.#e!==-1||this.#t||(this.config.editOn??t.effectiveConfig?.editOn)===!1)return!1;const n=t._focusRow,o=t._focusCol;if(n>=0&&o>=0){const s=t._visibleColumns[o];if(s?.editable&&s.field)return e.preventDefault(),this.beginCellEdit(n,s.field),!0}return!1}return!1}processColumns(e){const t=this.grid,i=t.effectiveConfig?.typeDefaults,n=t.__frameworkAdapter;return!i&&!n?.getTypeDefault?e:e.map(o=>{if(!o.type)return o;let s;if(i?.[o.type]?.editorParams&&(s=i[o.type].editorParams),!s&&n?.getTypeDefault){const l=n.getTypeDefault(o.type);l?.editorParams&&(s=l.editorParams)}return s?{...o,editorParams:{...s,...o.editorParams}}:o})}afterRender(){const e=this.grid;if(this.#y&&(this.#y=!1,this.#k(e)),this.#d!==-1){const t=this.#d;this.#d=-1,e.animateRow?.(t,"change")}if(!this.#t&&this.#h.size!==0)for(const t of this.#h){const[i,n]=t.split(":"),o=parseInt(i,10),s=parseInt(n,10),l=e.findRenderedRowElement?.(o);if(!l)continue;const a=l.querySelector(`.cell[data-col="${s}"]`);if(!a||a.classList.contains("editing"))continue;const c=e._rows[o],d=e._visibleColumns[s];c&&d&&this.#n(c,o,d,s,a,!0)}}afterCellRender(e){if(!this.#t)return;const{row:t,rowIndex:i,column:n,colIndex:o,cellElement:s}=e;n.editable&&(s.classList.contains("editing")||this.#n(t,i,n,o,s,!0))}onScrollRender(){this.afterRender()}get changedRows(){const e=[];for(const t of this.#i){const i=this.grid.getRow(t);i&&e.push(i)}return e}get changedRowIds(){return Array.from(this.#i)}get activeEditRow(){return this.#e}get activeEditCol(){return this.#r}isRowEditing(e){return this.#e===e}isCellEditing(e,t){return this.#h.has(`${e}:${t}`)}isRowChanged(e){const t=this.grid,i=t._rows[e];if(!i)return!1;try{const n=t.getRowId?.(i);return n?this.#i.has(n):!1}catch{return!1}}isRowChangedById(e){return this.#i.has(e)}setInvalid(e,t,i=""){let n=this.#g.get(e);n||(n=new Map,this.#g.set(e,n)),n.set(t,i),this.#p(e,t,!0)}clearInvalid(e,t){const i=this.#g.get(e);i&&(i.delete(t),i.size===0&&this.#g.delete(e)),this.#p(e,t,!1)}clearRowInvalid(e){const t=this.#g.get(e);if(t){const i=Array.from(t.keys());this.#g.delete(e),i.forEach(n=>this.#p(e,n,!1))}}clearAllInvalid(){const e=Array.from(this.#g.entries());this.#g.clear(),e.forEach(([t,i])=>{i.forEach((n,o)=>this.#p(t,o,!1))})}isCellInvalid(e,t){return this.#g.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#g.get(e)?.get(t)}hasInvalidCells(e){const t=this.#g.get(e);return t?t.size>0:!1}getInvalidFields(e){return new Map(this.#g.get(e)??[])}#p(e,t,i){const n=this.grid,o=n._visibleColumns?.findIndex(d=>d.field===t);if(o===-1||o===void 0)return;const l=n._rows?.findIndex(d=>{try{return n.getRowId?.(d)===e}catch{return!1}});if(l===-1||l===void 0)return;const c=n.findRenderedRowElement?.(l)?.querySelector(`.cell[data-col="${o}"]`);if(c)if(i){c.setAttribute("data-invalid","true");const d=this.#g.get(e)?.get(t);d&&c.setAttribute("title",d)}else c.removeAttribute("data-invalid"),c.removeAttribute("title")}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#i.clear(),this.#E(),e||this.emit("changed-rows-reset",{rows:t,ids:i}),this.grid._rowPool?.forEach(o=>o.classList.remove("changed"))}beginCellEdit(e,t){const i=this.grid,n=i._visibleColumns.findIndex(a=>a.field===t);if(n===-1||!i._visibleColumns[n]?.editable)return;const l=i.findRenderedRowElement?.(e)?.querySelector(`.cell[data-col="${n}"]`);l&&(this.#C=!0,this.#R(e,n,l))}beginBulkEdit(e){const t=this.grid;if((this.config.editOn??t.effectiveConfig?.editOn)===!1||!t._columns?.some(l=>l.editable))return;const o=t.findRenderedRowElement?.(e);if(!o)return;this.#C=!1;const s=t._rows[e];this.#v(e,s),Array.from(o.children).forEach((l,a)=>{const c=t._visibleColumns[a];if(c?.editable){const d=l;d.classList.contains("editing")||this.#n(s,e,c,a,d,!0)}}),setTimeout(()=>{let l=o.querySelector(`.cell[data-col="${t._focusCol}"]`);if(l?.classList.contains("editing")||(l=o.querySelector(".cell.editing")),l?.classList.contains("editing")){const a=l.querySelector(V);try{a?.focus({preventScroll:!0})}catch{}}},0)}commitActiveRowEdit(){this.#e!==-1&&this.#m(this.#e,!1)}cancelActiveRowEdit(){this.#e!==-1&&this.#m(this.#e,!0)}#R(e,t,i){const n=this.grid,o=n._rows[e],s=n._visibleColumns[t];!o||!s?.editable||i.classList.contains("editing")||(this.#e!==e&&this.#v(e,o),this.#r=t,this.#n(o,e,s,t,i,!1))}#_(){const e=this.grid,t=e._focusRow,i=e._focusCol;if(t<0||i<0)return;const o=e.findRenderedRowElement?.(t)?.querySelector(`.cell[data-col="${i}"]`);if(o?.classList.contains("editing")){const s=o.querySelector(V);s&&(this.#f=!1,s.focus(),this.#a=!0,s instanceof HTMLInputElement&&(s.type==="text"||s.type==="number")&&s.select())}}#x(e){const t=this.grid,i=t._rows,n=this.#t?t._focusRow:this.#e,o=t._visibleColumns.map((c,d)=>c.editable?d:-1).filter(c=>c>=0);if(o.length===0)return;const l=o.indexOf(t._focusCol)+(e?1:-1);if(l>=0&&l<o.length){t._focusCol=o[l];const d=t.findRenderedRowElement?.(n)?.querySelector(`.cell[data-col="${o[l]}"]`);d?.classList.contains("editing")&&d.querySelector(V)?.focus({preventScroll:!0}),N(t,{forceHorizontalScroll:!0});return}const a=n+(e?1:-1);a>=0&&a<i.length&&(this.#t?(t._focusRow=a,t._focusCol=e?o[0]:o[o.length-1],N(t,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const d=t.findRenderedRowElement?.(a)?.querySelector(`.cell[data-col="${t._focusCol}"]`);d?.classList.contains("editing")&&d.querySelector(V)?.focus({preventScroll:!0})},0)):(this.#m(n,!1),t._focusRow=a,t._focusCol=e?o[0]:o[o.length-1],this.beginBulkEdit(a),N(t,{forceHorizontalScroll:!0})))}#E(){const e=this.grid;e._activeEditRows=this.#e,e._rowEditSnapshots=this.#l}#v(e,t){if(this.#e!==e){this.#l.set(e,{...t}),this.#e=e,this.#c=t;const i=this.grid;try{this.#u=i.getRowId?.(t)??void 0}catch{this.#u=void 0}this.#E(),this.#t||this.emit("edit-open",{rowIndex:e,rowId:this.#u??"",row:t})}}#m(e,t){if(this.#e!==e)return;const i=this.grid,n=this.#l.get(e),o=i.findRenderedRowElement?.(e);let s=this.#u;const a=(s?i._getRowEntry(s):void 0)?.row??this.#c??i._rows[e];if(!s&&a)try{s=i.getRowId?.(a)}catch{}if(!t&&o&&a&&o.querySelectorAll(".cell.editing").forEach(d=>{const u=Number(d.getAttribute("data-col"));if(isNaN(u))return;const h=i._visibleColumns[u];if(!h||d.hasAttribute("data-editor-managed"))return;const p=d.querySelector("input,textarea,select");if(p){const g=h.field,f=a[g],w=le(p,h,f);f!==w&&this.#A(e,h,w,a)}}),t&&n&&a)Object.keys(n).forEach(c=>{a[c]=n[c]}),s&&(this.#i.delete(s),this.clearRowInvalid(s));else if(!t&&a){const c=this.#I(n,a),d=s?this.#i.has(s):c,u=this.emitCancelable("row-commit",{rowIndex:e,rowId:s??"",row:a,oldValue:n,newValue:a,changed:d,changedRows:this.changedRows,changedRowIds:this.changedRowIds});u&&n?(Object.keys(n).forEach(h=>{a[h]=n[h]}),s&&(this.#i.delete(s),this.clearRowInvalid(s))):!u&&c&&this.isAnimationEnabled&&(this.#d=e)}this.#l.delete(e),this.#e=-1,this.#u=void 0,this.#c=void 0,this.#r=-1,this.#C=!1,this.#E();for(const c of this.#h)c.startsWith(`${e}:`)&&this.#h.delete(c);for(const c of this.#w.keys())c.startsWith(`${e}:`)&&this.#w.delete(c);this.#y=!0,o?(o.querySelectorAll(".cell.editing").forEach(c=>{c.classList.remove("editing"),uo(c.parentElement)}),i.refreshVirtualWindow(!0)):(this.#k(i),this.#y=!1),!this.#t&&a&&this.emit("edit-close",{rowIndex:e,rowId:s??"",row:a,reverted:t})}#A(e,t,i,n){const o=t.field;if(!ye(o))return;const s=n[o];if(s===i)return;const l=this.grid;let a;try{a=this.grid.getRowId(n)}catch{}const c=a?!this.#i.has(a):!0,d=a?f=>this.grid.updateRow(a,f,"cascade"):wi;let u=!1;const h=a?f=>{u=!0,this.setInvalid(a,o,f??"")}:()=>{};if(this.emitCancelable("cell-commit",{row:n,rowId:a??"",field:o,oldValue:s,value:i,rowIndex:e,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:c,updateRow:d,setInvalid:h}))return;a&&!u&&this.isCellInvalid(a,o)&&this.clearInvalid(a,o),n[o]=i,a&&this.#i.add(a),this.#E(),this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:o,oldValue:s,newValue:i});const g=l.findRenderedRowElement?.(e);g&&g.classList.add("changed")}#n(e,t,i,n,o,s){if(!i.editable||o.classList.contains("editing"))return;let l;try{l=this.grid.getRowId(e)}catch{}const a=l?C=>this.grid.updateRow(l,C,"cascade"):wi,c=ye(i.field)?e[i.field]:void 0;o.classList.add("editing"),this.#h.add(`${t}:${n}`);const d=o.parentElement;d&&co(d);let u=!1;const h=C=>{if(u||!this.#t&&this.#e===-1)return;const v=this.grid,E=l?v._getRowEntry(l):void 0,m=E?.row??e,k=E?.index??t;this.#A(k,i,C,m)},p=()=>{if(u=!0,ye(i.field)){const C=this.grid,E=(l?C._getRowEntry(l):void 0)?.row??e;E[i.field]=c}},g=document.createElement("div");g.className="tbw-editor-host",o.innerHTML="",o.appendChild(g),g.addEventListener("keydown",C=>{if(C.key==="Enter"){if(this.#t){C.stopPropagation(),C.preventDefault();const v=g.querySelector("input,textarea,select");v&&h(le(v,i,c));return}if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(C)===!1)return;C.stopPropagation(),C.preventDefault(),u=!0,this.#m(t,!1)}if(C.key==="Escape"){if(this.#t){C.stopPropagation(),C.preventDefault();return}if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(C)===!1)return;C.stopPropagation(),C.preventDefault(),p(),this.#m(t,!0)}});const f=i,w=f.__editorTemplate,y=ao(this.grid,f)??pi(i),b=c,_=`${t}:${i.field}`,T=[];this.#w.set(_,C=>{for(const v of T)v(C)});const A=C=>{T.push(C)};if(y==="template"&&w)this.#S(g,f,e,c,h,p,s,t),A(C=>{const v=g.querySelector("input,textarea,select");v&&(v instanceof HTMLInputElement&&v.type==="checkbox"?v.checked=!!C:v.value=String(C??""))});else if(typeof y=="string"){const C=document.createElement(y);C.value=b,C.addEventListener("change",()=>h(C.value)),A(v=>{C.value=v}),g.appendChild(C),s||queueMicrotask(()=>{g.querySelector(V)?.focus({preventScroll:!0})})}else if(typeof y=="function"){const C={row:e,rowId:l??"",value:b,field:i.field,column:i,commit:h,cancel:p,updateRow:a,onValueChange:A},v=y(C);typeof v=="string"?(g.innerHTML=v,ho(g,i,h,c),A(E=>{const m=g.querySelector("input,textarea,select");m&&(m instanceof HTMLInputElement&&m.type==="checkbox"?m.checked=!!E:m.value=String(E??""))})):v instanceof Node&&(g.appendChild(v),v instanceof HTMLInputElement||v instanceof HTMLSelectElement||v instanceof HTMLTextAreaElement?A(m=>{v instanceof HTMLInputElement&&v.type==="checkbox"?v.checked=!!m:v.value=String(m??"")}):o.setAttribute("data-editor-managed","")),s||queueMicrotask(()=>{g.querySelector(V)?.focus({preventScroll:!0})})}else if(y&&typeof y=="object"){const C=document.createElement("div");C.setAttribute("data-external-editor",""),C.setAttribute("data-field",i.field),g.appendChild(C),o.setAttribute("data-editor-managed","");const v={row:e,rowId:l??"",value:b,field:i.field,column:i,commit:h,cancel:p,updateRow:a,onValueChange:A};if(y.mount)try{y.mount({placeholder:C,context:v,spec:y})}catch(E){console.warn(`[tbw-grid] External editor mount error for column '${i.field}':`,E)}else this.grid.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:C,spec:y,context:v}}))}}#S(e,t,i,n,o,s,l,a){const c=t.__editorTemplate;if(!c)return;const d=c.cloneNode(!0),u=t.__compiledEditor;u?d.innerHTML=u({row:i,value:n,field:t.field,column:t,commit:o,cancel:s}):d.querySelectorAll("*").forEach(p=>{p.childNodes.length===1&&p.firstChild?.nodeType===Node.TEXT_NODE&&(p.textContent=p.textContent?.replace(/{{\s*value\s*}}/g,n==null?"":String(n)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(g,f)=>{if(!ye(f))return"";const w=i[f];return w==null?"":String(w)})||"")});const h=d.querySelector("input,textarea,select");if(h){h instanceof HTMLInputElement&&h.type==="checkbox"?h.checked=!!n:h.value=String(n??"");let p=!1;h.addEventListener("blur",()=>{p||o(le(h,t,n))}),h.addEventListener("keydown",g=>{const f=g;if(f.key==="Enter"){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(f)===!1)return;f.stopPropagation(),f.preventDefault(),p=!0,o(le(h,t,n)),this.#m(a,!1)}if(f.key==="Escape"){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(f)===!1)return;f.stopPropagation(),f.preventDefault(),s(),this.#m(a,!0)}}),h instanceof HTMLInputElement&&h.type==="checkbox"&&h.addEventListener("change",()=>o(h.checked)),l||setTimeout(()=>h.focus({preventScroll:!0}),0)}e.appendChild(d)}#I(e,t){if(!e)return!1;const i=e,n=t,o=new Set([...Object.keys(i),...Object.keys(n)]);for(const s of o)if(i[s]!==n[s])return!0;return!1}#k(e){queueMicrotask(()=>{try{const t=e._focusRow,i=e._focusCol,n=e.findRenderedRowElement?.(t);if(n){Array.from(e._bodyEl.querySelectorAll(".cell-focus")).forEach(s=>s.classList.remove("cell-focus"));const o=n.querySelector(`.cell[data-row="${t}"][data-col="${i}"]`);o&&(o.classList.add("cell-focus"),o.setAttribute("aria-selected","true"),o.hasAttribute("tabindex")||o.setAttribute("tabindex","-1"),o.focus({preventScroll:!0}))}}catch{}})}}function mi(r,e=!0){if(r==null)return"";if(r instanceof Date)return r.toISOString();if(typeof r=="object")return JSON.stringify(r);const t=String(r);return e&&(t.includes(",")||t.includes('"')||t.includes(`
96
- `)||t.includes("\r"))?`"${t.replace(/"/g,'""')}"`:t}function go(r,e,t,i={}){const n=i.delimiter??",",o=i.newline??`
97
- `,s=[],l=i.bom?"\uFEFF":"";if(t.includeHeaders!==!1){const a=e.map(c=>{const d=c.header||c.field,u=t.processHeader?t.processHeader(d,c.field):d;return mi(u)});s.push(a.join(n))}for(const a of r){const c=e.map(d=>{let u=a[d.field];return t.processCell&&(u=t.processCell(u,d.field,a)),mi(u)});s.push(c.join(n))}return l+s.join(o)}function dt(r,e){const t=URL.createObjectURL(r),i=document.createElement("a");i.href=t,i.download=e,i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(t)}function po(r,e){const t=new Blob([r],{type:"text/csv;charset=utf-8;"});dt(t,e)}function bi(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function wo(r,e,t){let i=`<?xml version="1.0" encoding="UTF-8"?>
98
- <?mso-application progid="Excel.Sheet"?>
99
- <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
100
- xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
101
- <Worksheet ss:Name="Sheet1">
102
- <Table>`;if(t.includeHeaders!==!1){i+=`
103
- <Row>`;for(const n of e){const o=n.header||n.field,s=t.processHeader?t.processHeader(o,n.field):o;i+=`<Cell><Data ss:Type="String">${bi(s)}</Data></Cell>`}i+="</Row>"}for(const n of r){i+=`
104
- <Row>`;for(const o of e){let s=n[o.field];t.processCell&&(s=t.processCell(s,o.field,n));let l="String",a="";s==null?a="":typeof s=="number"&&!isNaN(s)?(l="Number",a=String(s)):s instanceof Date?(l="DateTime",a=s.toISOString()):a=bi(String(s)),i+=`<Cell><Data ss:Type="${l}">${a}</Data></Cell>`}i+="</Row>"}return i+=`
105
- </Table>
106
- </Worksheet>
107
- </Workbook>`,i}function mo(r,e){const t=e.endsWith(".xls")?e:`${e}.xls`,i=new Blob([r],{type:"application/vnd.ms-excel;charset=utf-8;"});dt(i,t)}class bo extends M{name="export";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;performExport(e,t){const i=this.config,n={format:e,fileName:t?.fileName??i.fileName??"export",includeHeaders:t?.includeHeaders??i.includeHeaders,processCell:t?.processCell,processHeader:t?.processHeader,columns:t?.columns,rowIndices:t?.rowIndices},o=De(this.columns,t?.columns,i.onlyVisible);let s;if(t?.rowIndices)s=it(this.rows,t.rowIndices);else if(i.onlySelected){const a=this.getSelectionState();a?.selected?.size?s=it(this.rows,[...a.selected]):s=[...this.rows]}else s=[...this.rows];this.isExportingFlag=!0;let l=n.fileName;try{switch(e){case"csv":{const a=go(s,o,n,{bom:!0});l=l.endsWith(".csv")?l:`${l}.csv`,po(a,l);break}case"excel":{const a=wo(s,o,n);l=l.endsWith(".xls")?l:`${l}.xls`,mo(a,l);break}case"json":{const a=s.map(u=>{const h={};for(const p of o){let g=u[p.field];n.processCell&&(g=n.processCell(g,p.field,u)),h[p.field]=g}return h}),c=JSON.stringify(a,null,2);l=l.endsWith(".json")?l:`${l}.json`;const d=new Blob([c],{type:"application/json"});dt(d,l);break}}this.lastExportInfo={format:e,timestamp:new Date},this.emit("export-complete",{format:e,fileName:l,rowCount:s.length,columnCount:o.length})}finally{this.isExportingFlag=!1}}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}exportCsv(e){this.performExport("csv",e)}exportExcel(e){this.performExport("excel",e)}exportJson(e){this.performExport("json",e)}isExporting(){return this.isExportingFlag}getLastExport(){return this.lastExportInfo}}const Ce="(Blank)";function W(r){if(r instanceof Date)return r.getTime();const e=Number(r);return isNaN(e)?new Date(r).getTime():e}function vo(r,e,t=!1,i){const n=r[e.field];if(e.operator==="blank")return n==null||n==="";if(e.operator==="notBlank")return n!=null&&n!=="";if(i&&(e.operator==="notIn"||e.operator==="in")){const a=i(n,r),c=Array.isArray(a)?a:a!=null?[a]:[];if(e.operator==="notIn"){const d=e.value;return Array.isArray(d)?c.length===0?!d.includes(Ce):!c.some(u=>d.includes(u)):!0}if(e.operator==="in"){const d=e.value;return Array.isArray(d)?c.length===0?d.includes(Ce):c.some(u=>d.includes(u)):!1}}if(e.operator==="notIn")return n==null?!0:Array.isArray(e.value)&&!e.value.includes(n);if(e.operator==="in")return Array.isArray(e.value)&&e.value.includes(n);if(n==null)return!1;const o=String(n),s=t?o:o.toLowerCase(),l=t?String(e.value):String(e.value).toLowerCase();switch(e.operator){case"contains":return s.includes(l);case"notContains":return!s.includes(l);case"equals":return s===l;case"notEquals":return s!==l;case"startsWith":return s.startsWith(l);case"endsWith":return s.endsWith(l);case"lessThan":return W(n)<W(e.value);case"lessThanOrEqual":return W(n)<=W(e.value);case"greaterThan":return W(n)>W(e.value);case"greaterThanOrEqual":return W(n)>=W(e.value);case"between":return W(n)>=W(e.value)&&W(n)<=W(e.valueTo);default:return!0}}function yo(r,e,t=!1,i){return e.length?r.filter(n=>e.every(o=>vo(n,o,t,i?.get(o.field)))):r}function Co(r){return JSON.stringify(r.map(e=>({field:e.field,operator:e.operator,value:e.value,valueTo:e.valueTo})))}function vi(r,e,t){const i=new Set;let n=!1;for(const o of r){const s=o[e];if(t){const l=t(s,o);if(Array.isArray(l)){l.length===0&&(n=!0);for(const a of l)a!=null&&i.add(a)}else l!=null?i.add(l):n=!0}else s!=null&&i.add(s)}return t&&n&&i.add(Ce),[...i].sort((o,s)=>typeof o=="number"&&typeof s=="number"?o-s:String(o).localeCompare(String(s)))}function yi(r,e){const t=new Map;for(const{field:n,filterValue:o}of e)t.set(n,{values:new Set,hasBlank:!1,hasExtractor:!!o});for(const n of r)for(const{field:o,filterValue:s}of e){const l=t.get(o),a=n[o];if(s){const c=s(a,n);if(Array.isArray(c)){c.length===0&&(l.hasBlank=!0);for(const d of c)d!=null&&l.values.add(d)}else c!=null?l.values.add(c):l.hasBlank=!0}else a!=null&&l.values.add(a)}const i=new Map;for(const[n,{values:o,hasBlank:s,hasExtractor:l}]of t)l&&s&&o.add(Ce),i.set(n,[...o].sort((a,c)=>typeof a=="number"&&typeof c=="number"?a-c:String(a).localeCompare(String(c))));return i}const Ci="__tbw_expander",xo=32;function Me(r){return r.field===Ci}function ae(r){return r.meta?.utility===!0}function Eo(r){return r.find(Me)}function Ro(r){return{field:Ci,header:"",width:xo,resizable:!1,sortable:!1,filterable:!1,meta:{lockPosition:!0,suppressMovable:!0,expanderColumn:!0,expanderPlugin:r,utility:!0}}}const So='@layer tbw-plugins{tbw-grid .tbw-quick-filter-input{flex:1;max-width:300px;height:var(--tbw-input-height, 1.75rem);padding:var(--tbw-input-padding, 0 .5rem);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);background:var(--tbw-color-bg);color:var(--tbw-color-fg);font-size:var(--tbw-font-size-sm, .8125rem)}tbw-grid .tbw-quick-filter-input:focus{outline:none;border-color:var(--tbw-color-accent)}tbw-grid .header-cell.filtered:before{content:"";position:absolute;top:var(--tbw-spacing-xs, .25rem);right:var(--tbw-spacing-xs, .25rem);width:var(--tbw-indicator-size, .375rem);height:var(--tbw-indicator-size, .375rem);background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border-radius:50%}tbw-grid .tbw-filter-btn{display:var(--tbw-filter-btn-display, inline-flex);visibility:var(--tbw-filter-btn-visibility, visible);align-items:center;justify-content:center;background:transparent;border:none;cursor:pointer;padding:2px;margin-left:var(--tbw-spacing-xs, .25rem);opacity:.4;transition:opacity .15s,visibility 0s,display 0s allow-discrete;color:inherit;vertical-align:middle;transition-behavior:allow-discrete}tbw-grid .tbw-filter-btn:hover,tbw-grid .tbw-filter-btn.active{opacity:1;visibility:visible;display:inline-flex}tbw-grid .tbw-filter-btn.active{color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6))}tbw-grid .header-row .cell:hover .tbw-filter-btn,tbw-grid .header-row .cell.filtered .tbw-filter-btn{display:inline-flex;visibility:visible}}',_o="@layer tbw-plugins{.tbw-filter-panel{position:fixed;background:var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));color:var(--tbw-filter-panel-fg, var(--tbw-color-fg, light-dark(#222222, #eeeeee)));border:1px solid var(--tbw-filter-panel-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-panel-radius, var(--tbw-border-radius, .25rem));box-shadow:0 4px 16px var(--tbw-filter-panel-shadow, var(--tbw-color-shadow, light-dark(rgba(0, 0, 0, .1), rgba(0, 0, 0, .3))));padding:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));z-index:10000;min-width:200px;max-width:280px;max-height:350px;display:flex;flex-direction:column;font-family:var(--tbw-font-family, system-ui, sans-serif);font-size:var(--tbw-font-size, .8125rem);transform-origin:top center}.tbw-filter-panel.tbw-filter-panel-above{transform-origin:bottom center}.tbw-filter-panel.tbw-filter-panel-animated{animation:tbw-filter-panel-enter var(--tbw-animation-duration, .15s) var(--tbw-animation-easing, ease-out)}.tbw-filter-panel.tbw-filter-panel-above.tbw-filter-panel-animated{animation:tbw-filter-panel-enter-above var(--tbw-animation-duration, .15s) var(--tbw-animation-easing, ease-out)}@keyframes tbw-filter-panel-enter{0%{opacity:0;transform:scaleY(.3) translateY(-10px)}to{opacity:1;transform:scaleY(1) translateY(0)}}@keyframes tbw-filter-panel-enter-above{0%{opacity:0;transform:scaleY(.3) translateY(10px)}to{opacity:1;transform:scaleY(1) translateY(0)}}@supports (anchor-name: --test){.tbw-filter-panel{position-anchor:--tbw-filter-anchor;top:anchor(bottom);left:anchor(left);margin-top:4px;position-try-fallbacks:flip-inline,flip-block,flip-block flip-inline}}.tbw-filter-search{margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));min-height:var(--tbw-filter-item-height, 28px)}.tbw-filter-search-input{height:var(--tbw-filter-item-height, 28px);width:100%;padding:var(--tbw-filter-search-padding, var(--tbw-spacing-sm, .375rem) var(--tbw-spacing-md, .5rem));background:var(--tbw-filter-input-bg, var(--tbw-color-bg, transparent));color:inherit;border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-input-radius, var(--tbw-border-radius, .25rem));font-size:inherit;box-sizing:border-box}.tbw-filter-search-input:focus{outline:none;border-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));box-shadow:0 0 0 2px rgba(from var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6)) r g b / 15%)}.tbw-filter-actions{display:flex;padding:var(--tbw-button-padding-sm, .25rem .125rem);margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border-bottom:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));min-height:var(--tbw-filter-item-height, 28px)}.tbw-filter-actions .tbw-filter-value-item{flex:1}.tbw-filter-values{flex:1;overflow-y:auto;margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));max-height:180px;position:relative}.tbw-filter-values-spacer{width:1px}.tbw-filter-values-content{position:absolute;top:0;left:0;right:0}.tbw-filter-value-item{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding-sm, .25rem .125rem);cursor:pointer;border-radius:3px;height:var(--tbw-filter-item-height, 28px)}.tbw-filter-value-item:hover{background:var(--tbw-filter-hover, var(--tbw-color-row-hover, light-dark(#f0f6ff, #1c1c1c)))}.tbw-filter-checkbox{margin:0;cursor:pointer;accent-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6))}.tbw-filter-no-match{color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem)) 0;text-align:center;font-style:italic}.tbw-filter-buttons{display:flex;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding-top:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border-top:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)))}.tbw-filter-apply-btn{flex:1;padding:var(--tbw-filter-btn-padding, var(--tbw-button-padding, .375rem .75rem));background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));color:var(--tbw-filter-accent-fg, var(--tbw-color-accent-fg, light-dark(#ffffff, #000000)));border:none;border-radius:var(--tbw-border-radius, .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);font-weight:var(--tbw-filter-btn-font-weight, 500);min-height:var(--tbw-filter-btn-min-height, auto)}.tbw-filter-apply-btn:hover{filter:brightness(.9)}.tbw-filter-clear-btn{flex:1;padding:var(--tbw-filter-btn-padding, var(--tbw-button-padding, .375rem .75rem));background:transparent;color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-border-radius, .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);font-weight:var(--tbw-filter-btn-font-weight, 500);min-height:var(--tbw-filter-btn-min-height, auto)}.tbw-filter-clear-btn:hover{background:var(--tbw-filter-hover, var(--tbw-color-row-hover, light-dark(#f0f6ff, #1c1c1c)))}.tbw-filter-range-inputs,.tbw-filter-date-range{display:flex;align-items:flex-end;gap:var(--tbw-spacing-sm, .375rem);margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-filter-range-group,.tbw-filter-date-group{display:flex;flex-direction:column;gap:var(--tbw-spacing-xs, .25rem);flex:1}.tbw-filter-range-label{font-size:var(--tbw-font-size-xs, .75rem);color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)))}.tbw-filter-range-input,.tbw-filter-date-input{width:100%;height:var(--tbw-filter-item-height, 28px);padding:var(--tbw-spacing-xs, .25rem) var(--tbw-spacing-sm, .375rem);background:var(--tbw-filter-input-bg, var(--tbw-color-bg, transparent));color:inherit;border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-input-radius, var(--tbw-border-radius, .25rem));font-size:inherit;box-sizing:border-box}.tbw-filter-range-input:focus,.tbw-filter-date-input:focus{outline:none;border-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));box-shadow:0 0 0 2px rgba(from var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6)) r g b / 15%)}.tbw-filter-range-separator{color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));padding-bottom:var(--tbw-spacing-xs, .25rem)}.tbw-filter-blank-option{display:flex;align-items:center;gap:var(--tbw-spacing-sm, .375rem);padding:var(--tbw-spacing-xs, .25rem) 0;margin-bottom:var(--tbw-spacing-xs, .25rem);font-size:var(--tbw-font-size-sm, .8125rem);cursor:pointer;-webkit-user-select:none;user-select:none}.tbw-filter-blank-checkbox{accent-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));margin:0;cursor:pointer}.tbw-filter-date-range.tbw-filter-disabled{opacity:.4;pointer-events:none}.tbw-filter-range-slider{position:relative;height:24px;margin:var(--tbw-spacing-md, .5rem) 0 var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-filter-range-track{position:absolute;top:50%;left:0;right:0;height:4px;background:var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:2px;transform:translateY(-50%)}.tbw-filter-range-fill{position:absolute;top:50%;height:4px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border-radius:2px;transform:translateY(-50%)}.tbw-filter-range-thumb{position:absolute;top:0;width:100%;height:100%;background:none;pointer-events:none;-webkit-appearance:none;appearance:none}.tbw-filter-range-thumb::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:16px;height:16px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border:2px solid var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));border-radius:50%;cursor:pointer;pointer-events:all;box-shadow:0 1px 3px #0003}.tbw-filter-range-thumb::-moz-range-thumb{width:16px;height:16px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border:2px solid var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));border-radius:50%;cursor:pointer;pointer-events:all;box-shadow:0 1px 3px #0003}.tbw-filter-range-thumb::-webkit-slider-thumb:hover{transform:scale(1.1)}.tbw-filter-range-thumb::-moz-range-thumb:hover{transform:scale(1.1)}}";class X extends M{static manifest={events:[{type:"filter-applied",description:"Emitted when filter criteria change. Subscribers can react to row visibility changes."}],queries:[{type:"getContextMenuItems",description:"Contributes filter-related items to the header context menu"}]};name="filtering";styles=So;get defaultConfig(){return{debounceMs:300,caseSensitive:!1,trimInput:!0,useWorker:!0}}isFilteringEnabled(){return this.grid.effectiveConfig?.filterable!==!1}isColumnFilterable(e){return this.isFilteringEnabled()?e.filterable!==!1:!1}getFilterValues(){const e=this.grid.effectiveConfig?.columns;if(!e)return;let t;for(const i of e)i.field&&i.filterValue&&(t||(t=new Map),t.set(i.field,i.filterValue));return t}filters=new Map;cachedResult=null;cacheKey=null;cachedInputSpot=null;openPanelField=null;panelElement=null;panelAnchorElement=null;searchText=new Map;excludedValues=new Map;panelAbortController=null;globalStylesInjected=!1;static DEFAULT_LIST_ITEM_HEIGHT=28;static LIST_OVERSCAN=3;static LIST_BYPASS_THRESHOLD=50;getListItemHeight(){if(this.panelElement){const e=getComputedStyle(this.panelElement).getPropertyValue("--tbw-filter-item-height");if(e&&e.trim()){const t=parseFloat(e);if(!isNaN(t)&&t>0)return t}}return X.DEFAULT_LIST_ITEM_HEIGHT}computeSelected(){const e=[];for(const[n,o]of this.filters){if(o.type!=="set"||o.operator!=="notIn")continue;const s=this.grid.effectiveConfig?.columns?.find(l=>l.field===n);e.push({field:n,filterValue:s?.filterValue})}if(e.length===0)return{};const t=yi(this.sourceRows,e),i={};for(const{field:n}of e){const o=this.excludedValues.get(n),s=t.get(n)??[];i[n]=o?s.filter(l=>!o.has(l)):s}return i}syncExcludedValues(e,t){t?t.type==="set"&&t.operator==="notIn"&&Array.isArray(t.value)?this.excludedValues.set(e,new Set(t.value)):t.type==="set"&&this.excludedValues.delete(e):this.excludedValues.delete(e)}attach(e){super.attach(e),this.injectGlobalStyles()}detach(){this.filters.clear(),this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,this.openPanelField=null,this.panelElement&&(this.panelElement.remove(),this.panelElement=null),this.searchText.clear(),this.excludedValues.clear(),this.panelAbortController?.abort(),this.panelAbortController=null}handleQuery(e){if(e.type==="getContextMenuItems"){const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field||!this.isFilteringEnabled()||!this.isColumnFilterable(i))return;const n=[],o=this.isFieldFiltered(i.field),s=this.filters.size>0;return o&&n.push({id:"filtering/clear-column-filter",label:"Clear Filter",icon:"✕",order:20,action:()=>this.clearFieldFilter(i.field)}),s&&n.push({id:"filtering/clear-all-filters",label:"Clear All Filters",icon:"✕",order:21,disabled:!s,action:()=>this.clearAllFilters()}),n.length>0?n:void 0}}processRows(e){const t=[...this.filters.values()];if(!t.length)return[...e];if(this.config.filterHandler)return this.cachedResult?this.cachedResult:[...e];const i=Co(t),n={len:e.length,first:e[0],mid:e[Math.floor(e.length/2)],last:e[e.length-1]},o=this.cachedInputSpot!=null&&n.len===this.cachedInputSpot.len&&n.first===this.cachedInputSpot.first&&n.mid===this.cachedInputSpot.mid&&n.last===this.cachedInputSpot.last;if(this.cacheKey===i&&this.cachedResult&&o)return this.cachedResult;const s=yo([...e],t,this.config.caseSensitive,this.getFilterValues());return this.cachedResult=s,this.cacheKey=i,this.cachedInputSpot=n,s}afterRender(){const e=this.gridElement;if(!e)return;e.querySelectorAll('[part~="header-cell"]').forEach(i=>{const n=i.getAttribute("data-col");if(n===null)return;const o=this.visibleColumns[parseInt(n,10)];if(!o||!this.isColumnFilterable(o)||ae(o))return;const s=o.field;if(!s)return;const l=this.filters.has(s);let a=i.querySelector(".tbw-filter-btn");if(a){const u=a.classList.contains("active");if(a.classList.toggle("active",l),i.classList.toggle("filtered",l),u!==l){const h=l?"filterActive":"filter";this.setIcon(a,this.resolveIcon(h))}return}a=document.createElement("button"),a.className="tbw-filter-btn",a.setAttribute("aria-label",`Filter ${o.header??s}`);const c=l?"filterActive":"filter";this.setIcon(a,this.resolveIcon(c)),l&&(a.classList.add("active"),i.classList.add("filtered")),a.addEventListener("click",u=>{u.stopPropagation(),this.toggleFilterPanel(s,o,a)});const d=i.querySelector(".resize-handle");d?i.insertBefore(a,d):i.appendChild(a)})}setFilter(e,t){if(t===null)this.filters.delete(e),this.syncExcludedValues(e,null);else{const i={...t,field:e};this.filters.set(e,i),this.syncExcludedValues(e,i)}this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:[...this.filters.values()]}),this.requestRender()}getFilter(e){return this.filters.get(e)}getFilters(){return[...this.filters.values()]}getFilterModel(){return this.getFilters()}setFilterModel(e){this.filters.clear(),this.excludedValues.clear();for(const t of e)this.filters.set(t.field,t),this.syncExcludedValues(t.field,t);this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:[...this.filters.values()]}),this.requestRender()}clearAllFilters(){this.filters.clear(),this.excludedValues.clear(),this.searchText.clear(),this.applyFiltersInternal()}clearFieldFilter(e){this.filters.delete(e),this.excludedValues.delete(e),this.searchText.delete(e),this.applyFiltersInternal()}isFieldFiltered(e){return this.filters.has(e)}getFilteredRowCount(){return this.cachedResult?.length??this.rows.length}getActiveFilters(){return this.getFilters()}getUniqueValues(e){const i=this.grid.effectiveConfig?.columns?.find(n=>n.field===e)?.filterValue;return vi(this.sourceRows,e,i)}copyGridThemeContext(e){const t=this.gridElement;if(!t)return;for(const n of t.classList)n.startsWith("tbw-")||n==="selecting"||e.classList.add(n);const i=t.dataset.theme;i&&(e.dataset.theme=i)}injectGlobalStyles(){if(this.globalStylesInjected)return;if(document.getElementById("tbw-filter-panel-styles")){this.globalStylesInjected=!0;return}const e=document.createElement("style");e.id="tbw-filter-panel-styles",e.textContent=_o,document.head.appendChild(e),this.globalStylesInjected=!0}toggleFilterPanel(e,t,i){if(this.openPanelField===e){this.closeFilterPanel();return}this.closeFilterPanel();const n=document.createElement("div");if(n.className="tbw-filter-panel",this.copyGridThemeContext(n),this.isAnimationEnabled&&n.classList.add("tbw-filter-panel-animated"),this.panelElement=n,this.openPanelField=e,this.config.valuesHandler){n.innerHTML='<div class="tbw-filter-loading">Loading...</div>',document.body.appendChild(n),this.positionPanel(n,i),this.setupPanelCloseHandler(n,i),this.config.valuesHandler(e,t).then(s=>{this.openPanelField!==e||!this.panelElement||(n.innerHTML="",this.renderPanelContent(e,t,n,s))});return}const o=vi(this.sourceRows,e,t.filterValue);document.body.appendChild(n),this.positionPanel(n,i),this.renderPanelContent(e,t,n,o),this.setupPanelCloseHandler(n,i)}renderPanelContent(e,t,i,n){let o=this.excludedValues.get(e);o||(o=new Set,this.excludedValues.set(e,o));const s=this.searchText.get(e)??"",l={field:e,column:t,uniqueValues:n,excludedValues:o,searchText:s,applySetFilter:c=>{this.applySetFilter(e,c),this.closeFilterPanel()},applyTextFilter:(c,d,u)=>{this.applyTextFilter(e,c,d,u),this.closeFilterPanel()},clearFilter:()=>{this.clearFieldFilter(e),this.closeFilterPanel()},closePanel:()=>this.closeFilterPanel()};let a=!1;if(this.config.filterPanelRenderer&&(this.config.filterPanelRenderer(i,l),a=i.children.length>0),!a&&t.type){const c=this.grid.effectiveConfig.typeDefaults?.[t.type];c?.filterPanelRenderer&&(c.filterPanelRenderer(i,l),a=i.children.length>0)}if(!a){const c=t.type;c==="number"?this.renderNumberFilterPanel(i,l,n):c==="date"?this.renderDateFilterPanel(i,l,n):this.renderDefaultFilterPanel(i,l,n,o)}}setupPanelCloseHandler(e,t){this.panelAbortController=new AbortController,setTimeout(()=>{document.addEventListener("click",i=>{!e.contains(i.target)&&i.target!==t&&this.closeFilterPanel()},{signal:this.panelAbortController?.signal})},0)}closeFilterPanel(){const e=this.panelElement;e&&(e.remove(),this.panelElement=null),this.panelAnchorElement&&(this.panelAnchorElement.style.anchorName="",this.panelAnchorElement=null),this.openPanelField=null,this.panelAbortController?.abort(),this.panelAbortController=null}static supportsAnchorPositioning=null;static checkAnchorPositioningSupport(){return X.supportsAnchorPositioning===null&&(X.supportsAnchorPositioning=CSS.supports("anchor-name","--test")),X.supportsAnchorPositioning}positionPanel(e,t){const n=t.closest(".cell")??t;if(n.style.anchorName="--tbw-filter-anchor",this.panelAnchorElement=n,X.checkAnchorPositioningSupport()){requestAnimationFrame(()=>{const s=e.getBoundingClientRect(),l=n.getBoundingClientRect();s.top<l.top&&e.classList.add("tbw-filter-panel-above")});return}const o=n.getBoundingClientRect();e.style.position="fixed",e.style.top=`${o.bottom+4}px`,e.style.left=`${o.left}px`,requestAnimationFrame(()=>{const s=e.getBoundingClientRect();s.right>window.innerWidth-8&&(e.style.left=`${o.right-s.width}px`),s.bottom>window.innerHeight-8&&(e.style.top=`${o.top-s.height-4}px`,e.classList.add("tbw-filter-panel-above"))})}renderDefaultFilterPanel(e,t,i,n){const{field:o,column:s}=t,l=this.getListItemHeight(),a=x=>{if(x==null)return"(Blank)";if(s.format&&!s.filterValue){const R=s.format(x,void 0);if(R)return R}return String(x)};i=i.slice().sort((x,R)=>a(x).localeCompare(a(R)));const c=document.createElement("div");c.className="tbw-filter-search";const d=document.createElement("input");d.type="text",d.placeholder="Search...",d.className="tbw-filter-search-input",d.value=this.searchText.get(o)??"",c.appendChild(d),e.appendChild(c);const u=document.createElement("div");u.className="tbw-filter-actions";const h=document.createElement("label");h.className="tbw-filter-value-item",h.style.padding="0",h.style.margin="0";const p=document.createElement("input");p.type="checkbox",p.className="tbw-filter-checkbox";const g=document.createElement("span");g.textContent="Select All",h.appendChild(p),h.appendChild(g),u.appendChild(h);const f=()=>{const x=[..._.values()],R=x.every(P=>P),I=x.every(P=>!P);p.checked=R,p.indeterminate=!R&&!I};p.addEventListener("change",()=>{const x=p.checked;for(const R of _.keys())_.set(R,x);f(),C()}),e.appendChild(u);const w=document.createElement("div");w.className="tbw-filter-values";const y=document.createElement("div");y.className="tbw-filter-values-spacer",w.appendChild(y);const b=document.createElement("div");b.className="tbw-filter-values-content",w.appendChild(b);const _=new Map;i.forEach(x=>{const R=x==null?"__null__":String(x);_.set(R,!n.has(x))}),f();let T=[];const A=(x,R)=>{const I=a(x),P=x==null?"__null__":String(x),H=document.createElement("label");H.className="tbw-filter-value-item",H.style.position="absolute",H.style.top=`calc(var(--tbw-filter-item-height, 28px) * ${R})`,H.style.left="0",H.style.right="0",H.style.boxSizing="border-box";const z=document.createElement("input");z.type="checkbox",z.className="tbw-filter-checkbox",z.checked=_.get(P)??!0,z.dataset.value=P,z.addEventListener("change",()=>{_.set(P,z.checked),f()});const L=document.createElement("span");return L.textContent=I,H.appendChild(z),H.appendChild(L),H},C=()=>{const x=T.length,R=w.clientHeight,I=w.scrollTop;if(y.style.height=`${x*l}px`,Or(x,X.LIST_BYPASS_THRESHOLD/3)){b.innerHTML="",b.style.transform="translateY(0px)",T.forEach((H,z)=>{b.appendChild(A(H,z))});return}const P=zr({totalRows:x,viewportHeight:R,scrollTop:I,rowHeight:l,overscan:X.LIST_OVERSCAN});b.style.transform=`translateY(${P.offsetY}px)`,b.innerHTML="";for(let H=P.start;H<P.end;H++)b.appendChild(A(T[H],H-P.start))},v=x=>{const R=this.config.caseSensitive??!1,I=R?x:x.toLowerCase();if(T=i.filter(P=>{const H=a(P),z=R?H:H.toLowerCase();return!x||z.includes(I)}),T.length===0){y.style.height="0px",b.innerHTML="";const P=document.createElement("div");P.className="tbw-filter-no-match",P.textContent="No matching values",b.appendChild(P);return}C()};w.addEventListener("scroll",()=>{T.length>0&&C()},{passive:!0}),v(d.value),e.appendChild(w);let E;d.addEventListener("input",()=>{clearTimeout(E),E=setTimeout(()=>{this.searchText.set(o,d.value),v(d.value)},this.config.debounceMs??150)});const m=document.createElement("div");m.className="tbw-filter-buttons";const k=document.createElement("button");k.className="tbw-filter-apply-btn",k.textContent="Apply",k.addEventListener("click",()=>{const x=[];for(const[R,I]of _)if(!I)if(R==="__null__")x.push(null);else{const P=i.find(H=>String(H)===R);x.push(P!==void 0?P:R)}t.applySetFilter(x)}),m.appendChild(k);const F=document.createElement("button");F.className="tbw-filter-clear-btn",F.textContent="Clear Filter",F.addEventListener("click",()=>{t.clearFilter()}),m.appendChild(F),e.appendChild(m)}renderNumberFilterPanel(e,t,i){const{field:n,column:o}=t,s=o.filterParams,l=o.editorParams,a=(D,de)=>{if(typeof D=="number")return D;if(typeof D=="string"){const Re=parseFloat(D);return isNaN(Re)?de:Re}return de},c=i.filter(D=>typeof D=="number"&&!isNaN(D)),d=c.length>0?Math.min(...c):0,u=c.length>0?Math.max(...c):100,h=a(s?.min??l?.min,d),p=a(s?.max??l?.max,u),g=s?.step??l?.step??1,f=this.filters.get(n);let w=h,y=p;f?.operator==="between"?(w=a(f.value,h),y=a(f.valueTo,p)):f?.operator==="greaterThanOrEqual"?w=a(f.value,h):f?.operator==="lessThanOrEqual"&&(y=a(f.value,p));const b=document.createElement("div");b.className="tbw-filter-range-inputs";const _=document.createElement("div");_.className="tbw-filter-range-group";const T=document.createElement("label");T.textContent="Min",T.className="tbw-filter-range-label";const A=document.createElement("input");A.type="number",A.className="tbw-filter-range-input",A.min=String(h),A.max=String(p),A.step=String(g),A.value=String(w),_.appendChild(T),_.appendChild(A),b.appendChild(_);const C=document.createElement("span");C.className="tbw-filter-range-separator",C.textContent="–",b.appendChild(C);const v=document.createElement("div");v.className="tbw-filter-range-group";const E=document.createElement("label");E.textContent="Max",E.className="tbw-filter-range-label";const m=document.createElement("input");m.type="number",m.className="tbw-filter-range-input",m.min=String(h),m.max=String(p),m.step=String(g),m.value=String(y),v.appendChild(E),v.appendChild(m),b.appendChild(v),e.appendChild(b);const k=document.createElement("div");k.className="tbw-filter-range-slider";const F=document.createElement("div");F.className="tbw-filter-range-track";const x=document.createElement("div");x.className="tbw-filter-range-fill";const R=document.createElement("input");R.type="range",R.className="tbw-filter-range-thumb tbw-filter-range-thumb-min",R.min=String(h),R.max=String(p),R.step=String(g),R.value=String(w);const I=document.createElement("input");I.type="range",I.className="tbw-filter-range-thumb tbw-filter-range-thumb-max",I.min=String(h),I.max=String(p),I.step=String(g),I.value=String(y),k.appendChild(F),k.appendChild(x),k.appendChild(R),k.appendChild(I),e.appendChild(k);const P=()=>{const D=parseFloat(R.value),de=parseFloat(I.value),Re=p-h,en=(D-h)/Re*100,cl=(de-h)/Re*100;x.style.left=`${en}%`,x.style.width=`${cl-en}%`};R.addEventListener("input",()=>{const D=Math.min(parseFloat(R.value),parseFloat(I.value));R.value=String(D),A.value=String(D),P()}),I.addEventListener("input",()=>{const D=Math.max(parseFloat(I.value),parseFloat(R.value));I.value=String(D),m.value=String(D),P()}),A.addEventListener("input",()=>{let D=parseFloat(A.value)||h;D=Math.max(h,Math.min(D,parseFloat(m.value))),R.value=String(D),P()}),m.addEventListener("input",()=>{let D=parseFloat(m.value)||p;D=Math.min(p,Math.max(D,parseFloat(A.value))),I.value=String(D),P()}),P();const H=document.createElement("div");H.className="tbw-filter-buttons";const z=document.createElement("button");z.className="tbw-filter-apply-btn",z.textContent="Apply",z.addEventListener("click",()=>{const D=parseFloat(A.value),de=parseFloat(m.value);t.applyTextFilter("between",D,de)}),H.appendChild(z);const L=document.createElement("button");L.className="tbw-filter-clear-btn",L.textContent="Clear Filter",L.addEventListener("click",()=>{t.clearFilter()}),H.appendChild(L),e.appendChild(H)}renderDateFilterPanel(e,t,i){const{field:n,column:o}=t,s=o.filterParams,l=o.editorParams,a=i.filter(L=>L instanceof Date||typeof L=="string"&&!isNaN(Date.parse(L))).map(L=>L instanceof Date?L:new Date(L)).filter(L=>!isNaN(L.getTime())),c=a.length>0?new Date(Math.min(...a.map(L=>L.getTime()))):null,d=a.length>0?new Date(Math.max(...a.map(L=>L.getTime()))):null,u=L=>L?L.toISOString().split("T")[0]:"",h=L=>L?typeof L=="string"?L:typeof L=="number"?u(new Date(L)):"":"",p=h(s?.min)||h(l?.min)||u(c),g=h(s?.max)||h(l?.max)||u(d),f=this.filters.get(n);let w="",y="";const b=f?.operator==="blank";f?.operator==="between"?(w=h(f.value)||"",y=h(f.valueTo)||""):f?.operator==="greaterThanOrEqual"?w=h(f.value)||"":f?.operator==="lessThanOrEqual"&&(y=h(f.value)||"");const _=document.createElement("div");_.className="tbw-filter-date-range";const T=document.createElement("div");T.className="tbw-filter-date-group";const A=document.createElement("label");A.textContent="From",A.className="tbw-filter-range-label";const C=document.createElement("input");C.type="date",C.className="tbw-filter-date-input",p&&(C.min=p),g&&(C.max=g),C.value=w,T.appendChild(A),T.appendChild(C),_.appendChild(T);const v=document.createElement("span");v.className="tbw-filter-range-separator",v.textContent="–",_.appendChild(v);const E=document.createElement("div");E.className="tbw-filter-date-group";const m=document.createElement("label");m.textContent="To",m.className="tbw-filter-range-label";const k=document.createElement("input");k.type="date",k.className="tbw-filter-date-input",p&&(k.min=p),g&&(k.max=g),k.value=y,E.appendChild(m),E.appendChild(k),_.appendChild(E),e.appendChild(_);const F=document.createElement("label");F.className="tbw-filter-blank-option";const x=document.createElement("input");x.type="checkbox",x.className="tbw-filter-blank-checkbox",x.checked=b;const R=document.createTextNode("Show only blank");F.appendChild(x),F.appendChild(R);const I=L=>{C.disabled=L,k.disabled=L,_.classList.toggle("tbw-filter-disabled",L)};I(b),x.addEventListener("change",()=>{I(x.checked)}),e.appendChild(F);const P=document.createElement("div");P.className="tbw-filter-buttons";const H=document.createElement("button");H.className="tbw-filter-apply-btn",H.textContent="Apply",H.addEventListener("click",()=>{if(x.checked){t.applyTextFilter("blank","");return}const L=C.value,D=k.value;L&&D?t.applyTextFilter("between",L,D):L?t.applyTextFilter("greaterThanOrEqual",L):D?t.applyTextFilter("lessThanOrEqual",D):t.clearFilter()}),P.appendChild(H);const z=document.createElement("button");z.className="tbw-filter-clear-btn",z.textContent="Clear Filter",z.addEventListener("click",()=>{t.clearFilter()}),P.appendChild(z),e.appendChild(P)}applySetFilter(e,t){this.excludedValues.set(e,new Set(t)),t.length===0?this.filters.delete(e):this.filters.set(e,{field:e,type:"set",operator:"notIn",value:t}),this.applyFiltersInternal()}applyTextFilter(e,t,i,n){this.filters.set(e,{field:e,type:"text",operator:t,value:i,valueTo:n}),this.applyFiltersInternal()}applyFiltersInternal(){this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null;const e=[...this.filters.values()];if(this.config.filterHandler){const t=this.grid;t.setAttribute("aria-busy","true");const i=this.config.filterHandler(e,this.sourceRows),n=o=>{t.removeAttribute("aria-busy"),this.cachedResult=o,this.grid.rows=o,this.emit("filter-change",{filters:e,filteredRowCount:o.length,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:e}),this.requestRender()};i&&typeof i.then=="function"?i.then(n):n(i);return}this.emit("filter-change",{filters:e,filteredRowCount:0,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:e}),this.requestRender()}getColumnState(e){const t=this.filters.get(e);if(t)return{filter:{type:t.type,operator:t.operator,value:t.value,valueTo:t.valueTo}}}applyColumnState(e,t){if(!t.filter){this.filters.delete(e);return}const i={field:e,type:t.filter.type,operator:t.filter.operator,value:t.filter.value,valueTo:t.filter.valueTo};this.filters.set(e,i),this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null}}function xi(r){if(!r.length)return[];const e=new Map,t=[],i=(s,l)=>{if(!l.length)return;const a=t[t.length-1];if(a&&a.implicit&&a.firstIndex+a.columns.length===s){a.columns.push(...l);return}t.push({id:"__implicit__"+s,label:void 0,columns:l,firstIndex:s,implicit:!0})};let n=[],o=0;return r.forEach((s,l)=>{const a=s.group;if(!a){n.length===0&&(o=l),n.push(s);return}n.length&&(i(o,n.slice()),n=[]);const c=typeof a=="string"?a:a.id;let d=e.get(c);d||(d={id:c,label:typeof a=="string"?void 0:a.label,columns:[],firstIndex:l},e.set(c,d),t.push(d)),d.columns.push(s)}),n.length&&i(o,n),t.length===1&&t[0].implicit&&t[0].columns.length===r.length?[]:t}function Ao(r,e,t){if(!e.length||!r)return;const i=new Map;for(const o of e)for(const s of o.columns)s.field&&i.set(s.field,o.id);const n=Array.from(r.querySelectorAll(".cell[data-field]"));n.forEach(o=>{const s=o.getAttribute("data-field")||"",l=i.get(s);l&&(o.classList.add("grouped"),o.getAttribute("data-group")||o.setAttribute("data-group",l))});for(const o of e){const s=o.columns[o.columns.length-1],l=n.find(a=>a.getAttribute("data-field")===s.field);l&&l.classList.add("group-end")}}function ko(r,e){if(r.length===0)return null;const t=document.createElement("div");t.className="header-group-row",t.setAttribute("role","row");for(const i of r){const n=i.columns[0],o=n?e.findIndex(c=>c.field===n.field):-1;if(o===-1)continue;const s=String(i.id).startsWith("__implicit__"),l=s?"":i.label||i.id,a=document.createElement("div");a.className="cell header-group-cell",s&&a.classList.add("implicit-group"),a.setAttribute("data-group",String(i.id)),a.style.gridColumn=`${o+1} / span ${i.columns.length}`,a.textContent=l,t.appendChild(a)}return t}function To(r){return r.some(e=>e.group!=null)}const Lo="@layer tbw-plugins{.header-group-row{display:grid;grid-auto-flow:column;background:var(--tbw-grouping-columns-header-bg, var(--tbw-color-header-bg));border-bottom:1px solid var(--tbw-grouping-columns-border, var(--tbw-color-border))}.header-group-cell{display:flex;align-items:center;justify-content:center;padding:var(--tbw-button-padding-sm, .25rem .5rem);font-weight:600;font-size:var(--tbw-font-size-sm, .9em);text-transform:uppercase;letter-spacing:.5px;border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.header-group-cell:last-child{border-right:none}.header-row .cell.grouped{border-top:none}.header-row .cell.group-end{border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.header-row .cell.group-end:last-child{border-right:none}.rows .cell.group-end{border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.rows .cell.group-end:last-child{border-right:none}.header-group-row.no-borders{border-bottom:none}.header-group-row.no-borders .header-group-cell{border-right:none}.header-row.no-group-borders .cell.group-end{border-right:1px solid var(--tbw-color-border)}}";class Po extends M{static manifest={ownedProperties:[{property:"group",level:"column",description:'the "group" column property'},{property:"columnGroups",level:"config",description:'the "columnGroups" config property',isUsed:e=>Array.isArray(e)&&e.length>0}],queries:[{type:"getColumnGrouping",description:"Returns column group metadata for the visibility panel"}]};name="groupingColumns";styles=Lo;get defaultConfig(){return{showGroupBorders:!0,lockGroupOrder:!1}}groups=[];isActive=!1;#t=new Set;attach(e){super.attach(e),e.addEventListener("column-move",this.#e,{signal:this.disconnectSignal})}detach(){this.groups=[],this.isActive=!1,this.#t.clear()}#e=e=>{if(!this.isActive)return;const t=e,{field:i,columnOrder:n}=t.detail;if(this.config.lockGroupOrder){for(const o of this.groups)if(!o.id.startsWith("__implicit__")&&!this.#r(o,n)){t.preventDefault(),this.#l(i);return}}this.#u(n)};#u(e){this.#t.clear();const t=this.#c(e);for(const i of this.groups){const n=new Set(i.columns.map(o=>o.field));for(let o=e.length-1;o>=0;o--)if(n.has(e[o])){const s=e[o];s!==t&&this.#t.add(s);break}}}#c(e){if(this.groups.length===0)return null;for(let t=e.length-1;t>=0;t--){const i=e[t];for(const n of this.groups)if(n.columns.some(o=>o.field===i)){const o=new Set(n.columns.map(s=>s.field));for(let s=e.length-1;s>=0;s--)if(o.has(e[s]))return e[s]}}return null}#r(e,t){const i=e.columns.map(n=>t.indexOf(n.field)).filter(n=>n!==-1).sort((n,o)=>n-o);return i.length<=1?!0:i.length===i[i.length-1]-i[0]+1}#l(e){const t=this.gridElement?.querySelector(`.header-row [part~="header-cell"][data-field="${e}"]`);t&&(t.style.setProperty("--_flash-color","var(--tbw-color-error)"),t.animate([{backgroundColor:"rgba(from var(--_flash-color) r g b / 30%)"},{backgroundColor:"transparent"}],{duration:400,easing:"ease-out"}))}handleQuery(e){if(e.type==="getColumnGrouping")return this.#i()}#i(){let e;const t=this.grid?.gridConfig?.columnGroups;if(t&&Array.isArray(t)&&t.length>0)e=t.filter(n=>n.children.length>0).map(n=>({id:n.id,label:n.header,fields:[...n.children]}));else if(this.isActive&&this.groups.length>0){e=this.groups.filter(o=>!o.id.startsWith("__implicit__")).map(o=>({id:o.id,label:o.label??o.id,fields:o.columns.map(s=>s.field)}));const n=this.columns;for(const o of n)if(o.hidden&&o.group){const s=typeof o.group=="string"?o.group:o.group.id,l=typeof o.group=="string"?o.group:o.group.label??o.group.id,a=e.find(c=>c.id===s);a?a.fields.includes(o.field)||a.fields.push(o.field):e.push({id:s,label:l,fields:[o.field]})}}else{const n=this.columns,o=new Map;for(const s of n){if(!s.group)continue;const l=typeof s.group=="string"?s.group:s.group.id,a=typeof s.group=="string"?s.group:s.group.label??s.group.id,c=o.get(l);c?c.fields.includes(s.field)||c.fields.push(s.field):o.set(l,{id:l,label:a,fields:[s.field]})}e=Array.from(o.values())}const i=this.grid?.getColumnOrder();if(i&&i.length>0){const n=new Map(i.map((o,s)=>[o,s]));for(const o of e)o.fields.sort((s,l)=>(n.get(s)??1/0)-(n.get(l)??1/0))}return e}static detect(e,t){if(t?.columnGroups&&Array.isArray(t.columnGroups)&&t.columnGroups.length>0)return!0;const i=t?.columns;return Array.isArray(i)?To(i):!1}processColumns(e){const t=this.grid?.gridConfig?.columnGroups;let i;if(t&&Array.isArray(t)&&t.length>0){const o=new Map;for(const s of t)for(const l of s.children)o.set(l,{id:s.id,label:s.header});i=e.map(s=>{const l=o.get(s.field);return l&&!s.group?{...s,group:l}:s})}else i=[...e];const n=xi(i);if(n.length===0)return this.isActive=!1,this.groups=[],i;this.isActive=!0,this.groups=n,this.#t.clear();for(const o of n){const s=o.columns[o.columns.length-1];s?.field&&this.#t.add(s.field)}return i}afterRender(){if(!this.isActive){const a=this.gridElement?.querySelector(".header")?.querySelector(".header-group-row");a&&a.remove();return}const e=this.gridElement?.querySelector(".header");if(!e)return;const t=e.querySelector(".header-group-row");t&&t.remove();const i=this.visibleColumns,n=xi(i);if(n.length===0)return;this.#t.clear();for(let l=0;l<n.length;l++){const a=n[l],c=a.columns[a.columns.length-1];c?.field&&l<n.length-1&&this.#t.add(c.field)}const o=ko(n,i);if(o){o.classList.toggle("no-borders",!this.config.showGroupBorders);const l=e.querySelector(".header-row");l?e.insertBefore(o,l):e.appendChild(o)}const s=e.querySelector(".header-row");s&&(s.classList.toggle("no-group-borders",!this.config.showGroupBorders),Ao(s,n))}afterCellRender(e){!this.isActive||!this.config.showGroupBorders||e.cellElement.classList.toggle("group-end",this.#t.has(e.column.field))}isGroupingActive(){return this.isActive}getGroups(){return this.groups}getGroupColumns(e){const t=this.groups.find(i=>i.id===e);return t?t.columns:[]}refresh(){this.requestRender()}}const ut={sum:(r,e)=>r.reduce((t,i)=>t+(Number(i[e])||0),0),avg:(r,e)=>{const t=r.reduce((i,n)=>i+(Number(n[e])||0),0);return r.length?t/r.length:0},count:r=>r.length,min:(r,e)=>r.length?Math.min(...r.map(t=>Number(t[e])||1/0)):0,max:(r,e)=>r.length?Math.max(...r.map(t=>Number(t[e])||-1/0)):0,first:(r,e)=>r[0]?.[e],last:(r,e)=>r[r.length-1]?.[e]},xe=new Map,Y={register(r,e){xe.set(r,e)},unregister(r){xe.delete(r)},get(r){if(r!==void 0)return typeof r=="function"?r:xe.get(r)??ut[r]},run(r,e,t,i){const n=this.get(r);return n?n(e,t,i):void 0},has(r){return xe.has(r)||r in ut},list(){return[...Object.keys(ut),...xe.keys()]}},Ei={sum:r=>r.reduce((e,t)=>e+t,0),avg:r=>r.length?r.reduce((e,t)=>e+t,0)/r.length:0,count:r=>r.length,min:r=>r.length?Math.min(...r):0,max:r=>r.length?Math.max(...r):0,first:r=>r[0]??0,last:r=>r[r.length-1]??0};function Ho(r){return Ei[r]??Ei.sum}Y.register.bind(Y),Y.unregister.bind(Y);const Ri=Y.get.bind(Y),ht=Y.run.bind(Y);Y.list.bind(Y);function Si({rows:r,config:e,expanded:t,initialExpanded:i}){const n=e.groupOn;if(typeof n!="function")return[];const o={key:"__root__",value:null,depth:-1,rows:[],children:new Map};if(r.forEach(c=>{let d=n(c);d==null||d===!1?d=["__ungrouped__"]:Array.isArray(d)||(d=[d]);let u=o;d.forEach((h,p)=>{const g=h==null?"∅":String(h),f=u.key==="__root__"?g:u.key+"||"+g;let w=u.children.get(g);w||(w={key:f,value:h,depth:p,rows:[],children:new Map,parent:u},u.children.set(g,w)),u=w}),u.rows.push(c)}),o.children.size===1&&o.children.has("__ungrouped__")&&o.children.get("__ungrouped__").rows.length===r.length)return[];const s=new Set([...t,...i??[]]),l=[],a=c=>{if(c===o){c.children.forEach(u=>a(u));return}const d=s.has(c.key);l.push({kind:"group",key:c.key,value:c.value,depth:c.depth,rows:c.rows,expanded:d}),d&&(c.children.size?c.children.forEach(u=>a(u)):c.rows.forEach(u=>l.push({kind:"data",row:u,rowIndex:r.indexOf(u)})))};return a(o),l}function Io(r,e){const t=new Set(r);return t.has(e)?t.delete(e):t.add(e),t}function Do(r){const e=new Set;for(const t of r)t.kind==="group"&&e.add(t.key);return e}function Mo(){return new Set}function zo(r,e){if(r===!0)return new Set(e);if(r===!1||r==null)return new Set;if(typeof r=="number"){const t=e[r];return t?new Set([t]):new Set}return typeof r=="string"?new Set([r]):Array.isArray(r)?new Set(r):new Set}function Oo(r){return r.filter(e=>e.kind==="group").map(e=>e.key)}function Fo(r){return r.kind!=="group"?0:r.rows.length}const No="@layer tbw-plugins{.group-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-grouping-rows-bg, var(--tbw-color-panel-bg));font-weight:500;border-bottom:var(--tbw-row-divider);min-height:var(--tbw-row-height)}.group-row .cell{display:flex;align-items:center;padding:var(--tbw-cell-padding, .125rem .5rem)}.group-row:hover{background:var(--tbw-grouping-rows-bg-hover, var(--tbw-color-row-hover))}.group-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-toggle-size, 1.25rem);height:var(--tbw-toggle-size, 1.25rem);margin-right:.25rem;background:none;border:0;font:inherit}.group-toggle:hover{background:var(--tbw-grouping-rows-toggle-hover, var(--tbw-color-row-hover));border-radius:var(--tbw-border-radius, .125rem)}.group-label{display:inline-flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.group-count{color:var(--tbw-grouping-rows-count-color, var(--tbw-color-fg-muted));font-size:var(--tbw-font-size-xs, .85em);font-weight:400}.group-aggregates{display:inline-flex;align-items:center;gap:var(--tbw-spacing-lg, 1rem);margin-left:var(--tbw-spacing-lg, 1rem);font-weight:400;font-size:var(--tbw-font-size-sm, .875em);color:var(--tbw-grouping-rows-aggregate-color, var(--tbw-color-fg-muted))}.group-aggregate{white-space:nowrap}.group-row{padding-left:calc(var(--tbw-group-depth, 0) * var(--tbw-group-indent-width, 1.25em))}.data-grid-row.tbw-group-slide-in{animation:tbw-group-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.data-grid-row.tbw-group-fade-in{animation:tbw-group-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-fade-in{0%{opacity:0}to{opacity:1}}}";class qo extends M{static manifest={events:[{type:"grouping-state-change",description:"Emitted when groups are expanded/collapsed. Subscribers can react to row visibility changes."}],queries:[{type:"canMoveRow",description:"Returns false for group header rows (cannot be reordered)"}],configRules:[{id:"groupingRows/accordion-defaultExpanded",severity:"warn",message:`"accordion: true" and "defaultExpanded" (non-false) are used together.
108
- → In accordion mode, only one group can be open at a time.
109
- → Using defaultExpanded with multiple groups will collapse to one on first toggle.
110
- → Consider using "defaultExpanded: false" or a single group key/index with accordion mode.`,check:e=>e.accordion===!0&&e.defaultExpanded!==!1&&e.defaultExpanded!==void 0&&typeof e.defaultExpanded!="number"&&typeof e.defaultExpanded!="string"&&(e.defaultExpanded===!0||Array.isArray(e.defaultExpanded)&&e.defaultExpanded.length>1)}]};name="groupingRows";styles=No;get defaultConfig(){return{defaultExpanded:!1,showRowCount:!0,indentWidth:20,aggregators:{},animation:"slide",accordion:!1}}expandedKeys=new Set;flattenedRows=[];isActive=!1;previousVisibleKeys=new Set;keysToAnimate=new Set;hasAppliedDefaultExpanded=!1;get animationStyle(){return this.isAnimationEnabled?this.config.animation??"slide":!1}detach(){this.expandedKeys.clear(),this.flattenedRows=[],this.isActive=!1,this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.hasAppliedDefaultExpanded=!1}getRowHeight(e,t){if(this.config.groupRowHeight!=null&&e.__isGroupRow===!0)return this.config.groupRowHeight}handleQuery(e){if(e.type==="canMoveRow"&&e.context?.__isGroupRow===!0)return!1}static detect(e,t){return typeof t?.groupOn=="function"||typeof t?.enableRowGrouping=="boolean"}processRows(e){const t=this.config;if(typeof t.groupOn!="function")return this.isActive=!1,this.flattenedRows=[],[...e];const i=Si({rows:[...e],config:t,expanded:new Set});if(i.length===0)return this.isActive=!1,this.flattenedRows=[],[...e];let n;if(!this.hasAppliedDefaultExpanded&&this.expandedKeys.size===0&&t.defaultExpanded!==!1){const l=Oo(i);n=zo(t.defaultExpanded??!1,l),n.size>0&&(this.expandedKeys=new Set(n),this.hasAppliedDefaultExpanded=!0)}const o=Si({rows:[...e],config:t,expanded:this.expandedKeys,initialExpanded:n});this.isActive=!0,this.flattenedRows=o,this.keysToAnimate.clear();const s=new Set;return o.forEach((l,a)=>{if(l.kind==="data"){const c=`data-${a}`;s.add(c),this.previousVisibleKeys.has(c)||this.keysToAnimate.add(c)}}),this.previousVisibleKeys=s,o.map(l=>l.kind==="group"?{__isGroupRow:!0,__groupKey:l.key,__groupValue:l.value,__groupDepth:l.depth,__groupRows:l.rows,__groupExpanded:l.expanded,__groupRowCount:Fo(l),__rowCacheKey:`group:${l.key}`}:l.row)}onCellClick(e){const t=e.row;if(t?.__isGroupRow&&e.originalEvent.target?.closest(".group-toggle"))return this.toggle(t.__groupKey),!0}onKeyDown(e){if(e.key!==" ")return;const t=this.grid._focusRow,i=this.rows[t];if(i?.__isGroupRow)return e.preventDefault(),this.toggle(i.__groupKey),this.requestRenderWithFocus(),!0}renderRow(e,t,i){if(!e?.__isGroupRow)return!1;const n=this.config;if(n.groupRowRenderer){const l=()=>{this.toggle(e.__groupKey)},a=n.groupRowRenderer({key:e.__groupKey,value:e.__groupValue,depth:e.__groupDepth,rows:e.__groupRows,expanded:e.__groupExpanded,toggleExpand:l});if(a)return t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),typeof a=="string"?t.innerHTML=a:(t.innerHTML="",t.appendChild(a)),!0}const o=()=>{this.toggle(e.__groupKey)};return t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),t.setAttribute("role","row"),t.setAttribute("aria-expanded",String(e.__groupExpanded)),t.style.setProperty("--tbw-group-depth",String(e.__groupDepth||0)),n.indentWidth!==void 0&&t.style.setProperty("--tbw-group-indent-width",`${n.indentWidth}px`),t.style.height="",t.innerHTML="",n.fullWidth!==!1?this.renderFullWidthGroupRow(e,t,o):this.renderPerColumnGroupRow(e,t,o),!0}afterRender(){const e=this.animationStyle;if(e===!1||this.keysToAnimate.size===0)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const i=e==="fade"?"tbw-group-fade-in":"tbw-group-slide-in";for(const n of t.querySelectorAll(".data-grid-row:not(.group-row)")){const o=n.querySelector(".cell[data-row]"),s=o?parseInt(o.getAttribute("data-row")??"-1",10):-1,a=this.flattenedRows[s]?.kind==="data"?`data-${s}`:void 0;a&&this.keysToAnimate.has(a)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}createToggleButton(e,t){const i=document.createElement("button");return i.type="button",i.className=`group-toggle${e?" expanded":""}`,i.setAttribute("aria-label",e?"Collapse group":"Expand group"),this.setIcon(i,this.resolveIcon(e?"collapse":"expand")),i.addEventListener("click",n=>{n.stopPropagation(),t()}),i}getGroupLabelText(e,t,i){const n=this.config;return n.formatLabel?n.formatLabel(e,t,i):String(e)}renderFullWidthGroupRow(e,t,i){const n=this.config,o=n.aggregators??{},s=e.__groupRows??[],l=document.createElement("div");l.className="cell group-full",l.style.gridColumn="1 / -1",l.setAttribute("role","gridcell"),l.setAttribute("data-col","0"),l.appendChild(this.createToggleButton(e.__groupExpanded,i));const a=document.createElement("span");if(a.className="group-label",a.textContent=this.getGroupLabelText(e.__groupValue,e.__groupDepth||0,e.__groupKey),l.appendChild(a),n.showRowCount!==!1){const d=document.createElement("span");d.className="group-count",d.textContent=`(${e.__groupRowCount??e.__groupRows?.length??0})`,l.appendChild(d)}const c=Object.entries(o);if(c.length>0){const d=document.createElement("span");d.className="group-aggregates";for(const[u,h]of c){const p=this.columns.find(f=>f.field===u),g=ht(h,s,u,p);if(g!=null){const f=document.createElement("span");f.className="group-aggregate",f.setAttribute("data-field",u);const w=p?.header??u;f.textContent=`${w}: ${g}`,d.appendChild(f)}}d.children.length>0&&l.appendChild(d)}t.appendChild(l)}renderPerColumnGroupRow(e,t,i){const n=this.config,o=n.aggregators??{},s=this.columns,l=e.__groupRows??[],c=this.gridElement?.querySelector(".body")?.style.gridTemplateColumns||"";c&&(t.style.display="grid",t.style.gridTemplateColumns=c);let d=!1;s.forEach((u,h)=>{const p=document.createElement("div");if(p.className="cell group-cell",p.setAttribute("data-col",String(h)),p.setAttribute("role","gridcell"),Me(u)){p.setAttribute("data-field",u.field),t.appendChild(p);return}if(d){const g=o[u.field];if(g){const f=ht(g,l,u.field,u);p.textContent=f!=null?String(f):""}else p.textContent=""}else{d=!0,p.appendChild(this.createToggleButton(e.__groupExpanded,i));const g=document.createElement("span"),f=o[u.field];if(f){const w=ht(f,l,u.field,u);g.textContent=w!=null?String(w):String(e.__groupValue)}else g.textContent=this.getGroupLabelText(e.__groupValue,e.__groupDepth||0,e.__groupKey);if(p.appendChild(g),n.showRowCount!==!1){const w=document.createElement("span");w.className="group-count",w.textContent=` (${l.length})`,p.appendChild(w)}}t.appendChild(p)})}expandAll(){this.expandedKeys=Do(this.flattenedRows),this.emitPluginEvent("grouping-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=Mo(),this.emitPluginEvent("grouping-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}toggle(e){const t=!this.expandedKeys.has(e),i=this.config,n=this.flattenedRows.find(o=>o.kind==="group"&&o.key===e);if(i.accordion&&t&&n){const o=new Set;for(const s of this.expandedKeys)if(e.startsWith(s+"||")||s.startsWith(e+"||"))e.startsWith(s+"||")&&o.add(s);else{const l=this.flattenedRows.find(a=>a.kind==="group"&&a.key===s);l&&l.depth!==n.depth&&o.add(s)}o.add(e),this.expandedKeys=o}else this.expandedKeys=Io(this.expandedKeys,e);this.emit("group-toggle",{key:e,expanded:this.expandedKeys.has(e),value:n?.value,depth:n?.depth??0}),this.emitPluginEvent("grouping-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}expand(e){this.expandedKeys.has(e)||(this.expandedKeys=new Set([...this.expandedKeys,e]),this.requestRender())}collapse(e){if(this.expandedKeys.has(e)){const t=new Set(this.expandedKeys);t.delete(e),this.expandedKeys=t,this.requestRender()}}getGroupState(){const e=this.flattenedRows.filter(t=>t.kind==="group");return{isActive:this.isActive,expandedCount:this.expandedKeys.size,totalGroups:e.length,expandedKeys:[...this.expandedKeys]}}getRowCount(){return this.flattenedRows.length}refreshGroups(){this.requestRender()}getExpandedGroups(){return[...this.expandedKeys]}getFlattenedRows(){return this.flattenedRows}isGroupingActive(){return this.isActive}setGroupOn(e){this.config.groupOn=e,this.requestRender()}}function _i(r,e){const t=new Set(r);return t.has(e)?t.delete(e):t.add(e),t}function Go(r,e){const t=new Set(r);return t.add(e),t}function Bo(r,e){const t=new Set(r);return t.delete(e),t}function $o(r,e){return r.has(e)}function Wo(r,e,t,i){const n=document.createElement("div");n.className="master-detail-row",n.setAttribute("data-detail-for",String(e)),n.setAttribute("role","row");const o=document.createElement("div");o.className="master-detail-cell",o.setAttribute("role","cell"),o.style.gridColumn=`1 / ${i+1}`;const s=t(r,e);return typeof s=="string"?o.innerHTML=s:s instanceof HTMLElement&&o.appendChild(s),n.appendChild(o),n}const Ko="@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-right:none!important;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1 / 3}tbw-grid .master-detail-expander{display:flex;align-items:center;justify-content:center;width:100%;height:100%}tbw-grid .master-detail-toggle{cursor:pointer;opacity:.7;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center}tbw-grid .master-detail-toggle:hover{opacity:1}tbw-grid .master-detail-row{grid-column:1 / -1;display:grid;background:var(--tbw-master-detail-bg, var(--tbw-color-row-alt));border-bottom:1px solid var(--tbw-master-detail-border, var(--tbw-color-border));overflow:hidden}tbw-grid .master-detail-cell{padding:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));overflow:auto}tbw-grid .master-detail-row.tbw-expanding{animation:tbw-detail-expand var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .master-detail-row.tbw-collapsing{animation:tbw-detail-collapse var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-detail-expand{0%{opacity:0;max-height:0;padding-top:0;padding-bottom:0}to{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem);padding-top:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));padding-bottom:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem))}}@keyframes tbw-detail-collapse{0%{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem)}to{opacity:0;max-height:0}}}";class ft extends M{name="masterDetail";styles=Ko;get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,animation:"slide"}}attach(e){super.attach(e),this.parseLightDomDetail()}parseLightDomDetail(){const e=this.grid;if(!e||typeof e.querySelector!="function")return;const t=e.querySelector("tbw-grid-detail");if(!t)return;const i=e;if(i.__frameworkAdapter?.parseDetailElement){const u=i.__frameworkAdapter.parseDetailElement(t);if(u){this.config={...this.config,detailRenderer:u};return}}const n=t.getAttribute("animation"),o=t.getAttribute("show-expand-column"),s=t.getAttribute("expand-on-row-click"),l=t.getAttribute("collapse-on-click-outside"),a=t.getAttribute("height"),c={};n!==null&&(c.animation=n==="false"?!1:n),o!==null&&(c.showExpandColumn=o!=="false"),s!==null&&(c.expandOnRowClick=s==="true"),l!==null&&(c.collapseOnClickOutside=l==="true"),a!==null&&(c.detailHeight=a==="auto"?"auto":parseInt(a,10));const d=t.innerHTML.trim();d&&!this.config.detailRenderer&&(c.detailRenderer=(u,h)=>{const p=fe(d,{value:u,row:u});return U(p)}),Object.keys(c).length>0&&(this.config={...this.config,...c})}get animationStyle(){return this.isAnimationEnabled?this.config.animation??"slide":!1}animateExpand(e,t,i){if(!this.isAnimationEnabled||this.animationStyle===!1)return!1;e.classList.add("tbw-expanding");let n=!1;const o=()=>{n||(n=!0,e.classList.remove("tbw-expanding"),t!==void 0&&i!==void 0&&this.#t(e,t,i))};return e.addEventListener("animationend",o,{once:!0}),setTimeout(o,this.animationDuration+50),!0}animateCollapse(e,t){if(!this.isAnimationEnabled||this.animationStyle===!1){t();return}e.classList.add("tbw-collapsing");const i=()=>{e.classList.remove("tbw-collapsing"),t()};e.addEventListener("animationend",i,{once:!0}),setTimeout(i,this.animationDuration+50)}#t(e,t,i){if(!e.isConnected)return;const n=e.offsetHeight;if(n>0){const o=this.measuredDetailHeights.get(t);this.measuredDetailHeights.set(t,n),o!==n&&this.grid.invalidateRowHeight(i)}}expandedRows=new Set;detailElements=new Map;measuredDetailHeights=new Map;rowsToAnimate=new Set;static DEFAULT_DETAIL_HEIGHT=150;getDetailHeight(e){const t=this.detailElements.get(e);if(t&&!(t.classList.contains("tbw-expanding")||t.classList.contains("tbw-collapsing"))){const o=t.offsetHeight;if(o>0)return this.measuredDetailHeights.set(e,o),o}const i=this.measuredDetailHeights.get(e);return i&&i>0?i:typeof this.config?.detailHeight=="number"?this.config.detailHeight:ft.DEFAULT_DETAIL_HEIGHT}toggleAndEmit(e,t){this.expandedRows=_i(this.expandedRows,e);const i=this.expandedRows.has(e);i&&this.rowsToAnimate.add(e),this.emit("detail-expand",{rowIndex:t,row:e,expanded:i}),this.requestRender()}detach(){this.expandedRows.clear(),this.detailElements.clear(),this.measuredDetailHeights.clear(),this.rowsToAnimate.clear()}processColumns(e){if(!(this.config.showExpandColumn===!0||this.config.showExpandColumn!==!1&&!!this.config.detailRenderer))return[...e];const i=[...e];if(Eo(i))return i;const o=Ro(this.name);return o.viewRenderer=s=>{const{row:l}=s,a=this.expandedRows.has(l),c=document.createElement("span");c.className="master-detail-expander expander-cell";const d=document.createElement("span");return d.className=`master-detail-toggle${a?" expanded":""}`,this.setIcon(d,this.resolveIcon(a?"collapse":"expand")),d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-expanded",String(a)),d.setAttribute("aria-label",a?"Collapse details":"Expand details"),c.appendChild(d),c},[o,...i]}onRowClick(e){if(!(!this.config.expandOnRowClick||!this.config.detailRenderer))return this.toggleAndEmit(e.row,e.rowIndex),!1}onCellClick(e){if(e.originalEvent?.target?.classList.contains("master-detail-toggle"))return this.toggleAndEmit(e.row,e.rowIndex),!0;this.expandedRows.size>0&&queueMicrotask(()=>this.#e())}onKeyDown(e){if(e.key!==" ")return;const t=this.grid._focusCol,i=this.grid._focusRow,n=this.visibleColumns[t];if(!n||!Me(n))return;const o=this.rows[i];if(o)return e.preventDefault(),this.toggleAndEmit(o,i),this.requestRenderWithFocus(),!0}afterRender(){this.#e()}onScrollRender(){!this.config.detailRenderer||this.expandedRows.size===0||this.#e()}#e(){if(!this.config.detailRenderer)return;const e=this.gridElement?.querySelector(".rows");if(!e)return;const t=this.grid,i=t._rowPool,n=t._virtualization?.start??0,o=t._virtualization?.end??0,s=this.columns.length,l=n,a=o,c=new Map;if(i){const d=Math.min(i.length,a-l);for(let u=0;u<d;u++){const h=i[u];h.parentNode===e&&c.set(l+u,h)}}else{const d=e.querySelectorAll(".data-grid-row");for(const u of d){const h=u.querySelector(".cell[data-row]"),p=h?parseInt(h.getAttribute("data-row")??"-1",10):-1;p>=0&&c.set(p,u)}}for(const[d,u]of this.detailElements){const h=this.rows.indexOf(d),p=this.expandedRows.has(d),g=h>=0&&c.has(h);if(!p||!g){const f=this.grid.__frameworkAdapter;if(f?.unmount){const y=u.querySelector(".master-detail-cell")?.firstElementChild;y&&f.unmount(y)}u.parentNode&&u.remove(),this.detailElements.delete(d)}}for(const[d,u]of c){const h=this.rows[d];if(!h||!this.expandedRows.has(h))continue;const p=this.detailElements.get(h);if(p){p.previousElementSibling!==u&&u.after(p);continue}const g=Wo(h,d,this.config.detailRenderer,s);typeof this.config.detailHeight=="number"&&(g.style.height=`${this.config.detailHeight}px`),u.after(g),this.detailElements.set(h,g);const f=this.rowsToAnimate.has(h);f&&this.rowsToAnimate.delete(h),f&&this.animateExpand(g,h,d)||requestAnimationFrame(()=>{this.#t(g,h,d)})}}getExtraHeight(){let e=0;for(const t of this.expandedRows)e+=this.getDetailHeight(t);return e}getExtraHeightBefore(e){let t=0;for(const i of this.expandedRows){const n=this.rows.indexOf(i);n>=0&&n<e&&(t+=this.getDetailHeight(i))}return t}getRowHeight(e,t){if(!this.expandedRows.has(e))return;const n=this.grid.defaultRowHeight??28,o=this.getDetailHeight(e);return n+o}adjustVirtualStart(e,t,i){if(this.expandedRows.size===0)return e;const n=this.grid?._virtualization?.positionCache;let o=e;if(n&&n.length>0)for(const s of this.expandedRows){const l=this.rows.indexOf(s);if(l<0||l>=e)continue;n[l].offset+n[l].height>t&&l<o&&(o=l)}else{const s=[];for(const a of this.expandedRows){const c=this.rows.indexOf(a);c>=0&&s.push({index:c,row:a})}s.sort((a,c)=>a.index-c.index);let l=0;for(const{index:a,row:c}of s){const d=a*i+l,u=this.getDetailHeight(c),h=d+i+u;l+=u,!(a>=e)&&h>t&&a<o&&(o=a)}}return o}expand(e){const t=this.rows[e];t&&(this.rowsToAnimate.add(t),this.expandedRows=Go(this.expandedRows,t),this.requestRender())}collapse(e){const t=this.rows[e];t&&(this.expandedRows=Bo(this.expandedRows,t),this.requestRender())}toggle(e){const t=this.rows[e];t&&(this.expandedRows=_i(this.expandedRows,t),this.expandedRows.has(t)&&this.rowsToAnimate.add(t),this.requestRender())}isExpanded(e){const t=this.rows[e];return t?$o(this.expandedRows,t):!1}expandAll(){for(const e of this.rows)this.rowsToAnimate.add(e),this.expandedRows.add(e);this.requestRender()}collapseAll(){this.expandedRows.clear(),this.requestRender()}getExpandedRows(){const e=[];for(const t of this.expandedRows){const i=this.rows.indexOf(t);i>=0&&e.push(i)}return e}getDetailElement(e){const t=this.rows[e];return t?this.detailElements.get(t):void 0}refreshDetailRenderer(){const e=this.config.detailRenderer;if(this.config={...this.config,detailRenderer:void 0},this.parseLightDomDetail(),!this.config.detailRenderer&&e&&(this.config={...this.config,detailRenderer:e}),this.config.detailRenderer){const t=this.grid;typeof t.refreshColumns=="function"?t.refreshColumns():this.requestRender()}}}function Vo(r,e,t){return e.length?[...r].sort((i,n)=>{for(const o of e){const l=t.find(u=>u.field===o.field)?.sortComparator??Uo,a=i[o.field],c=n[o.field],d=l(a,c,i,n);if(d!==0)return o.direction==="asc"?d:-d}return 0}):[...r]}function Uo(r,e){return r==null&&e==null?0:r==null?1:e==null?-1:typeof r=="number"&&typeof e=="number"?r-e:r instanceof Date&&e instanceof Date?r.getTime()-e.getTime():typeof r=="boolean"&&typeof e=="boolean"?r===e?0:r?-1:1:String(r).localeCompare(String(e))}function jo(r,e,t,i){const n=r.find(o=>o.field===e);return t?n?n.direction==="asc"?r.map(o=>o.field===e?{...o,direction:"desc"}:o):r.filter(o=>o.field!==e):r.length<i?[...r,{field:e,direction:"asc"}]:r:n?.direction==="asc"?[{field:e,direction:"desc"}]:n?.direction==="desc"?[]:[{field:e,direction:"asc"}]}function Ai(r,e){const t=r.findIndex(i=>i.field===e);return t>=0?t+1:void 0}function ki(r,e){return r.find(t=>t.field===e)?.direction}const Yo='@layer tbw-plugins{.header-cell[data-sort=asc]:after{content:"↑";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.header-cell[data-sort=desc]:after{content:"↓";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-indicator{margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-index{font-size:var(--tbw-font-size-2xs, .7em);background:var(--tbw-multi-sort-badge-bg, var(--tbw-color-panel-bg));color:var(--tbw-multi-sort-badge-color, var(--tbw-color-fg));border-radius:50%;width:var(--tbw-multi-sort-badge-size, 1em);height:var(--tbw-multi-sort-badge-size, 1em);display:inline-flex;align-items:center;justify-content:center;margin-left:var(--tbw-spacing-xs, .125em);font-weight:600}}';class Xo extends M{name="multiSort";styles=Yo;get defaultConfig(){return{maxSortColumns:3,showSortIndex:!0}}sortModel=[];cachedSortResult=null;clearCoreSortState(){const e=this.gridElement;e&&(e._sortState=null)}detach(){this.sortModel=[],this.cachedSortResult=null}processRows(e){if(this.sortModel.length===0)return this.cachedSortResult=null,[...e];const t=this.gridElement;if(t&&!t._isGridEditMode&&typeof t._activeEditRows=="number"&&t._activeEditRows!==-1&&this.cachedSortResult&&this.cachedSortResult.length===e.length)return[...this.cachedSortResult];const i=Vo([...e],this.sortModel,[...this.columns]);return this.cachedSortResult=i,i}onHeaderClick(e){if(!this.columns.find(o=>o.field===e.field)?.sortable)return!1;const i=e.originalEvent.shiftKey,n=this.config.maxSortColumns??3;return this.sortModel=jo(this.sortModel,e.field,i,n),this.clearCoreSortState(),this.emit("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),this.grid?.requestStateChange?.(),!0}afterRender(){const e=this.gridElement;if(!e)return;const t=this.config.showSortIndex!==!1;e.querySelectorAll(".header-row .cell[data-field]").forEach(n=>{const o=n.getAttribute("data-field");if(!o)return;const s=Ai(this.sortModel,o),l=ki(this.sortModel,o);if(n.querySelector(".sort-index")?.remove(),l){n.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove(),n.setAttribute("data-sort",l);const d=document.createElement("span");d.className="sort-indicator",this.setIcon(d,this.resolveIcon(l==="asc"?"sortAsc":"sortDesc"));const u=n.querySelector(".tbw-filter-btn"),h=n.querySelector(".resize-handle"),p=u??h;if(p?n.insertBefore(d,p):n.appendChild(d),t&&this.sortModel.length>1&&s!==void 0){const g=document.createElement("span");g.className="sort-index",g.textContent=String(s),d.nextSibling?n.insertBefore(g,d.nextSibling):n.appendChild(g)}}else n.removeAttribute("data-sort"),n.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove()})}getSortModel(){return[...this.sortModel]}setSortModel(e){this.sortModel=[...e],this.clearCoreSortState(),this.emit("sort-change",{sortModel:[...e]}),this.requestRender(),this.grid?.requestStateChange?.()}clearSort(){this.sortModel=[],this.clearCoreSortState(),this.emit("sort-change",{sortModel:[]}),this.requestRender(),this.grid?.requestStateChange?.()}getSortIndex(e){return Ai(this.sortModel,e)}getSortDirection(e){return ki(this.sortModel,e)}getColumnState(e){const t=this.sortModel.findIndex(n=>n.field===e);return t===-1?void 0:{sort:{direction:this.sortModel[t].direction,priority:t}}}applyColumnState(e,t){if(!t.sort){this.sortModel=this.sortModel.filter(o=>o.field!==e);return}const i=this.sortModel.findIndex(o=>o.field===e),n={field:e,direction:t.sort.direction};i!==-1?this.sortModel[i]=n:this.sortModel.splice(t.sort.priority,0,n),this.clearCoreSortState()}}function Z(r){return r.pinned??r.sticky??r.meta?.pinned??r.meta?.sticky}function gt(r,e){return xn(r,e)}function Ti(r,e){const t=Z(r);return t?gt(t,e)==="left":!1}function Li(r,e){const t=Z(r);return t?gt(t,e)==="right":!1}function Qo(r,e="ltr"){return r.filter(t=>Ti(t,e))}function Zo(r,e="ltr"){return r.filter(t=>Li(t,e))}function pt(r){return r.some(e=>Z(e)!=null)}function Pi(r,e){const t=Array.from(r.querySelectorAll(".header-row .cell"));if(!t.length)return;const i=pe(r);let n=0;for(const s of e)if(Ti(s,i)){const l=t.find(a=>a.getAttribute("data-field")===s.field);l&&(l.classList.add("sticky-left"),l.style.position="sticky",l.style.left=n+"px",r.querySelectorAll(`.data-grid-row .cell[data-field="${s.field}"]`).forEach(a=>{a.classList.add("sticky-left"),a.style.position="sticky",a.style.left=n+"px"}),n+=l.offsetWidth)}let o=0;for(const s of[...e].reverse())if(Li(s,i)){const l=t.find(a=>a.getAttribute("data-field")===s.field);l&&(l.classList.add("sticky-right"),l.style.position="sticky",l.style.right=o+"px",r.querySelectorAll(`.data-grid-row .cell[data-field="${s.field}"]`).forEach(a=>{a.classList.add("sticky-right"),a.style.position="sticky",a.style.right=o+"px"}),o+=l.offsetWidth)}}function Jo(r,e="ltr"){const t=[],i=[],n=[];for(const o of r){const s=Z(o);s?gt(s,e)==="left"?t.push(o):n.push(o):i.push(o)}return[...t,...i,...n]}function Hi(r){r.querySelectorAll(".sticky-left, .sticky-right").forEach(t=>{t.classList.remove("sticky-left","sticky-right"),t.style.position="",t.style.left="",t.style.right=""})}const Ii="canMoveColumn";class es extends M{static manifest={ownedProperties:[{property:"pinned",level:"column",description:'the "pinned" column property',isUsed:e=>e==="left"||e==="right"||e==="start"||e==="end"},{property:"sticky",level:"column",description:'the "sticky" column property (deprecated, use "pinned")',isUsed:e=>e==="left"||e==="right"||e==="start"||e==="end"}],incompatibleWith:[{name:"groupingColumns",reason:"Pinning reorders columns to the grid edges, but moving a column out of its column group is not supported. The group header layout cannot accommodate members at different positions."}],queries:[{type:Ii,description:"Prevents pinned (sticky) columns from being moved/reordered"},{type:"getStickyOffsets",description:"Returns the sticky offsets for left/right pinned columns"},{type:"getContextMenuItems",description:"Contributes pin/unpin items to the header context menu"}]};name="pinnedColumns";get defaultConfig(){return{}}isApplied=!1;leftOffsets=new Map;rightOffsets=new Map;#t=[];detach(){this.leftOffsets.clear(),this.rightOffsets.clear(),this.isApplied=!1,this.#t=[]}static detect(e,t){const i=t?.columns;return Array.isArray(i)?pt(i):!1}processColumns(e){const t=[...e];if(this.isApplied=pt(t),!this.isApplied)return t;const i=this.gridElement,n=i?pe(i):"ltr";return Jo(t,n)}afterRender(){if(!this.isApplied)return;const e=this.grid,t=[...this.columns];if(!pt(t)){Hi(e),this.isApplied=!1;return}queueMicrotask(()=>{Pi(e,t)})}handleQuery(e){switch(e.type){case Ii:{const t=e.context;return Z(t)!=null?!1:void 0}case"getStickyOffsets":return{left:Object.fromEntries(this.leftOffsets),right:Object.fromEntries(this.rightOffsets)};case"getContextMenuItems":{const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field||i.meta?.lockPinning||this.grid?.getPluginByName("groupingColumns")?.isGroupingActive())return;const s=Z(i)!=null,l=[];return s?l.push({id:"pinned/unpin",label:"Unpin Column",icon:"📌",order:40,action:()=>this.setPinPosition(i.field,void 0)}):(l.push({id:"pinned/pin-left",label:"Pin Left",icon:"⬅",order:40,action:()=>this.setPinPosition(i.field,"left")}),l.push({id:"pinned/pin-right",label:"Pin Right",icon:"➡",order:41,action:()=>this.setPinPosition(i.field,"right")})),l}default:return}}setPinPosition(e,t){const i=this.columns;if(!i?.length)return;const n=i.findIndex(s=>s.field===e);if(n===-1)return;const o=this.grid;if(t){this.#t.length===0&&(this.#t=i.map(l=>l.field));const s=i.map(l=>{if(l.field!==e)return l;const a={...l};return a.pinned=t,delete a.sticky,a});o.columns=s}else{const l={...i[n]};delete l.pinned,delete l.sticky;const a=[...i];a.splice(n,1);const c=this.#t.indexOf(e);if(c>=0){let d=a.length;for(let u=0;u<a.length;u++){if(Z(a[u]))continue;if(this.#t.indexOf(a[u].field)>c){d=u;break}}a.splice(d,0,l)}else a.splice(Math.min(n,a.length),0,l);a.some(d=>Z(d)!=null)||(this.#t=[]),o.columns=a}}refreshStickyOffsets(){const e=[...this.columns];Pi(this.grid,e)}getLeftPinnedColumns(){const e=[...this.columns],t=pe(this.grid);return Qo(e,t)}getRightPinnedColumns(){const e=[...this.columns],t=pe(this.grid);return Zo(e,t)}clearStickyPositions(){Hi(this.grid)}getHorizontalScrollOffsets(e,t){if(!this.isApplied)return;let i=0,n=0;if(e){const s=e.querySelectorAll(".sticky-left"),l=e.querySelectorAll(".sticky-right");s.forEach(a=>{i+=a.offsetWidth}),l.forEach(a=>{n+=a.offsetWidth})}else this.grid.querySelectorAll(".header-row .cell").forEach(a=>{a.classList.contains("sticky-left")?i+=a.offsetWidth:a.classList.contains("sticky-right")&&(n+=a.offsetWidth)});const o=t?.classList.contains("sticky-left")||t?.classList.contains("sticky-right");return{left:i,right:n,skipScroll:o}}}function ts(r){return typeof r=="object"&&r!==null&&"aggFunc"in r}function wt(r,e){const t=document.createElement("div");t.className="tbw-pinned-rows",t.setAttribute("role","presentation"),t.setAttribute("aria-live","polite");const i=document.createElement("div");i.className="tbw-pinned-rows-left";const n=document.createElement("div");n.className="tbw-pinned-rows-center";const o=document.createElement("div");if(o.className="tbw-pinned-rows-right",r.showRowCount!==!1){const s=document.createElement("span");s.className="tbw-status-panel tbw-status-panel-row-count",s.textContent=`Total: ${e.totalRows} rows`,i.appendChild(s)}if(r.showFilteredCount&&e.filteredRows!==e.totalRows){const s=document.createElement("span");s.className="tbw-status-panel tbw-status-panel-filtered-count",s.textContent=`Filtered: ${e.filteredRows}`,i.appendChild(s)}if(r.showSelectedCount&&e.selectedRows>0){const s=document.createElement("span");s.className="tbw-status-panel tbw-status-panel-selected-count",s.textContent=`Selected: ${e.selectedRows}`,o.appendChild(s)}if(r.customPanels)for(const s of r.customPanels){const l=os(s,e);switch(s.position){case"left":i.appendChild(l);break;case"center":n.appendChild(l);break;case"right":o.appendChild(l);break}}return t.appendChild(i),t.appendChild(n),t.appendChild(o),t}function Di(r){const e=document.createElement("div");return e.className=`tbw-aggregation-rows tbw-aggregation-rows-${r}`,e.setAttribute("role","presentation"),e}function Mi(r,e,t,i,n=!1){r.innerHTML="";for(const o of e){const s=document.createElement("div");s.className="tbw-aggregation-row",s.setAttribute("role","presentation"),o.id&&s.setAttribute("data-aggregation-id",o.id),o.fullWidth??n?is(s,o,t,i):ns(s,o,t,i),r.appendChild(s)}}function is(r,e,t,i){const n=document.createElement("div");n.className="tbw-aggregation-cell tbw-aggregation-cell-full",n.style.gridColumn="1 / -1";const o=typeof e.label=="function"?e.label(i,t):e.label;if(o){const l=document.createElement("span");l.className="tbw-aggregation-label",l.textContent=o,n.appendChild(l)}const s=rs(e,t,i);s&&n.appendChild(s),r.appendChild(n)}function ns(r,e,t,i){for(const n of t){const o=document.createElement("div");o.className="tbw-aggregation-cell",o.setAttribute("data-field",n.field);const{value:s,formatter:l}=zi(e,n,i);s!=null?o.textContent=l?l(s,n.field,n):String(s):o.textContent="",r.appendChild(o)}}function zi(r,e,t){let i,n;const o=r.aggregators?.[e.field];if(o)if(ts(o)){const s=Ri(o.aggFunc);s&&(i=s(t,e.field,e)),n=o.formatter}else{const s=Ri(o);s&&(i=s(t,e.field,e))}else if(r.cells&&Object.prototype.hasOwnProperty.call(r.cells,e.field)){const s=r.cells[e.field];typeof s=="function"?i=s(t,e.field,e):i=s}return{value:i,formatter:n}}function rs(r,e,t){const i=r.aggregators&&Object.keys(r.aggregators).length>0,n=r.cells&&Object.keys(r.cells).length>0;if(!i&&!n)return null;const o=document.createElement("span");o.className="tbw-aggregation-aggregates";for(const s of e){const{value:l,formatter:a}=zi(r,s,t);if(l!=null){const c=document.createElement("span");c.className="tbw-aggregation-aggregate",c.setAttribute("data-field",s.field);const d=s.header??s.field,u=a?a(l,s.field,s):String(l);c.textContent=`${d}: ${u}`,o.appendChild(c)}}return o.children.length>0?o:null}function os(r,e){const t=document.createElement("div");t.className="tbw-status-panel tbw-status-panel-custom",t.id=`status-panel-${r.id}`;const i=r.render(e);return typeof i=="string"?t.innerHTML=i:t.appendChild(i),t}function Oi(r,e,t,i,n){return{totalRows:r.length,filteredRows:n?.cachedResult?.length??r.length,selectedRows:i?.selected?.size??0,columns:e,rows:r,grid:t}}const ss="@layer tbw-plugins{.tbw-footer{flex-shrink:0;z-index:var(--tbw-z-layer-pinned-rows, 20);background:var(--tbw-color-panel-bg)}.tbw-pinned-rows{display:flex;align-items:center;justify-content:space-between;padding:var(--tbw-button-padding, var(--tbw-spacing-md, .5rem) var(--tbw-spacing-lg, .75rem));background:var(--tbw-pinned-rows-bg, var(--tbw-color-panel-bg));border-top:1px solid var(--tbw-pinned-rows-border, var(--tbw-color-border));font-size:var(--tbw-font-size-xs, .75rem);color:var(--tbw-pinned-rows-color, var(--tbw-color-fg-muted));min-height:32px;box-sizing:border-box;min-width:fit-content}.tbw-pinned-rows-left,.tbw-pinned-rows-center,.tbw-pinned-rows-right{display:flex;align-items:center;gap:var(--tbw-spacing-xl, 1rem)}.tbw-pinned-rows-left{justify-content:flex-start}.tbw-pinned-rows-center{justify-content:center;flex:1}.tbw-pinned-rows-right{justify-content:flex-end}.tbw-status-panel{white-space:nowrap}.tbw-aggregation-rows{min-width:fit-content;background:var(--tbw-aggregation-bg, var(--tbw-color-header-bg))}.tbw-aggregation-rows-top{border-bottom:1px solid var(--tbw-aggregation-border, var(--tbw-color-border))}.tbw-aggregation-rows-bottom{border-top:1px solid var(--tbw-aggregation-border, var(--tbw-color-border))}.tbw-aggregation-row{display:grid;grid-template-columns:var(--tbw-column-template);font-size:var(--tbw-aggregation-font-size, .8em);font-weight:var(--tbw-aggregation-font-weight, 600)}.tbw-aggregation-cell{padding:var(--tbw-cell-padding, .125rem .5rem);min-height:var(--tbw-row-height, 1.75rem);display:block;align-items:center;align-content:center;border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;text-overflow:ellipsis;white-space:var(--tbw-cell-white-space, nowrap)}.tbw-aggregation-cell:last-child{border-right:0}.tbw-aggregation-cell-full{grid-column:1 / -1;border-right:0;display:flex;align-items:center;gap:var(--tbw-spacing-lg, .75rem)}.tbw-aggregation-label{white-space:nowrap}.tbw-aggregation-aggregates{display:flex;align-items:center;gap:var(--tbw-spacing-lg, .75rem);font-weight:400;opacity:.85}.tbw-aggregation-aggregate{white-space:nowrap}}";class ls extends M{name="pinnedRows";styles=ss;get defaultConfig(){return{position:"bottom",showRowCount:!0,showSelectedCount:!0,showFilteredCount:!0}}infoBarElement=null;topAggregationContainer=null;bottomAggregationContainer=null;footerWrapper=null;detach(){this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null),this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null)}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-scroll-area")??e.querySelector(".tbw-grid-content")??e.children[0];if(!t)return;this.footerWrapper&&!t.contains(this.footerWrapper)&&(this.footerWrapper=null,this.bottomAggregationContainer=null,this.infoBarElement=null),this.topAggregationContainer&&!t.contains(this.topAggregationContainer)&&(this.topAggregationContainer=null),this.infoBarElement&&!t.contains(this.infoBarElement)&&(this.infoBarElement=null);const i=this.getSelectionState(),n=this.getFilterState(),o=Oi(this.sourceRows,this.columns,this.grid,i,n),s=this.config.aggregationRows||[],l=s.filter(h=>h.position==="top"),a=s.filter(h=>h.position!=="top");if(l.length>0){if(!this.topAggregationContainer){this.topAggregationContainer=Di("top");const h=e.querySelector(".header");h&&h.nextSibling?t.insertBefore(this.topAggregationContainer,h.nextSibling):t.appendChild(this.topAggregationContainer)}Mi(this.topAggregationContainer,l,this.visibleColumns,this.sourceRows,this.config.fullWidth)}else this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null);const c=this.config.showRowCount!==!1||this.config.showSelectedCount&&o.selectedRows>0||this.config.showFilteredCount&&o.filteredRows!==o.totalRows||this.config.customPanels&&this.config.customPanels.length>0,d=c&&this.config.position!=="top",u=a.length>0||d;if(c&&this.config.position==="top")if(!this.infoBarElement)this.infoBarElement=wt(this.config,o),t.insertBefore(this.infoBarElement,t.firstChild);else{const h=wt(this.config,o);this.infoBarElement.replaceWith(h),this.infoBarElement=h}else this.config.position==="top"&&this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null);u?(this.footerWrapper||(this.footerWrapper=document.createElement("div"),this.footerWrapper.className="tbw-footer",t.appendChild(this.footerWrapper)),this.footerWrapper.innerHTML="",a.length>0&&(this.bottomAggregationContainer||(this.bottomAggregationContainer=Di("bottom")),this.footerWrapper.appendChild(this.bottomAggregationContainer),Mi(this.bottomAggregationContainer,a,this.visibleColumns,this.sourceRows,this.config.fullWidth)),d&&(this.infoBarElement=wt(this.config,o),this.footerWrapper.appendChild(this.infoBarElement))):this.cleanupFooter()}cleanup(){this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null),this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null)}cleanupFooter(){this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.infoBarElement&&this.config.position!=="top"&&(this.infoBarElement.remove(),this.infoBarElement=null)}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}getFilterState(){try{return this.grid?.getPluginState?.("filtering")??null}catch{return null}}refresh(){this.requestRender()}getContext(){const e=this.getSelectionState(),t=this.getFilterState();return Oi(this.rows,this.columns,this.grid,e,t)}addPanel(e){this.config.customPanels||(this.config.customPanels=[]),this.config.customPanels.push(e),this.requestRender()}removePanel(e){this.config.customPanels&&(this.config.customPanels=this.config.customPanels.filter(t=>t.id!==e),this.requestRender())}addAggregationRow(e){this.config.aggregationRows||(this.config.aggregationRows=[]),this.config.aggregationRows.push(e),this.requestRender()}removeAggregationRow(e){this.config.aggregationRows&&(this.config.aggregationRows=this.config.aggregationRows.filter(t=>t.id!==e),this.requestRender())}}const as=Ho;function cs(r){const e=[];return!r.rowGroupFields?.length&&!r.columnGroupFields?.length&&e.push("At least one row or column group field is required"),r.valueFields?.length||e.push("At least one value field is required"),e}function mt(r,e){return[...r,e].join("|")}function ds(r,e){const t=e.rowGroupFields??[],i=e.columnGroupFields??[],n=e.valueFields??[],o=us(r,i),s=Fi(r,t,i,o,n,0,""),l=fs(s,o,n),a=Object.values(l).reduce((c,d)=>c+d,0);return{rows:s,columnKeys:o,totals:l,grandTotal:a}}function us(r,e){if(e.length===0)return["value"];const t=new Set;for(const i of r){const n=e.map(o=>String(i[o]??"")).join("|");t.add(n)}return[...t].sort()}function hs(r,e){const t=new Map;for(const i of r){const n=String(i[e]??""),o=t.get(n);o?o.push(i):t.set(n,[i])}return t}function Fi(r,e,t,i,n,o,s){const l=[];if(e.length===0){const h=Ni(r,t,i,n),p=qi(h);return l.push({rowKey:s||"all",rowLabel:s||"All",depth:o,values:h,total:p,isGroup:!1,rowCount:r.length}),l}const a=e[0],c=e.slice(1),d=c.length>0,u=hs(r,a);for(const[h,p]of u){const g=s?`${s}|${h}`:h,f=Ni(p,t,i,n),w=qi(f);let y;d&&(y=Fi(p,c,t,i,n,o+1,g)),l.push({rowKey:g,rowLabel:h||"(blank)",depth:o,values:f,total:w,isGroup:d,children:y,rowCount:p.length})}return l}function Ni(r,e,t,i){const n={};for(const o of t)for(const s of i){const a=(e.length>0?r.filter(h=>e.map(p=>String(h[p]??"")).join("|")===o):r).map(h=>Number(h[s.field])||0),c=as(s.aggFunc),d=a.length>0?c(a):null,u=mt([o],s.field);n[u]=d}return n}function qi(r){let e=0;for(const t of Object.values(r))e+=t??0;return e}function fs(r,e,t){const i={};function n(o){for(const s of o)if(!s.isGroup||!s.children?.length)for(const l of e)for(const a of t){const c=mt([l],a.field);i[c]=(i[c]??0)+(s.values[c]??0)}else s.children&&n(s.children)}return n(r),i}function gs(r,e,t=!0){const i=[];function n(o){i.push(o);const s=e?e.has(o.rowKey):t;if(o.children&&s)for(const l of o.children)n(l)}for(const o of r)n(o);return i}function ps(r){const e=[];function t(i){if(i.isGroup&&e.push(i.rowKey),i.children)for(const n of i.children)t(n)}for(const i of r)t(i);return e}const ws=["sum","avg","count","min","max","first","last"];function ms(r,e,t,i){const n=new AbortController,o={config:e,callbacks:i,signal:n.signal},s=document.createElement("div");return s.className="tbw-pivot-panel",s.appendChild(Ee("Options",()=>xs(t,o))),s.appendChild(Ee("Row Groups",()=>Gi("rowGroups",o))),s.appendChild(Ee("Column Groups",()=>Gi("columnGroups",o))),s.appendChild(Ee("Values",()=>vs(o))),s.appendChild(Ee("Available Fields",()=>Cs(o))),r.appendChild(s),()=>{n.abort(),s.remove()}}function Ee(r,e){const t=document.createElement("div");t.className="tbw-pivot-section";const i=document.createElement("div");i.className="tbw-pivot-section-header",i.textContent=r;const n=document.createElement("div");return n.className="tbw-pivot-section-content",n.appendChild(e()),t.appendChild(i),t.appendChild(n),t}function Gi(r,e){const{config:t,callbacks:i,signal:n}=e,o=document.createElement("div");o.className="tbw-pivot-drop-zone",o.setAttribute("data-zone",r);const s=r==="rowGroups"?t.rowGroupFields??[]:t.columnGroupFields??[];if(s.length===0){const l=document.createElement("div");l.className="tbw-pivot-placeholder",l.textContent="Drag fields here or click to add",o.appendChild(l)}else for(const l of s)o.appendChild(bs(l,r,e));return o.addEventListener("dragover",l=>{l.preventDefault(),o.classList.add("drag-over")},{signal:n}),o.addEventListener("dragleave",()=>{o.classList.remove("drag-over")},{signal:n}),o.addEventListener("drop",l=>{l.preventDefault(),o.classList.remove("drag-over");const a=l.dataTransfer?.getData("text/plain");a&&i.onAddFieldToZone(a,r)},{signal:n}),o}function bs(r,e,t){const{callbacks:i,signal:n}=t,o=document.createElement("div");o.className="tbw-pivot-field-chip",o.draggable=!0;const s=i.getAvailableFields().find(c=>c.field===r),l=document.createElement("span");l.className="tbw-pivot-chip-label",l.textContent=s?.header??r;const a=document.createElement("button");return a.className="tbw-pivot-chip-remove",a.innerHTML="×",a.title="Remove field",a.addEventListener("click",c=>{c.stopPropagation(),i.onRemoveFieldFromZone(r,e)},{signal:n}),o.appendChild(l),o.appendChild(a),o.addEventListener("dragstart",c=>{c.dataTransfer?.setData("text/plain",r),c.dataTransfer?.setData("source-zone",e),o.classList.add("dragging")},{signal:n}),o.addEventListener("dragend",()=>{o.classList.remove("dragging")},{signal:n}),o}function vs(r){const{config:e,callbacks:t,signal:i}=r,n=document.createElement("div");n.className="tbw-pivot-drop-zone tbw-pivot-values-zone",n.setAttribute("data-zone","values");const o=e.valueFields??[];if(o.length===0){const s=document.createElement("div");s.className="tbw-pivot-placeholder",s.textContent="Drag numeric fields here for aggregation",n.appendChild(s)}else for(const s of o)n.appendChild(ys(s,r));return n.addEventListener("dragover",s=>{s.preventDefault(),n.classList.add("drag-over")},{signal:i}),n.addEventListener("dragleave",()=>{n.classList.remove("drag-over")},{signal:i}),n.addEventListener("drop",s=>{s.preventDefault(),n.classList.remove("drag-over");const l=s.dataTransfer?.getData("text/plain");l&&t.onAddValueField(l,"sum")},{signal:i}),n}function ys(r,e){const{callbacks:t,signal:i}=e,n=document.createElement("div");n.className="tbw-pivot-field-chip tbw-pivot-value-chip";const o=t.getAvailableFields().find(d=>d.field===r.field),s=document.createElement("div");s.className="tbw-pivot-value-label-wrapper";const l=document.createElement("span");l.className="tbw-pivot-chip-label",l.textContent=o?.header??r.field;const a=document.createElement("select");a.className="tbw-pivot-agg-select",a.title="Aggregation function";for(const d of ws){const u=document.createElement("option");u.value=d,u.textContent=d.toUpperCase(),u.selected=d===r.aggFunc,a.appendChild(u)}a.addEventListener("change",()=>{t.onUpdateValueAggFunc(r.field,a.value)},{signal:i});const c=document.createElement("button");return c.className="tbw-pivot-chip-remove",c.innerHTML="×",c.title="Remove value field",c.addEventListener("click",d=>{d.stopPropagation(),t.onRemoveValueField(r.field)},{signal:i}),s.appendChild(l),s.appendChild(a),n.appendChild(s),n.appendChild(c),n}function Cs(r){const{config:e,callbacks:t,signal:i}=r,n=document.createElement("div");n.className="tbw-pivot-available-fields";const o=t.getAvailableFields(),s=new Set([...e.rowGroupFields??[],...e.columnGroupFields??[],...e.valueFields?.map(a=>a.field)??[]]),l=o.filter(a=>!s.has(a.field));if(l.length===0){const a=document.createElement("div");a.className="tbw-pivot-placeholder",a.textContent="All fields are in use",n.appendChild(a)}else for(const a of l){const c=document.createElement("div");c.className="tbw-pivot-field-chip available",c.textContent=a.header,c.draggable=!0,c.title=`Drag to add "${a.field}" to a zone`,c.addEventListener("dragstart",d=>{d.dataTransfer?.setData("text/plain",a.field),c.classList.add("dragging")},{signal:i}),c.addEventListener("dragend",()=>{c.classList.remove("dragging")},{signal:i}),n.appendChild(c)}return n}function xs(r,e){const{config:t,callbacks:i,signal:n}=e,o=document.createElement("div");return o.className="tbw-pivot-options",o.appendChild(bt("Enable Pivot View",r,s=>{i.onTogglePivot(s)},n)),o.appendChild(bt("Show Row Totals",t.showTotals??!0,s=>{i.onOptionChange("showTotals",s)},n)),o.appendChild(bt("Show Grand Total",t.showGrandTotal??!0,s=>{i.onOptionChange("showGrandTotal",s)},n)),o}function bt(r,e,t,i){const n=document.createElement("label");n.className="tbw-pivot-checkbox";const o=document.createElement("input");o.type="checkbox",o.checked=e,o.addEventListener("change",()=>t(o.checked),{signal:i});const s=document.createElement("span");return s.textContent=r,n.appendChild(o),n.appendChild(s),n}function Es(r,e,t){return e.className="data-grid-row pivot-group-row",e.setAttribute("data-pivot-depth",String(r.__pivotDepth??0)),e.setAttribute("data-pivot-key",String(r.__pivotRowKey??"")),e.setAttribute("role","row"),e.innerHTML="",t.columns.forEach((i,n)=>{const o=document.createElement("div");if(o.className="cell",o.setAttribute("data-col",String(n)),o.setAttribute("data-row",String(t.rowIndex)),o.setAttribute("role","gridcell"),n===0){const s=Number(r.__pivotIndent)||0;o.style.paddingLeft=`${s}px`;const l=String(r.__pivotRowKey),a=document.createElement("button");a.type="button",a.className="pivot-toggle",a.setAttribute("aria-label",r.__pivotExpanded?"Collapse group":"Expand group"),t.setIcon(a,t.resolveIcon(r.__pivotExpanded?"collapse":"expand")),a.addEventListener("click",u=>{u.stopPropagation(),t.onToggle(l)}),o.appendChild(a);const c=document.createElement("span");c.className="pivot-label",c.textContent=String(r.__pivotLabel??""),o.appendChild(c);const d=document.createElement("span");d.className="pivot-count",d.textContent=` (${Number(r.__pivotRowCount)||0})`,o.appendChild(d)}else{const s=r[i.field];o.textContent=s!=null?String(s):""}e.appendChild(o)}),!0}function Rs(r,e,t,i){return e.className="data-grid-row pivot-leaf-row",e.setAttribute("data-pivot-depth",String(r.__pivotDepth??0)),e.setAttribute("data-pivot-key",String(r.__pivotRowKey??"")),e.innerHTML="",t.forEach((n,o)=>{const s=document.createElement("div");if(s.className="cell",s.setAttribute("data-col",String(o)),s.setAttribute("data-row",String(i)),s.setAttribute("role","gridcell"),o===0){const l=Number(r.__pivotIndent)||0;s.style.paddingLeft=`${l+20}px`;const a=document.createElement("span");a.className="pivot-label",a.textContent=String(r.__pivotLabel??""),s.appendChild(a)}else{const l=r[n.field];s.textContent=l!=null?String(l):""}e.appendChild(s)}),!0}function Ss(r,e,t){return e.className="pivot-grand-total-row",e.setAttribute("role","presentation"),e.innerHTML="",t.forEach((i,n)=>{const o=document.createElement("div");if(o.className="cell",o.setAttribute("data-col",String(n)),n===0){const s=document.createElement("span");s.className="pivot-label",s.textContent="Grand Total",o.appendChild(s)}else{const s=r[i.field];o.textContent=s!=null?String(s):""}e.appendChild(o)}),!0}const _s='@layer tbw-plugins{.pivot-group-row{display:grid;grid-template-columns:var(--tbw-column-template);font-weight:600;background:var(--tbw-pivot-group-bg, var(--tbw-color-row-alt));min-height:var(--tbw-row-height);border-bottom:var(--tbw-row-divider)}.pivot-group-row:hover{background:var(--tbw-pivot-group-hover, var(--tbw-color-row-hover))}.pivot-leaf-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-pivot-leaf-bg, var(--tbw-color-bg));min-height:var(--tbw-row-height);border-bottom:var(--tbw-row-divider)}.pivot-grand-total-row{display:grid;grid-template-columns:var(--tbw-column-template);font-weight:700;background:var(--tbw-pivot-grand-total-bg, var(--tbw-color-header-bg));min-height:var(--tbw-row-height);border-top:2px solid var(--tbw-color-border-strong)}.pivot-grand-total-row>.cell{display:flex;align-items:center;padding:var(--tbw-cell-padding);border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;min-width:0}.pivot-grand-total-row>.cell:last-child{border-right:0}.pivot-grand-total-footer{position:sticky;bottom:0;z-index:var(--tbw-z-layer-pinned-rows, 20);background:var(--tbw-pivot-grand-total-bg, var(--tbw-color-header-bg));min-width:fit-content}.pivot-group-row>.cell,.pivot-leaf-row>.cell{display:flex;align-items:center;padding:var(--tbw-cell-padding);border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;min-width:0}.pivot-group-row>.cell:last-child,.pivot-leaf-row>.cell:last-child{border-right:0}.pivot-toggle{display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-pivot-toggle-size, var(--tbw-toggle-size, 1.25em));height:var(--tbw-pivot-toggle-size, var(--tbw-toggle-size, 1.25em));margin-right:var(--tbw-spacing-sm, .375em);border:none;background:transparent;cursor:pointer;color:var(--tbw-pivot-toggle-color, var(--tbw-color-fg-muted));border-radius:var(--tbw-border-radius);transition:background var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease),color var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease)}.pivot-toggle:hover{background:var(--tbw-pivot-toggle-hover-bg, var(--tbw-color-row-hover));color:var(--tbw-pivot-toggle-hover-color, var(--tbw-color-fg))}.pivot-toggle:focus{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}.pivot-label{font-weight:inherit}.pivot-count{color:var(--tbw-pivot-count-color, var(--tbw-color-fg-muted));font-size:.9em;font-weight:400}.pivot-total-row{font-weight:700;border-top:2px solid var(--tbw-pivot-border, var(--tbw-color-border-strong))}[data-pivot-depth="1"]{--tbw-pivot-depth: 1}[data-pivot-depth="2"]{--tbw-pivot-depth: 2}[data-pivot-depth="3"]{--tbw-pivot-depth: 3}[data-pivot-depth="4"]{--tbw-pivot-depth: 4}.tbw-pivot-panel{display:flex;flex-direction:column;gap:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));padding:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));height:100%;overflow-y:auto;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-pivot-section{border:1px solid var(--tbw-pivot-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius);background:var(--tbw-pivot-section-bg, var(--tbw-color-bg))}.tbw-pivot-section-header{padding:var(--tbw-button-padding, var(--tbw-spacing-md, .5rem) var(--tbw-spacing-lg, .75rem));font-weight:600;background:var(--tbw-pivot-header-bg, var(--tbw-color-header-bg));border-bottom:1px solid var(--tbw-pivot-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius) var(--tbw-border-radius) 0 0}.tbw-pivot-section-content{padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-pivot-toggle-wrapper{display:flex;align-items:center}.tbw-pivot-toggle-label{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));cursor:pointer}.tbw-pivot-toggle-label input{width:var(--tbw-icon-size, 1rem);height:var(--tbw-icon-size, 1rem);cursor:pointer}.tbw-pivot-drop-zone{min-height:60px;padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border:2px dashed var(--tbw-pivot-drop-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius);background:var(--tbw-pivot-drop-bg, var(--tbw-color-row-alt));display:flex;flex-wrap:wrap;gap:var(--tbw-spacing-sm, .375rem);align-content:flex-start;transition:all .15s ease}.tbw-pivot-drop-zone.drag-over{border-color:var(--tbw-color-accent);background:var(--tbw-pivot-drop-active, var(--tbw-focus-background))}.tbw-pivot-placeholder{color:var(--tbw-color-fg-muted);font-style:italic;padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));text-align:center;width:100%}.tbw-pivot-field-chip{display:inline-flex;align-items:center;gap:var(--tbw-spacing-sm, .375rem);padding:var(--tbw-button-padding-sm, var(--tbw-spacing-xs, .25rem) var(--tbw-spacing-md, .5rem));background:var(--tbw-pivot-chip-bg, var(--tbw-color-header-bg));border:1px solid var(--tbw-pivot-chip-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius);cursor:grab;font-size:var(--tbw-font-size-xs, .75rem);transition:all .15s ease}.tbw-pivot-field-chip:hover{background:var(--tbw-pivot-chip-hover, var(--tbw-color-row-hover));border-color:var(--tbw-color-accent)}.tbw-pivot-field-chip.available{background:var(--tbw-color-bg)}.tbw-pivot-field-chip.dragging{opacity:.5;cursor:grabbing}.tbw-pivot-chip-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:120px}.tbw-pivot-chip-remove{display:flex;align-items:center;justify-content:center;width:var(--tbw-icon-size, 1rem);height:var(--tbw-icon-size, 1rem);padding:0;border:none;background:transparent;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-sm, .875rem);font-weight:700;cursor:pointer;border-radius:50%;transition:all .15s ease}.tbw-pivot-chip-remove:hover{background:var(--tbw-pivot-chip-remove-hover-bg, var(--tbw-color-accent));color:var(--tbw-pivot-chip-remove-hover-fg, var(--tbw-color-accent-fg))}.tbw-pivot-value-chip{padding:var(--tbw-button-padding-sm, var(--tbw-spacing-xs, .25rem) var(--tbw-spacing-md, .5rem))}.tbw-pivot-value-label-wrapper{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));flex:1;min-width:0}.tbw-pivot-agg-select{padding:var(--tbw-spacing-xs, .125rem) var(--tbw-spacing-xs, .25rem);font-size:var(--tbw-font-size-xs, .6875rem);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);background:var(--tbw-color-bg);cursor:pointer}.tbw-pivot-available-fields{display:flex;flex-wrap:wrap;gap:var(--tbw-spacing-sm, .375rem);min-height:40px}.tbw-pivot-options{display:flex;flex-direction:column;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-pivot-checkbox{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));cursor:pointer}.tbw-pivot-checkbox input{width:var(--tbw-icon-size-sm, .875rem);height:var(--tbw-icon-size-sm, .875rem);cursor:pointer}.pivot-group-row.tbw-pivot-slide-in,.pivot-leaf-row.tbw-pivot-slide-in{animation:tbw-pivot-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-pivot-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.pivot-group-row.tbw-pivot-fade-in,.pivot-leaf-row.tbw-pivot-fade-in{animation:tbw-pivot-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-pivot-fade-in{0%{opacity:0}to{opacity:1}}}';class te extends M{name="pivot";styles=_s;static PANEL_ID="pivot";get defaultConfig(){return{active:!0,showTotals:!0,showGrandTotal:!0,showToolPanel:!0,animation:"slide"}}isActive=!1;hasInitialized=!1;pivotResult=null;fieldHeaderMap=new Map;expandedKeys=new Set;defaultExpanded=!0;userHasToggledExpand=!1;originalColumns=[];panelContainer=null;grandTotalFooter=null;previousVisibleKeys=new Set;keysToAnimate=new Set;hasValidPivotConfig(){return(this.config.valueFields?.length??0)>0}get animationStyle(){return this.isAnimationEnabled?this.config.animation??"slide":!1}detach(){this.isActive=!1,this.hasInitialized=!1,this.pivotResult=null,this.fieldHeaderMap.clear(),this.originalColumns=[],this.panelContainer=null,this.cleanupGrandTotalFooter(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.userHasToggledExpand=!1}getToolPanel(){if((this.config?.showToolPanel??this.userConfig?.showToolPanel??!0)!==!1)return{id:te.PANEL_ID,title:"Pivot",icon:"⊞",tooltip:"Configure pivot table",order:90,render:t=>this.renderPanel(t)}}processRows(e){if(!this.hasInitialized&&this.config.active!==!1&&this.hasValidPivotConfig()&&(this.hasInitialized=!0,this.isActive=!0),!this.isActive)return[...e];const t=cs(this.config);if(t.length>0)return this.warn(`Config errors: ${t.join(", ")}`),[...e];this.buildFieldHeaderMap(),this.defaultExpanded=this.config.defaultExpanded??!0,this.pivotResult=ds(e,this.config),this.expandedKeys.size===0&&this.defaultExpanded&&!this.userHasToggledExpand&&this.expandAllKeys();const i=this.config.indentWidth??20,n=gs(this.pivotResult.rows,this.expandedKeys,this.defaultExpanded).map(s=>({__pivotRowKey:s.rowKey,__pivotLabel:s.rowLabel,__pivotDepth:s.depth,__pivotIsGroup:s.isGroup,__pivotHasChildren:!!s.children?.length,__pivotExpanded:this.expandedKeys.has(s.rowKey),__pivotRowCount:s.rowCount??0,__pivotIndent:s.depth*i,__pivotTotal:s.total,...s.values}));this.keysToAnimate.clear();const o=new Set;for(const s of n){const l=s.__pivotRowKey;o.add(l),!this.previousVisibleKeys.has(l)&&s.__pivotDepth>0&&this.keysToAnimate.add(l)}return this.previousVisibleKeys=o,n}processColumns(e){if(!this.isActive||!this.pivotResult)return[...e];const t=[],i=(this.config.rowGroupFields??[]).map(n=>this.fieldHeaderMap.get(n)??n).join(" / ");t.push({field:"__pivotLabel",header:i||"Group",width:200});for(const n of this.pivotResult.columnKeys)for(const o of this.config.valueFields??[]){const s=mt([n],o.field),l=o.header||this.fieldHeaderMap.get(o.field)||o.field;t.push({field:s,header:`${n} - ${l} (${o.aggFunc})`,width:120,type:"number"})}return this.config.showTotals&&t.push({field:"__pivotTotal",header:"Total",width:100,type:"number"}),t}renderRow(e,t,i){const n=e;return n.__pivotRowKey&&n.__pivotHasChildren?Es(n,t,{columns:this.gridColumns,rowIndex:i,onToggle:o=>this.toggle(o),resolveIcon:o=>this.resolveIcon(o),setIcon:(o,s)=>this.setIcon(o,s)}):n.__pivotRowKey!==void 0&&this.isActive?Rs(n,t,this.gridColumns,i):(this.cleanupPivotStyling(t),!1)}cleanupPivotStyling(e){(e.classList.contains("pivot-group-row")||e.classList.contains("pivot-leaf-row")||e.classList.contains("pivot-grand-total-row"))&&(e.classList.remove("pivot-group-row","pivot-leaf-row","pivot-grand-total-row"),e.classList.add("data-grid-row"),e.removeAttribute("data-pivot-depth"),e.innerHTML="")}onKeyDown(e){if(e.key!==" "||!this.isActive)return;const t=this.grid._focusRow,i=this.rows[t];if(!(!i?.__pivotIsGroup||!i.__pivotHasChildren))return e.preventDefault(),this.toggle(i.__pivotRowKey),this.requestRenderWithFocus(),!0}afterRender(){this.isActive&&this.config.showGrandTotal&&this.pivotResult?this.renderGrandTotalFooter():this.cleanupGrandTotalFooter();const e=this.animationStyle;if(e===!1||this.keysToAnimate.size===0)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const i=e==="fade"?"tbw-pivot-fade-in":"tbw-pivot-slide-in";for(const n of t.querySelectorAll(".pivot-group-row, .pivot-leaf-row")){const o=n.dataset.pivotKey;o&&this.keysToAnimate.has(o)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}renderGrandTotalFooter(){if(!this.pivotResult)return;const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-scroll-area")??e.querySelector(".tbw-grid-content")??e.children[0];if(!t)return;this.grandTotalFooter||(this.grandTotalFooter=document.createElement("div"),this.grandTotalFooter.className="pivot-grand-total-footer",t.appendChild(this.grandTotalFooter));const i={__pivotRowKey:"__grandTotal",__pivotLabel:"Grand Total",__pivotIsGrandTotal:!0,__pivotTotal:this.pivotResult.grandTotal,...this.pivotResult.totals};Ss(i,this.grandTotalFooter,this.gridColumns)}cleanupGrandTotalFooter(){this.grandTotalFooter&&(this.grandTotalFooter.remove(),this.grandTotalFooter=null)}toggle(e){this.userHasToggledExpand=!0,this.expandedKeys.has(e)?this.expandedKeys.delete(e):this.expandedKeys.add(e),this.requestRender()}expand(e){this.userHasToggledExpand=!0,this.expandedKeys.add(e),this.requestRender()}collapse(e){this.userHasToggledExpand=!0,this.expandedKeys.delete(e),this.requestRender()}expandAll(){this.userHasToggledExpand=!0,this.expandAllKeys(),this.requestRender()}collapseAll(){this.userHasToggledExpand=!0,this.expandedKeys.clear(),this.requestRender()}expandAllKeys(){if(!this.pivotResult)return;const e=ps(this.pivotResult.rows);for(const t of e)this.expandedKeys.add(t)}isExpanded(e){return this.expandedKeys.has(e)}enablePivot(){this.originalColumns.length===0&&this.captureOriginalColumns(),this.isActive=!0,this.requestRender()}disablePivot(){this.isActive=!1,this.pivotResult=null,this.requestRender()}isPivotActive(){return this.isActive}getPivotResult(){return this.pivotResult}setRowGroupFields(e){this.config.rowGroupFields=e,this.requestRender()}setColumnGroupFields(e){this.config.columnGroupFields=e,this.requestRender()}setValueFields(e){this.config.valueFields=e,this.requestRender()}refresh(){this.pivotResult=null,this.requestRender()}showPanel(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(te.PANEL_ID)||this.grid.toggleToolPanelSection(te.PANEL_ID)}hidePanel(){this.grid.closeToolPanel()}togglePanel(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(te.PANEL_ID)}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(te.PANEL_ID)}get gridColumns(){return this.grid.columns??[]}refreshIfActive(){this.isActive&&this.refresh(),this.refreshPanel()}buildFieldHeaderMap(){const e=this.getAvailableFields();this.fieldHeaderMap.clear();for(const t of e)this.fieldHeaderMap.set(t.field,t.header)}getAvailableFields(){return this.originalColumns.length>0?this.originalColumns:this.captureOriginalColumns()}captureOriginalColumns(){try{const e=this.grid.getAllColumns?.()??this.grid.columns??[];return this.originalColumns=e.filter(t=>!t.field.startsWith("__pivot")).map(t=>({field:t.field,header:t.header??t.field})),this.originalColumns}catch{return[]}}renderPanel(e){this.panelContainer=e,this.originalColumns.length===0&&this.captureOriginalColumns();const t={onTogglePivot:i=>{i?this.enablePivot():this.disablePivot(),this.refreshPanel()},onAddFieldToZone:(i,n)=>this.addFieldToZone(i,n),onRemoveFieldFromZone:(i,n)=>this.removeFieldFromZone(i,n),onAddValueField:(i,n)=>this.addValueField(i,n),onRemoveValueField:i=>this.removeValueField(i),onUpdateValueAggFunc:(i,n)=>this.updateValueAggFunc(i,n),onOptionChange:(i,n)=>{this.config[i]=n,this.isActive&&this.refresh()},getAvailableFields:()=>this.getAvailableFields()};return ms(e,this.config,this.isActive,t)}refreshPanel(){this.panelContainer&&(this.panelContainer.innerHTML="",this.renderPanel(this.panelContainer))}addFieldToZone(e,t){if(t==="rowGroups"){const i=this.config.rowGroupFields??[];i.includes(e)||(this.config.rowGroupFields=[...i,e])}else{const i=this.config.columnGroupFields??[];i.includes(e)||(this.config.columnGroupFields=[...i,e])}this.removeFromOtherZones(e,t),this.refreshIfActive()}removeFieldFromZone(e,t){t==="rowGroups"?this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(i=>i!==e):this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(i=>i!==e),this.refreshIfActive()}removeFromOtherZones(e,t){t!=="rowGroups"&&(this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(i=>i!==e)),t!=="columnGroups"&&(this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(i=>i!==e)),t!=="values"&&(this.config.valueFields=(this.config.valueFields??[]).filter(i=>i.field!==e))}addValueField(e,t){const i=this.config.valueFields??[];i.some(n=>n.field===e)||(this.config.valueFields=[...i,{field:e,aggFunc:t}]),this.removeFromOtherZones(e,"values"),this.refreshIfActive()}removeValueField(e){this.config.valueFields=(this.config.valueFields??[]).filter(t=>t.field!==e),this.refreshIfActive()}updateValueAggFunc(e,t){const i=this.config.valueFields??[],n=i.findIndex(o=>o.field===e);n>=0&&(i[n]={...i[n],aggFunc:t},this.config.valueFields=[...i]),this.isActive&&this.refresh()}}const ze="tbw-print-isolation-style";function As(r,e){const t=document.createElement("style");return t.id=ze,t.textContent=`
111
- /* Print isolation: hide everything except the target grid */
112
- @media print {
113
- /* Hide all body children by default */
114
- body > *:not(#${r}) {
115
- display: none !important;
116
- }
117
-
118
- /* But show the grid and ensure it's not hidden by ancestor rules */
119
- #${r} {
120
- display: block !important;
121
- position: static !important;
122
- visibility: visible !important;
123
- opacity: 1 !important;
124
- overflow: visible !important;
125
- height: auto !important;
126
- width: 100% !important;
127
- max-height: none !important;
128
- margin: 0 !important;
129
- padding: 0 !important;
130
- transform: none !important;
131
- }
132
-
133
- /* If grid is nested, we need to show its ancestors too */
134
- #${r},
135
- #${r} * {
136
- visibility: visible !important;
137
- }
138
-
139
- /* Walk up the DOM and show all ancestors of the grid */
140
- body *:has(> #${r}),
141
- body *:has(#${r}) {
142
- display: block !important;
143
- visibility: visible !important;
144
- opacity: 1 !important;
145
- overflow: visible !important;
146
- height: auto !important;
147
- position: static !important;
148
- transform: none !important;
149
- background: transparent !important;
150
- border: none !important;
151
- padding: 0 !important;
152
- margin: 0 !important;
153
- }
154
-
155
- /* Hide siblings of ancestors (everything that's not in the path to the grid) */
156
- body *:has(#${r}) > *:not(:has(#${r})):not(#${r}) {
157
- display: none !important;
158
- }
159
-
160
- /* Page settings */
161
- @page {
162
- size: ${e};
163
- margin: 1cm;
164
- }
165
-
166
- /* Ensure proper print styling */
167
- body {
168
- margin: 0 !important;
169
- padding: 0 !important;
170
- background: white !important;
171
- color-scheme: light !important;
172
- }
173
- }
174
-
175
- /* Screen: also apply isolation for print preview */
176
- @media screen {
177
- /* When this stylesheet is active, we're about to print */
178
- /* No screen-specific rules needed - isolation only applies to print */
179
- }
180
- `,t}async function Bi(r,e={}){const{orientation:t="landscape"}=e,i=r.id;document.querySelectorAll(`#${CSS.escape(i)}`).length>1&&console.warn(`[tbw-grid:print] Multiple elements found with id="${i}". Print isolation may not work correctly. Ensure each grid has a unique ID.`),document.getElementById(ze)?.remove();const o=As(i,t);return document.head.appendChild(o),new Promise(s=>{const l=()=>{window.removeEventListener("afterprint",l),document.getElementById(ze)?.remove(),s()};window.addEventListener("afterprint",l),window.print(),setTimeout(()=>{window.removeEventListener("afterprint",l),document.getElementById(ze)?.remove(),s()},5e3)})}const ks=".tbw-print-header,.tbw-print-footer{display:none}@media print{tbw-grid{overflow:visible!important;height:auto!important;border:none!important;border-radius:0!important;color-scheme:light only;-webkit-print-color-adjust:exact;print-color-adjust:exact}tbw-grid .tbw-grid-content{overflow:visible!important;height:auto!important;max-height:none!important}tbw-grid .tbw-scroll-area{overflow:visible!important;height:auto!important;max-height:none!important}tbw-grid .rows-body{overflow:visible!important;height:auto!important;max-height:none!important}tbw-grid .rows-container,tbw-grid .rows-viewport,tbw-grid .rows{overflow:visible!important;height:auto!important;max-height:none!important;transform:none!important}tbw-grid .rows-viewport .rows{position:static!important}tbw-grid .resize-handle,tbw-grid [part=sort-indicator],tbw-grid .tbw-filter-btn,tbw-grid .tool-panel,tbw-grid .tool-panel-content,tbw-grid .tbw-shell-header,tbw-grid .shell-toolbar,tbw-grid .tool-panel-toggle,tbw-grid [data-print-hide],tbw-grid .expander-cell,tbw-grid .tree-toggle,tbw-grid .context-menu,tbw-grid .faux-vscroll{display:none!important}tbw-grid .tbw-print-header{display:flex;justify-content:space-between;align-items:baseline;padding:var(--tbw-spacing-md, .5em) 0;margin-bottom:var(--tbw-spacing-md, .5em);border-bottom:2px solid var(--tbw-print-border, var(--tbw-color-border-strong));font-family:inherit}.tbw-print-header-title{font-size:1.25em;font-weight:700}.tbw-print-header-timestamp{font-size:var(--tbw-font-size-sm, .875em);color:var(--tbw-print-muted, var(--tbw-color-fg-muted))}tbw-grid .tbw-print-footer{display:block;margin-top:var(--tbw-spacing-md, .5em);padding-top:var(--tbw-spacing-md, .5em);border-top:1px solid var(--tbw-print-border, var(--tbw-color-border));font-size:var(--tbw-font-size-xs, .75em);color:var(--tbw-print-muted, var(--tbw-color-fg-muted));text-align:end}tbw-grid .data-grid-row{break-inside:avoid;page-break-inside:avoid}tbw-grid .cell{border:1px solid var(--tbw-print-cell-border, var(--tbw-color-border))!important}tbw-grid .header-row,tbw-grid .data-grid-row{padding-inline-end:1px}tbw-grid .data-grid-row:hover,tbw-grid .cell:hover{background:inherit!important}@page{margin:1cm}@page{tbw-grid.print-landscape{size:landscape}}@page{tbw-grid.print-portrait{size:portrait}}}",Ts={button:!1,orientation:"landscape",warnThreshold:500,maxRows:0,includeTitle:!0,includeTimestamp:!0,title:"",isolate:!1};class Ls extends M{name="print";version="1.0.0";styles=ks;#t=!1;#e=null;#u=null;#c=null;#r=null;#l=null;#i=null;get#h(){return this.grid}isPrinting(){return this.#t}async print(e){if(this.#t){console.warn("[PrintPlugin] Print already in progress");return}const t=this.gridElement;if(!t){console.warn("[PrintPlugin] Grid not available");return}const i={...Ts,...this.config,...e},o=this.rows.length;let s=o,l=!1;if(i.warnThreshold>0&&o>i.warnThreshold){const c=i.maxRows>0?`
181
-
182
- Note: Output will be limited to ${i.maxRows.toLocaleString()} rows.`:"";if(!confirm(`This grid has ${o.toLocaleString()} rows. Printing large datasets may cause performance issues or browser slowdowns.${c}
183
-
184
- Click OK to continue, or Cancel to abort.`))return}i.maxRows>0&&o>i.maxRows&&(s=i.maxRows,l=!0),this.#t=!0;const a=performance.now();this.emit("print-start",{rowCount:s,limitApplied:l,originalRowCount:o});try{const c=this.#h;this.#u={bypassThreshold:c._virtualization?.bypassThreshold??24},this.#a(),l&&(this.#c=this.sourceRows,this.grid.rows=this.sourceRows.slice(0,s),await new Promise(d=>setTimeout(d,50))),(i.includeTitle||i.includeTimestamp)&&this.#w(i),await this.#y(),await new Promise(d=>requestAnimationFrame(d)),await new Promise(d=>requestAnimationFrame(d)),t.classList.add(`print-${i.orientation}`),await new Promise(d=>requestAnimationFrame(d)),await new Promise(d=>requestAnimationFrame(d)),i.isolate?await this.#g(i):await this.#d(),this.emit("print-complete",{success:!0,rowCount:s,duration:Math.round(performance.now()-a)})}catch(c){console.error("[PrintPlugin] Print failed:",c),this.emit("print-complete",{success:!1,rowCount:0,duration:Math.round(performance.now()-a)})}finally{this.#C(),this.#t=!1}}#w(e){const t=this.gridElement;if(t){if(this.#r=document.createElement("div"),this.#r.className="tbw-print-header",e.includeTitle){const i=e.title||this.grid.effectiveConfig?.shell?.header?.title||"Grid Data",n=document.createElement("div");n.className="tbw-print-header-title",n.textContent=i,this.#r.appendChild(n)}if(e.includeTimestamp){const i=document.createElement("div");i.className="tbw-print-header-timestamp",i.textContent=`Printed: ${new Date().toLocaleString()}`,this.#r.appendChild(i)}t.insertBefore(this.#r,t.firstChild),this.#l=document.createElement("div"),this.#l.className="tbw-print-footer",this.#l.textContent=`Page generated from ${window.location.hostname}`,t.appendChild(this.#l)}}async#y(){const e=this.#h;if(!e._virtualization)return;const t=this.rows.length;e._virtualization.bypassThreshold=t+100,e.refreshVirtualWindow(!0),await new Promise(i=>setTimeout(i,100))}async#d(){return new Promise(e=>{const t=()=>{window.removeEventListener("afterprint",t),e()};window.addEventListener("afterprint",t),window.print(),setTimeout(()=>{typeof window<"u"&&window.removeEventListener("afterprint",t),e()},1e3)})}async#g(e){const t=this.gridElement;t&&await Bi(t,{orientation:e.orientation})}#a(){const e=this.columns;if(e){this.#e=new Map;for(const t of e)t.printHidden&&t.field&&(this.#e.set(t.field,!t.hidden),this.grid.setColumnVisible(t.field,!1))}}#f(){if(this.#e){for(const[e,t]of this.#e)this.grid.setColumnVisible(e,t);this.#e=null}}#C(){const e=this.gridElement;if(!e)return;this.#f(),e.classList.remove("print-portrait","print-landscape"),this.#i!==null&&(e.style.transform="",e.style.transformOrigin="",e.style.width="",this.#i=null),this.#r&&(this.#r.remove(),this.#r=null),this.#l&&(this.#l.remove(),this.#l=null);const t=this.#h;this.#u&&t._virtualization&&(t._virtualization.bypassThreshold=this.#u.bypassThreshold,t.refreshVirtualWindow(!0),this.#u=null),this.#c!==null&&(this.grid.rows=this.#c,this.#c=null)}afterRender(){this.config?.button&&!this.#p&&(this.#R(),this.#p=!0)}#p=!1;#R(){this.#h.registerToolbarContent?.({id:"print-button",order:900,render:t=>{const i=document.createElement("button");i.className="tbw-toolbar-btn tbw-print-btn",i.title="Print grid",i.type="button";const n=this.resolveIcon("print")||"🖨️";this.setIcon(i,n),i.addEventListener("click",()=>{this.print()},{signal:this.disconnectSignal}),t.appendChild(i)}})}}function Ps(r){const e=r.meta??{};return e.lockPosition!==!0&&e.suppressMovable!==!0}function $i(r,e,t){if(e===t||e<0||e>=r.length||t<0||t>r.length)return r;const i=[...r],[n]=i.splice(e,1);return i.splice(t,0,n),i}const Hs='@layer tbw-plugins{.header-row>.cell[draggable=true]{cursor:grab;position:relative}.header-row>.cell.dragging{opacity:.5;cursor:grabbing}.header-row>.cell.drop-before:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.header-row>.cell.drop-after:after{content:"";position:absolute;right:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.cell.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}@keyframes reorder-fade-in{0%{opacity:0}to{opacity:1}}.cell.fade-animating{animation:reorder-fade-in var(--tbw-animation-duration, .2s) ease-out backwards}}';class Is extends M{name="reorder";styles=Hs;get defaultConfig(){return{animation:"flip"}}get animationType(){return this.isAnimationEnabled?this.config.animation!==void 0?this.config.animation:"flip":!1}get animationDuration(){return this.config.animationDuration!==void 0?this.config.animationDuration:super.animationDuration}isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;canMoveColumnWithPlugins(e){return!e||!Ps(e)?!1:!this.grid.query("canMoveColumn",e).includes(!1)}clearDragClasses(){this.gridElement?.querySelectorAll(".header-row > .cell").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-reorder-request",t=>{const i=t.detail;i?.field&&typeof i.toIndex=="number"&&this.moveColumn(i.field,i.toIndex)},{signal:this.disconnectSignal})}detach(){this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}afterRender(){const e=this.gridElement;if(!e)return;e.querySelectorAll(".header-row > .cell").forEach(i=>{const n=i,o=n.getAttribute("data-field");if(!o)return;const s=this.columns.find(l=>l.field===o);if(!this.canMoveColumnWithPlugins(s)){n.draggable=!1;return}n.draggable=!0,!n.getAttribute("data-dragstart-bound")&&(n.setAttribute("data-dragstart-bound","true"),n.addEventListener("dragstart",l=>{const c=this.getColumnOrder().indexOf(o);this.isDragging=!0,this.draggedField=o,this.draggedIndex=c,l.dataTransfer&&(l.dataTransfer.effectAllowed="move",l.dataTransfer.setData("text/plain",o)),n.classList.add("dragging")}),n.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses()}),n.addEventListener("dragover",l=>{if(l.preventDefault(),!this.isDragging||this.draggedField===o)return;const a=n.getBoundingClientRect(),c=a.left+a.width/2,u=this.getColumnOrder().indexOf(o);this.dropIndex=l.clientX<c?u:u+1,n.classList.add("drop-target"),n.classList.toggle("drop-before",l.clientX<c),n.classList.toggle("drop-after",l.clientX>=c)}),n.addEventListener("dragleave",()=>{n.classList.remove("drop-target","drop-before","drop-after")}),n.addEventListener("drop",l=>{l.preventDefault();const a=this.draggedField,c=this.draggedIndex,d=this.dropIndex;if(!this.isDragging||a===null||c===null||d===null)return;const u=d>c?d-1:d,h=this.getColumnOrder(),p=$i(h,c,u),g={field:a,fromIndex:c,toIndex:u,columnOrder:p};this.emitCancelable("column-move",g)||this.updateColumnOrder(p)}))})}onKeyDown(e){if(!e.altKey||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const t=this.grid,i=t._focusCol,n=t._visibleColumns;if(i<0||i>=n.length)return;const o=n[i];if(!this.canMoveColumnWithPlugins(o))return;const s=this.getColumnOrder(),l=s.indexOf(o.field);if(l===-1)return;const a=e.key==="ArrowLeft"?l-1:l+1;if(a<0||a>=s.length)return;const c=n.find(d=>d.field===s[a]);if(this.canMoveColumnWithPlugins(c))return this.moveColumn(o.field,a),t._focusCol=a,N(this.grid),e.preventDefault(),e.stopPropagation(),!0}getColumnOrder(){return this.grid.getColumnOrder()}moveColumn(e,t){const i=this.getColumnOrder(),n=i.indexOf(e);if(n===-1)return;const o=$i(i,n,t);this.emitCancelable("column-move",{field:e,fromIndex:n,toIndex:t,columnOrder:o})||this.updateColumnOrder(o)}setColumnOrder(e){this.updateColumnOrder(e)}resetColumnOrder(){const e=this.columns.map(t=>t.field);this.updateColumnOrder(e)}captureHeaderPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const i=t.getAttribute("data-field");i&&e.set(i,t.getBoundingClientRect().left)}),e}animateFLIP(e){const t=this.gridElement;if(!t||e.size===0)return;const i=new Map;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(s=>{const l=s.getAttribute("data-field");if(!l)return;const a=e.get(l);if(a===void 0)return;const c=a-s.getBoundingClientRect().left;Math.abs(c)>1&&i.set(l,c)}),i.size===0)return;const n=[];if(t.querySelectorAll(".cell[data-field]").forEach(s=>{const l=i.get(s.getAttribute("data-field")??"");if(l!==void 0){const a=s;a.style.transform=`translateX(${l}px)`,n.push(a)}}),n.length===0)return;this.gridElement.offsetHeight;const o=this.animationDuration;requestAnimationFrame(()=>{n.forEach(s=>{s.classList.add("flip-animating"),s.style.transform=""}),setTimeout(()=>{n.forEach(s=>{s.style.transform="",s.classList.remove("flip-animating")})},o+50)})}animateFade(e){const t=this.gridElement;if(!t){e();return}const i=this.captureHeaderPositions();e();const n=new Set;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(l=>{const a=l.getAttribute("data-field");if(!a)return;const c=i.get(a);if(c===void 0)return;const d=l.getBoundingClientRect().left;Math.abs(c-d)>1&&n.add(a)}),n.size===0)return;const o=[];if(t.querySelectorAll(".cell[data-field]").forEach(l=>{const a=l.getAttribute("data-field");if(a&&n.has(a)){const c=l;c.classList.add("fade-animating"),o.push(c)}}),o.length===0)return;const s=this.animationDuration;setTimeout(()=>{o.forEach(l=>l.classList.remove("fade-animating"))},s+50)}updateColumnOrder(e){const t=this.animationType;if(t==="flip"&&this.gridElement){const i=this.captureHeaderPositions();this.grid.setColumnOrder(e),requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(i)})}else t==="fade"?this.animateFade(()=>this.grid.setColumnOrder(e)):this.grid.setColumnOrder(e);this.grid.requestStateChange?.()}}const Ds='tbw-grid[data-responsive-animate] .data-grid-row,tbw-grid[data-responsive-animate] .data-grid-row>.cell{transition:opacity var(--tbw-responsive-duration, .2s) ease-out,transform var(--tbw-responsive-duration, .2s) ease-out}tbw-grid[data-responsive][data-responsive-animate] .data-grid-row{animation:responsive-card-enter var(--tbw-responsive-duration, .2s) ease-out}@keyframes responsive-card-enter{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}tbw-grid[data-responsive] .header{display:none!important}tbw-grid[data-responsive] .footer-row{display:none}tbw-grid[data-responsive] .tbw-scroll-area{overflow-x:hidden;min-width:0!important}tbw-grid[data-responsive] .rows-body-wrapper{min-width:0!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row){display:block!important;grid-template-columns:none!important;padding:var(--tbw-cell-padding);padding-inline-start:var(--tbw-spacing-xl);border-bottom:1px solid var(--tbw-color-border);min-height:auto!important;height:auto!important;contain:none!important;content-visibility:visible!important;background:var(--tbw-color-bg);position:relative}tbw-grid[data-responsive] .data-grid-row:not(.group-row):nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid[data-responsive] .data-grid-row:not(.group-row):hover{background:var(--tbw-color-row-hover)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]{background:var(--tbw-color-selection)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]:before{content:"";position:absolute;inset-inline-start:0;top:0;bottom:0;width:4px;background:var(--tbw-color-accent)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell{display:flex!important;justify-content:space-between;align-items:center;padding:var(--tbw-spacing-xs) var(--tbw-spacing-md);width:100%!important;min-width:0!important;min-height:auto!important;height:auto!important;line-height:1.5!important;position:static!important;left:auto!important;right:auto!important;border:none!important;border-bottom:none!important;border-inline-end:none!important;background:transparent!important;white-space:normal!important;overflow:visible!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:before{content:attr(data-header) ": ";font-weight:600;color:var(--tbw-color-header-fg);flex-shrink:0;margin-inline-end:var(--tbw-spacing-md);min-width:100px}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:after{content:none}tbw-grid[data-responsive] .cell[data-utility]{display:none!important}tbw-grid[data-responsive] .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .cell[data-responsive-value-only]:before{display:none!important}tbw-grid:not([data-responsive]) .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .tbw-footer,tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows{display:none!important}tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows,tbw-grid[data-responsive] .tbw-aggregation-row{min-width:0!important}tbw-grid[data-responsive] .data-grid-row.responsive-card{display:block!important;padding:var(--tbw-cell-padding);border-bottom:1px solid var(--tbw-color-border)}tbw-grid[data-responsive] .data-grid-row.responsive-card>*{width:100%}tbw-grid[data-responsive] .data-grid-row.responsive-card .cell:before{display:none}';class Ms extends M{name="responsive";version="1.0.0";styles=Ds;static manifest={incompatibleWith:[{name:"groupingRows",reason:"Responsive card layout does not yet support row grouping. The variable row heights (cards vs group headers) cause scroll calculation issues."}],queries:[{type:"isCardMode",description:"Returns whether the grid is currently in responsive card mode"}]};#t;#e=!1;#u;#c=!1;#r=0;#l=new Set;#i=new Set;#h=null;#w=[];isResponsive(){return this.#e}setResponsive(e){e!==this.#e&&(this.#e=e,this.#C(),this.emit("responsive-change",{isResponsive:e,width:this.#r,breakpoint:this.config.breakpoint??0}))}setBreakpoint(e){this.config.breakpoint=e,this.#g(this.#r)}setCardRenderer(e){this.config.cardRenderer=e,this.#e&&this.requestRender()}getWidth(){return this.#r}getActiveBreakpoint(){return this.#h}attach(e){super.attach(e),this.#y(),this.#d(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#w=[...this.config.breakpoints].sort((t,i)=>i.maxWidth-t.maxWidth)),this.#t=new ResizeObserver(t=>{const i=t[0]?.contentRect.width??0;this.#r=i,clearTimeout(this.#u),this.#u=setTimeout(()=>{this.#g(i)},this.config.debounceMs??100)}),this.#t.observe(this.gridElement)}#y(){const e=this.grid;if(!e||typeof e.querySelector!="function")return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const i=e;if(i.__frameworkAdapter?.parseResponsiveCardElement){const u=i.__frameworkAdapter.parseResponsiveCardElement(t);u&&(this.config={...this.config,cardRenderer:u})}const n=t.getAttribute("breakpoint"),o=t.getAttribute("card-row-height"),s=t.getAttribute("hidden-columns"),l=t.getAttribute("hide-header"),a=t.getAttribute("debounce-ms"),c={};if(n!==null){const u=parseInt(n,10);isNaN(u)||(c.breakpoint=u)}if(o!==null&&(c.cardRowHeight=o==="auto"?"auto":parseInt(o,10)),s!==null&&(c.hiddenColumns=s.split(",").map(u=>u.trim()).filter(u=>u.length>0)),l!==null&&(c.hideHeader=l!=="false"),a!==null){const u=parseInt(a,10);isNaN(u)||(c.debounceMs=u)}const d=t.innerHTML.trim();d&&!this.config.cardRenderer&&!i.__frameworkAdapter?.parseResponsiveCardElement&&(c.cardRenderer=u=>{const h=fe(d,{value:u,row:u}),p=U(h),g=document.createElement("div");return g.className="tbw-responsive-card-content",g.innerHTML=p,g}),Object.keys(c).length>0&&(this.config={...this.config,...c})}#d(e){if(this.#l.clear(),this.#i.clear(),!!e)for(const t of e)typeof t=="string"?this.#l.add(t):t.showValue?this.#i.add(t.field):this.#l.add(t.field)}detach(){this.#t?.disconnect(),this.#t=void 0,clearTimeout(this.#u),this.#u=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if(e.type==="isCardMode")return this.#e}afterRender(){if(this.#S(),!(this.#w.length>0?this.#h!==null:this.#e))return;const t=this.#l.size>0,i=this.#i.size>0;if(!t&&!i)return;const n=this.gridElement.querySelectorAll(".cell[data-field]");for(const o of n){const s=o.getAttribute("data-field");s&&(this.#l.has(s)?(o.setAttribute("data-responsive-hidden",""),o.removeAttribute("data-responsive-value-only")):this.#i.has(s)?(o.setAttribute("data-responsive-value-only",""),o.removeAttribute("data-responsive-hidden")):(o.removeAttribute("data-responsive-hidden"),o.removeAttribute("data-responsive-value-only")))}}#g(e){if(this.#w.length>0){this.#a(e);return}const t=this.config.breakpoint??0;t===0&&!this.#c&&(this.#c=!0,console.warn("[tbw-grid:ResponsivePlugin] No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count."));const i=t>0&&e<t;i!==this.#e&&(this.#e=i,this.#C(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#a(e){let t=null;for(const n of this.#w)e<=n.maxWidth&&(t=n);if(t!==this.#h){this.#h=t,t?.hiddenColumns?this.#d(t.hiddenColumns):this.#d(this.config.hiddenColumns);const n=t?.cardLayout===!0;n!==this.#e&&(this.#e=n,this.#C()),this.emit("responsive-change",{isResponsive:this.#e,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#f;#C(){this.gridElement.toggleAttribute("data-responsive",this.#e);const e=this.config.animate!==!1;this.gridElement.toggleAttribute("data-responsive-animate",e),this.config.animationDuration&&this.gridElement.style.setProperty("--tbw-responsive-duration",`${this.config.animationDuration}ms`);const t=this.grid;if(this.#e){t._virtualization&&(this.#f=t._virtualization.rowHeight);const i=this.gridElement.querySelector(".tbw-scroll-area");i&&(i.scrollLeft=0)}else{const i=this.gridElement.querySelectorAll(".data-grid-row");for(const n of i)n.style.height="",n.classList.remove("responsive-card");this.#f&&this.#f>0&&t._virtualization&&(t._virtualization.rowHeight=this.#f,this.#f=void 0),this.#p=void 0,this.#R=void 0,this.#_=void 0}}renderRow(e,t,i){if(!this.#e||!this.config.cardRenderer||e.__isGroupRow)return;t.replaceChildren();const n=this.config.cardRenderer(e,i);t.className="data-grid-row responsive-card";const o=this.config.cardRowHeight??"auto";return o!=="auto"?t.style.height=`${o}px`:t.style.height="auto",t.appendChild(n),!0}onKeyDown(e){if(!this.#e||this.config.cardRenderer&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return!1;const t=this.rows.length-1,i=this.visibleColumns.length-1;switch(e.key){case"ArrowDown":if(this.grid._focusCol<i)return this.grid._focusCol+=1,e.preventDefault(),N(this.grid),!0;if(this.grid._focusRow<t)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),N(this.grid),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),N(this.grid),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=i,e.preventDefault(),N(this.grid),!0;break;case"ArrowRight":if(this.grid._focusRow<t)return this.grid._focusRow+=1,e.preventDefault(),N(this.grid),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),N(this.grid),!0;break}return!1}#p;#R;#_;#x(){if(this.#p&&this.#p>0)return this.#p;const e=this.config.cardRowHeight;return typeof e=="number"&&e>0?e:80}#E(){return this.#R&&this.#R>0?this.#R:this.#f??28}#v(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}#m(){let e=0,t=0;for(const i of this.rows)i.__isGroupRow?e++:t++;return{groupCount:e,cardCount:t}}getExtraHeight(){if(!this.#e||!this.config.cardRenderer||!this.#v())return 0;const e=this.#f??28,t=this.#E(),i=this.#x(),{groupCount:n,cardCount:o}=this.#m(),s=n*Math.max(0,t-e),l=o*Math.max(0,i-e);return s+l}getExtraHeightBefore(e){if(!this.#e||!this.config.cardRenderer||!this.#v())return 0;const t=this.#f??28,i=this.#E(),n=this.#x(),o=Math.max(0,i-t),s=Math.max(0,n-t);let l=0,a=0;const c=this.rows,d=Math.min(e,c.length);for(let u=0;u<d;u++)c[u].__isGroupRow?l++:a++;return l*o+a*s}getRowHeight(e,t){if(!(!this.#e||!this.config.cardRenderer))return e.__isGroupRow?this.#E():this.#x()}#A(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#n=!1;#S(){if(!this.#e||!this.config.cardRenderer)return;let e=!1;const t=this.grid,i=this.#v(),n=this.#A();if(n!==this.#_&&(this.#_=n,e=!0),i){const s=this.gridElement.querySelector(".data-grid-row.group-row");if(s){const l=s.getBoundingClientRect().height;l>0&&l!==this.#R&&(this.#R=l,e=!0)}}const o=this.gridElement.querySelector(".data-grid-row.responsive-card");if(o){const s=o.getBoundingClientRect().height;s>0&&s!==this.#p&&(this.#p=s,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=s))}e&&!this.#n&&(this.#n=!0,queueMicrotask(()=>{this.#n=!1,this.grid&&this.#e&&this.grid.refreshVirtualWindow?.(!0,!0)}))}}const zs='@layer tbw-plugins{[data-field=__tbw_row_drag]{display:flex;align-items:center;justify-content:center}.dg-row-drag-handle{display:flex;align-items:center;justify-content:center;min-width:1em;min-height:1em;cursor:grab;-webkit-user-select:none;user-select:none;color:var(--tbw-row-reorder-handle-color, var(--tbw-color-fg-muted));transition:color var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease);font-size:var(--tbw-font-size, 1em);letter-spacing:-2px}.dg-row-drag-handle:hover{color:var(--tbw-row-reorder-handle-hover, var(--tbw-color-fg))}.dg-row-drag-handle:active{cursor:grabbing}.data-grid-row.dragging{opacity:.6}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before{content:"";position:absolute;top:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.drop-target.drop-after:after{content:"";position:absolute;bottom:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.keyboard-moving{background-color:var(--tbw-row-reorder-moving-bg, var(--tbw-focus-background));box-shadow:0 0 0 1px var(--tbw-row-reorder-moving-border, var(--tbw-color-accent)) inset}.data-grid-row.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}}',Wi="__tbw_row_drag";class Os extends M{name="rowReorder";styles=zs;get defaultConfig(){return{enableKeyboard:!0,showDragHandle:!0,dragHandlePosition:"left",dragHandleWidth:40,debounceMs:150,animation:"flip"}}get animationType(){return this.isAnimationEnabled?this.config.animation!==void 0?this.config.animation:"flip":!1}isDragging=!1;draggedRowIndex=null;dropRowIndex=null;pendingMove=null;debounceTimer=null;lastFocusCol=0;detach(){this.clearDebounceTimer(),this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.pendingMove=null}processColumns(e){if(!this.config.showDragHandle)return[...e];const t={field:Wi,header:"",width:this.config.dragHandleWidth??40,resizable:!1,sortable:!1,filterable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0},viewRenderer:()=>{const i=document.createElement("div");return i.className="dg-row-drag-handle",i.setAttribute("aria-label","Drag to reorder"),i.setAttribute("role","button"),i.setAttribute("tabindex","-1"),i.draggable=!0,this.setIcon(i,this.resolveIcon("dragHandle")),i}};return this.config.dragHandlePosition==="right"?[...e,t]:[t,...e]}afterRender(){if(!this.config.showDragHandle)return;const e=this.gridElement;if(!e)return;e.querySelectorAll(".dg-row-drag-handle").forEach(n=>{const o=n;if(o.getAttribute("data-drag-bound"))return;o.setAttribute("data-drag-bound","true");const s=o.closest(".data-grid-row");s&&this.setupHandleDragListeners(o,s)}),e.querySelectorAll(".data-grid-row").forEach(n=>{const o=n;o.getAttribute("data-drop-bound")||(o.setAttribute("data-drop-bound","true"),this.setupRowDropListeners(o))})}onKeyDown(e){if(!this.config.enableKeyboard||!e.ctrlKey||e.key!=="ArrowUp"&&e.key!=="ArrowDown")return;const t=this.grid,i=t._focusRow,n=t._rows??this.sourceRows;if(i<0||i>=n.length)return;const o=e.key==="ArrowUp"?"up":"down",s=o==="up"?i-1:i+1;if(s<0||s>=n.length)return;const l=n[i];if(!(this.config.canMove&&!this.config.canMove(l,i,s,o)))return this.handleKeyboardMove(l,i,s,o,t._focusCol),e.preventDefault(),e.stopPropagation(),!0}onCellClick(){this.flushPendingMove()}moveRow(e,t){const i=[...this.sourceRows];if(e<0||e>=i.length||t<0||t>=i.length||e===t)return;const n=t<e?"up":"down",o=i[e];this.config.canMove&&!this.config.canMove(o,e,t,n)||this.executeMove(o,e,t,"keyboard")}canMoveRow(e,t){const i=this.sourceRows;if(e<0||e>=i.length||t<0||t>=i.length||e===t)return!1;if(!this.config.canMove)return!0;const n=t<e?"up":"down";return this.config.canMove(i[e],e,t,n)}setupHandleDragListeners(e,t){e.addEventListener("dragstart",i=>{const n=this.getRowIndex(t);n<0||(this.isDragging=!0,this.draggedRowIndex=n,i.dataTransfer&&(i.dataTransfer.effectAllowed="move",i.dataTransfer.setData("text/plain",String(n))),t.classList.add("dragging"))}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.clearDragClasses()})}setupRowDropListeners(e){e.addEventListener("dragover",t=>{if(t.preventDefault(),!this.isDragging||this.draggedRowIndex===null)return;const i=this.getRowIndex(e);if(i<0||i===this.draggedRowIndex)return;const n=e.getBoundingClientRect(),o=n.top+n.height/2,s=t.clientY<o;this.dropRowIndex=s?i:i+1,e.classList.add("drop-target"),e.classList.toggle("drop-before",s),e.classList.toggle("drop-after",!s)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",t=>{t.preventDefault();const i=this.draggedRowIndex;let n=this.dropRowIndex;if(!(!this.isDragging||i===null||n===null)&&(n>i&&n--,i!==n)){const s=this.sourceRows[i],l=n<i?"up":"down";(!this.config.canMove||this.config.canMove(s,i,n,l))&&this.executeMove(s,i,n,"drag")}})}handleKeyboardMove(e,t,i,n,o){this.pendingMove?this.pendingMove.currentIndex=i:this.pendingMove={originalIndex:t,currentIndex:i,row:e},this.lastFocusCol=o;const s=this.grid,l=[...s._rows??this.sourceRows],[a]=l.splice(t,1);l.splice(i,0,a),s._rows=l,s._focusRow=i,s._focusCol=o,s.refreshVirtualWindow(!0),N(s),this.clearDebounceTimer(),this.debounceTimer=setTimeout(()=>{this.flushPendingMove()},this.config.debounceMs??300)}flushPendingMove(){if(this.clearDebounceTimer(),!this.pendingMove)return;const{originalIndex:e,currentIndex:t,row:i}=this.pendingMove;if(this.pendingMove=null,e===t)return;const n={row:i,fromIndex:e,toIndex:t,rows:[...this.sourceRows],source:"keyboard"};if(this.emitCancelable("row-move",n)){const s=[...this.sourceRows],[l]=s.splice(t,1);s.splice(e,0,l);const a=this.grid;a._rows=s,a._focusRow=e,a._focusCol=this.lastFocusCol,a.refreshVirtualWindow(!0),N(a)}}executeMove(e,t,i,n){const o=[...this.sourceRows],[s]=o.splice(t,1);o.splice(i,0,s);const l={row:e,fromIndex:t,toIndex:i,rows:o,source:n};if(!this.emitCancelable("row-move",l))if(this.animationType==="flip"&&this.gridElement){const c=this.captureRowPositions();this.grid.rows=o,requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(c,t,i)})}else this.grid.rows=o}captureRowPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".data-grid-row").forEach(t=>{const i=this.getRowIndex(t);i>=0&&e.set(i,t.getBoundingClientRect().top)}),e}animateFLIP(e,t,i){const n=this.gridElement;if(!n||e.size===0)return;const o=Math.min(t,i),s=Math.max(t,i),l=[];if(n.querySelectorAll(".data-grid-row").forEach(c=>{const d=c,u=this.getRowIndex(d);if(u<0||u<o||u>s)return;let h;u===i?h=t:t<i?h=u+1:h=u-1;const p=e.get(h);if(p===void 0)return;const g=d.getBoundingClientRect().top,f=p-g;Math.abs(f)>1&&l.push({el:d,deltaY:f})}),l.length===0)return;l.forEach(({el:c,deltaY:d})=>{c.style.transform=`translateY(${d}px)`}),n.offsetHeight;const a=this.animationDuration;requestAnimationFrame(()=>{l.forEach(({el:c})=>{c.classList.add("flip-animating"),c.style.transform=""}),setTimeout(()=>{l.forEach(({el:c})=>{c.style.transform="",c.classList.remove("flip-animating")})},a+50)})}getRowIndex(e){const t=e.querySelector(".cell[data-row]");return t?parseInt(t.getAttribute("data-row")??"-1",10):-1}clearDragClasses(){this.gridElement?.querySelectorAll(".data-grid-row").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}function ce(r){return{startRow:Math.min(r.startRow,r.endRow),startCol:Math.min(r.startCol,r.endCol),endRow:Math.max(r.startRow,r.endRow),endCol:Math.max(r.startCol,r.endCol)}}function Fs(r){const e=ce(r);return{from:{row:e.startRow,col:e.startCol},to:{row:e.endRow,col:e.endCol}}}function Ki(r){return r.map(Fs)}function Ns(r,e,t){const i=ce(t);return r>=i.startRow&&r<=i.endRow&&e>=i.startCol&&e<=i.endCol}function qs(r,e,t){return t.some(i=>Ns(r,e,i))}function Gs(r){const e=[],t=ce(r);for(let i=t.startRow;i<=t.endRow;i++)for(let n=t.startCol;n<=t.endCol;n++)e.push({row:i,col:n});return e}function Bs(r){const e=new Map;for(const t of r)for(const i of Gs(t))e.set(`${i.row},${i.col}`,i);return[...e.values()]}function vt(r,e){return{startRow:r.row,startCol:r.col,endRow:e.row,endCol:e.col}}function Oe(r,e){const t=ce(r),i=ce(e);return t.startRow===i.startRow&&t.startCol===i.startCol&&t.endRow===i.endRow&&t.endCol===i.endCol}const $s='@layer tbw-plugins{tbw-grid.selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}tbw-grid:has(.selection){-webkit-user-select:none;user-select:none}tbw-grid .data-grid-row.row-focus{background-color:var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%));outline:none;position:relative}tbw-grid .data-grid-row.row-focus:after{content:"";position:absolute;inset:0;pointer-events:none;border-width:0;border-style:var(--tbw-selection-border-style, var(--tbw-border-style));border-color:var(--tbw-range-border-color, var(--tbw-color-accent));border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width));border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width));z-index:1}tbw-grid .data-grid-row.row-focus+.data-grid-row.row-focus:after{border-top-width:0}tbw-grid .data-grid-row.row-focus:has(+.data-grid-row.row-focus):after{border-bottom-width:0}tbw-grid[data-selection-mode=row] .cell-focus,tbw-grid[data-selection-mode=row] .row-focus,tbw-grid[data-selection-mode=range] .cell-focus{outline:none}tbw-grid .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg);position:relative}tbw-grid .data-grid-row>.cell.selected:after{content:"";position:absolute;inset:0;pointer-events:none;border:0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1}tbw-grid .data-grid-row>.cell.selected.top:after{border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.bottom:after{border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.first:after{border-left-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.last:after{border-right-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row[data-selectable=false].row-focus{background-color:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row>.cell[data-selectable=false].selected{background-color:var(--tbw-selection-warning-bg, rgba(from var(--tbw-color-error) r g b / 50%))}tbw-grid .tbw-selection-summary{font-size:var(--tbw-font-size-sm, .8125rem);color:var(--tbw-color-fg-muted);white-space:nowrap}tbw-grid .data-grid-row>.cell[data-field=__tbw_checkbox],tbw-grid .header-row>.cell[data-field=__tbw_checkbox]{text-align:center;cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .tbw-select-row-checkbox{pointer-events:none;margin:0;cursor:pointer}tbw-grid .tbw-checkbox-header{display:flex;justify-content:center;align-items:center;height:100%}tbw-grid .tbw-select-all-checkbox{margin:0;cursor:pointer}}',Vi="__tbw_checkbox";function Ws(r,e,t){if(r==="cell"&&e.selectedCell)return{mode:r,ranges:[{from:{row:e.selectedCell.row,col:e.selectedCell.col},to:{row:e.selectedCell.row,col:e.selectedCell.col}}]};if(r==="row"&&e.selected.size>0){const i=[...e.selected].sort((l,a)=>l-a),n=[];let o=i[0],s=o;for(let l=1;l<i.length;l++)i[l]===s+1?s=i[l]:(n.push({from:{row:o,col:0},to:{row:s,col:t-1}}),o=i[l],s=o);return n.push({from:{row:o,col:0},to:{row:s,col:t-1}}),{mode:r,ranges:n}}return r==="range"&&e.ranges.length>0?{mode:r,ranges:Ki(e.ranges)}:{mode:r,ranges:[]}}class Ks extends M{static manifest={queries:[{type:"getSelection",description:"Get the current selection state"},{type:"selectRows",description:"Select specific rows by index (row mode only)"},{type:"getSelectedRowIndices",description:"Get sorted array of selected row indices"},{type:"getSelectedRows",description:"Get actual row objects for the current selection (works in all modes)"}],configRules:[{id:"selection/range-dblclick",severity:"warn",message:`"triggerOn: 'dblclick'" has no effect when mode is "range".
185
- → Range selection uses drag interaction (mousedown → mousemove), not click events.
186
- → The "triggerOn" option only affects "cell" and "row" selection modes.`,check:e=>e.mode==="range"&&e.triggerOn==="dblclick"}]};name="selection";styles=$s;get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0}}selected=new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;selectedCell=null;lastSyncedFocusRow=-1;lastSyncedFocusCol=-1;explicitSelection=!1;isSelectionEnabled(){return this.config.enabled===!1?!1:this.grid.effectiveConfig?.selectable!==!1}checkSelectable(e,t){const{isSelectable:i}=this.config;if(!i)return!0;const n=this.rows[e];if(!n)return!1;const o=t!==void 0?this.visibleColumns[t]:void 0;return i(n,e,o,t)}isRowSelectable(e){return this.checkSelectable(e)}isCellSelectable(e,t){return this.checkSelectable(e,t)}attach(e){super.attach(e),this.on("filter-applied",()=>this.clearSelectionSilent()),this.on("grouping-state-change",()=>this.clearSelectionSilent()),this.on("tree-state-change",()=>this.clearSelectionSilent())}handleQuery(e){if(e.type==="getSelection")return this.getSelection();if(e.type==="getSelectedRowIndices")return this.getSelectedRowIndices();if(e.type==="getSelectedRows")return this.getSelectedRows();if(e.type==="selectRows")return this.selectRows(e.context),!0}detach(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.pendingKeyboardUpdate=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1}clearSelectionSilent(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedCell=null,this.lastSelected=null,this.anchor=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,this.requestAfterRender()}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{rowIndex:t,colIndex:i,originalEvent:n}=e,{mode:o,triggerOn:s="click"}=this.config;if(n.type!==s)return!1;const l=e.column,a=l&&ae(l);if(o==="cell"){if(a||!this.isCellSelectable(t,i))return!1;const c=this.selectedCell;return c&&c.row===t&&c.col===i||(this.selectedCell={row:t,col:i},this.emit("selection-change",this.#r()),this.requestAfterRender()),!1}if(o==="row"){if(!this.isRowSelectable(t))return!1;const c=this.config.multiSelect!==!1,d=n.shiftKey&&c,u=(n.ctrlKey||n.metaKey)&&c,h=l?.meta?.checkboxColumn===!0;if(d&&this.anchor!==null){const p=Math.min(this.anchor,t),g=Math.max(this.anchor,t);u||this.selected.clear();for(let f=p;f<=g;f++)this.isRowSelectable(f)&&this.selected.add(f)}else if(u||h&&c)this.selected.has(t)?this.selected.delete(t):this.selected.add(t),this.anchor=t;else{if(this.selected.size===1&&this.selected.has(t))return!1;this.selected.clear(),this.selected.add(t),this.anchor=t}return this.lastSelected=t,this.explicitSelection=!0,this.emit("selection-change",this.#r()),this.requestAfterRender(),!1}if(o==="range"){if(a||!this.isCellSelectable(t,i))return!1;const c=n.shiftKey,d=(n.ctrlKey||n.metaKey)&&this.config.multiSelect!==!1;if(c&&this.cellAnchor){const u=vt(this.cellAnchor,{row:t,col:i}),h=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(h&&Oe(h,u))return!1;d?this.ranges.length>0?this.ranges[this.ranges.length-1]=u:this.ranges.push(u):this.ranges=[u],this.activeRange=u}else if(d){const u={startRow:t,startCol:i,endRow:t,endCol:i};this.ranges.push(u),this.activeRange=u,this.cellAnchor={row:t,col:i}}else{const u={startRow:t,startCol:i,endRow:t,endCol:i};if(this.ranges.length===1&&Oe(this.ranges[0],u))return!1;this.ranges=[u],this.activeRange=u,this.cellAnchor={row:t,col:i}}return this.emit("selection-change",this.#r()),this.requestAfterRender(),!1}return!1}onKeyDown(e){if(!this.isSelectionEnabled())return!1;const{mode:t}=this.config,n=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"].includes(e.key);if(e.key==="Escape")return this.grid.query("isEditing").some(Boolean)?!1:(t==="cell"?this.selectedCell=null:t==="row"?(this.selected.clear(),this.anchor=null):t==="range"&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#r()),this.requestAfterRender(),!0);if(t==="cell"&&n)return queueMicrotask(()=>{const o=this.grid._focusRow,s=this.grid._focusCol;this.isCellSelectable(o,s)?this.selectedCell={row:o,col:s}:this.selectedCell=null,this.emit("selection-change",this.#r()),this.requestAfterRender()}),!1;if(t==="row"){const o=this.config.multiSelect!==!1;if(e.key==="ArrowUp"||e.key==="ArrowDown"){const s=e.shiftKey&&o;return s&&this.anchor===null&&(this.anchor=this.grid._focusRow),queueMicrotask(()=>{const l=this.grid._focusRow;if(s&&this.anchor!==null){this.selected.clear();const a=Math.min(this.anchor,l),c=Math.max(this.anchor,l);for(let d=a;d<=c;d++)this.isRowSelectable(d)&&this.selected.add(d)}else this.isRowSelectable(l)?(this.selected.clear(),this.selected.add(l),this.anchor=l):this.selected.clear();this.lastSelected=l,this.explicitSelection=!0,this.emit("selection-change",this.#r()),this.requestAfterRender()}),!1}if(o&&e.key==="a"&&(e.ctrlKey||e.metaKey))return this.grid.query("isEditing").some(Boolean)?!1:(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}if(t==="range"&&n){const o=e.key==="Tab",s=e.shiftKey&&!o;return s&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:s},queueMicrotask(()=>this.requestAfterRender()),!1}return t==="range"&&this.config.multiSelect!==!1&&e.key==="a"&&(e.ctrlKey||e.metaKey)?this.grid.query("isEditing").some(Boolean)?!1:(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0):!1}onCellMouseDown(e){if(!this.isSelectionEnabled()||this.config.mode!=="range"||e.rowIndex===void 0||e.colIndex===void 0||e.rowIndex<0||e.column&&ae(e.column)||!this.isCellSelectable(e.rowIndex,e.colIndex)||e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const t=e.rowIndex,i=e.colIndex,n=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&this.config.multiSelect!==!1,o={startRow:t,startCol:i,endRow:t,endCol:i};return!n&&this.ranges.length===1&&Oe(this.ranges[0],o)?(this.cellAnchor={row:t,col:i},!0):(this.cellAnchor={row:t,col:i},n||(this.ranges=[]),this.ranges.push(o),this.activeRange=o,this.emit("selection-change",this.#r()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled()||this.config.mode!=="range"||!this.isDragging||!this.cellAnchor||e.rowIndex===void 0||e.colIndex===void 0||e.rowIndex<0)return;let t=e.colIndex;const i=this.visibleColumns[t];if(i&&ae(i)){const s=this.visibleColumns.findIndex(l=>!ae(l));s>=0&&(t=s)}const n=vt(this.cellAnchor,{row:e.rowIndex,col:t}),o=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return o&&Oe(o,n)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=n:this.ranges.push(n),this.activeRange=n,this.emit("selection-change",this.#r()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&this.config.mode==="range"&&this.isDragging)return this.isDragging=!1,!0}processColumns(e){if(this.config.checkbox&&this.config.mode==="row"){if(e.some(o=>o.field===Vi))return e;const t=this.#t(),i=e.findIndex(Me),n=i>=0?i+1:0;return[...e.slice(0,n),t,...e.slice(n)]}return e}#t(){return{field:Vi,header:"",width:32,resizable:!1,sortable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0,checkboxColumn:!0},headerRenderer:()=>{const e=document.createElement("div");if(e.className="tbw-checkbox-header",this.config.multiSelect===!1)return e;const t=document.createElement("input");return t.type="checkbox",t.className="tbw-select-all-checkbox",t.addEventListener("click",i=>{i.stopPropagation(),i.target.checked?this.selectAll():this.clearSelection()}),e.appendChild(t),e},renderer:e=>{const t=document.createElement("input");t.type="checkbox",t.className="tbw-select-row-checkbox";const i=e.cellEl;if(i){const n=parseInt(i.getAttribute("data-row")??"-1",10);n>=0&&(t.checked=this.selected.has(n))}return t}}}#e(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(n=>{const o=n.closest(".cell"),s=o?Se(o):-1;s>=0&&(n.checked=this.selected.has(s))});const i=e.querySelector(".tbw-select-all-checkbox");if(i){const n=this.rows.length;let o=0;if(this.config.isSelectable)for(let a=0;a<n;a++)this.isRowSelectable(a)&&o++;else o=n;const s=o>0&&this.selected.size>=o,l=this.selected.size>0;i.checked=s,i.indeterminate=l&&!s}}#u(e){const t=this.grid._focusRow,i=this.grid._focusCol;if(e==="row"){if(this.explicitSelection){this.explicitSelection=!1,this.lastSyncedFocusRow=t;return}t!==this.lastSyncedFocusRow&&(this.lastSyncedFocusRow=t,this.isRowSelectable(t)&&(!this.selected.has(t)||this.selected.size!==1)&&(this.selected.clear(),this.selected.add(t),this.lastSelected=t,this.anchor=t,this.emit("selection-change",this.#r())))}if(e==="cell"){if(this.explicitSelection){this.explicitSelection=!1,this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=i;return}if((t!==this.lastSyncedFocusRow||i!==this.lastSyncedFocusCol)&&(this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=i,this.isCellSelectable(t,i))){const n=this.selectedCell;(!n||n.row!==t||n.col!==i)&&(this.selectedCell={row:t,col:i},this.emit("selection-change",this.#r()))}}}#c(){const e=this.gridElement;if(!e)return;const{mode:t}=this.config,i=!!this.config.isSelectable;e.querySelectorAll(".cell").forEach(s=>{s.classList.remove("selected","top","bottom","first","last"),i&&s.removeAttribute("data-selectable")});const o=e.querySelectorAll(".data-grid-row");if(o.forEach(s=>{s.classList.remove("selected","row-focus"),i&&s.removeAttribute("data-selectable")}),t==="row"&&(ge(e),o.forEach(s=>{const l=s.querySelector(".cell[data-row]"),a=Se(l);a>=0&&(i&&!this.isRowSelectable(a)&&s.setAttribute("data-selectable","false"),this.selected.has(a)&&s.classList.add("selected","row-focus"))}),this.config.checkbox&&this.#e(e)),(t==="cell"||t==="range")&&i&&e.querySelectorAll(".cell[data-row][data-col]").forEach(l=>{const a=parseInt(l.getAttribute("data-row")??"-1",10),c=parseInt(l.getAttribute("data-col")??"-1",10);a>=0&&c>=0&&(this.isCellSelectable(a,c)||l.setAttribute("data-selectable","false"))}),t==="range"&&this.ranges.length>0){ge(e);const s=this.ranges.map(ce),l=(c,d)=>{for(const u of s)if(c>=u.startRow&&c<=u.endRow&&d>=u.startCol&&d<=u.endCol)return!0;return!1};e.querySelectorAll(".cell[data-row][data-col]").forEach(c=>{const d=parseInt(c.getAttribute("data-row")??"-1",10),u=parseInt(c.getAttribute("data-col")??"-1",10);if(d>=0&&u>=0){const h=this.visibleColumns[u];if(h&&ae(h))return;l(d,u)&&(c.classList.add("selected"),l(d-1,u)||c.classList.add("top"),l(d+1,u)||c.classList.add("bottom"),l(d,u-1)||c.classList.add("first"),l(d,u+1)||c.classList.add("last"))}})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.children[0],{mode:i}=this.config;if(this.pendingKeyboardUpdate&&i==="range"){const{shiftKey:n}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const o=this.grid._focusRow,s=this.grid._focusCol;if(n&&this.cellAnchor){const l=vt(this.cellAnchor,{row:o,col:s});this.ranges=[l],this.activeRange=l}else n||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:o,col:s});this.emit("selection-change",this.#r())}this.#u(i),this.grid.setAttribute("data-selection-mode",i),t&&t.classList.toggle("selecting",this.isDragging),this.#c()}onScrollRender(){this.isSelectionEnabled()&&this.#c()}getSelection(){return{mode:this.config.mode,ranges:this.#r().ranges,anchor:this.cellAnchor}}getSelectedCells(){return Bs(this.ranges)}isCellSelected(e,t){return qs(e,t,this.ranges)}selectAll(){const{mode:e,multiSelect:t}=this.config;if(t!==!1){if(e==="row"){this.selected.clear();for(let i=0;i<this.rows.length;i++)this.isRowSelectable(i)&&this.selected.add(i);this.explicitSelection=!0,this.emit("selection-change",this.#r()),this.requestAfterRender()}else if(e==="range"){const i=this.rows.length,n=this.columns.length;if(i>0&&n>0){const o={startRow:0,startCol:0,endRow:i-1,endCol:n-1};this.ranges=[o],this.activeRange=o,this.emit("selection-change",this.#r()),this.requestAfterRender()}}}}selectRows(e){if(this.config.mode!=="row")return;const t=this.config.multiSelect===!1&&e.length>1?[e[e.length-1]]:e;this.selected.clear();for(const i of t)i>=0&&i<this.rows.length&&this.isRowSelectable(i)&&this.selected.add(i);this.anchor=t.length>0?t[t.length-1]:null,this.explicitSelection=!0,this.emit("selection-change",this.#r()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const{mode:e}=this.config,t=this.rows;if(e==="row")return this.getSelectedRowIndices().filter(i=>i>=0&&i<t.length).map(i=>t[i]);if(e==="cell"&&this.selectedCell){const{row:i}=this.selectedCell;return i>=0&&i<t.length?[t[i]]:[]}if(e==="range"&&this.ranges.length>0){const i=new Set;for(const n of this.ranges){const o=Math.max(0,Math.min(n.startRow,n.endRow)),s=Math.min(t.length-1,Math.max(n.startRow,n.endRow));for(let l=o;l<=s;l++)i.add(l)}return[...i].sort((n,o)=>n-o).map(n=>t[n])}return[]}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.emit("selection-change",{mode:this.config.mode,ranges:[]}),this.requestAfterRender()}setRanges(e){this.ranges=e.map(t=>({startRow:t.from.row,startCol:t.from.col,endRow:t.to.row,endCol:t.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",{mode:this.config.mode,ranges:Ki(this.ranges)}),this.requestAfterRender()}#r(){return Ws(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}}function Fe(r,e){return Math.floor(r/e)}function Vs(r,e){return{start:r*e,end:(r+1)*e}}function Us(r,e,t){const i=Fe(r,t),n=Fe(e-1,t),o=[];for(let s=i;s<=n;s++)o.push(s);return o}async function Ui(r,e,t,i){const n=Vs(e,t);return r.getRows({startRow:n.start,endRow:n.end,sortModel:i.sortModel,filterModel:i.filterModel})}function js(r,e,t){const i=Fe(r,e),n=t.get(i);if(!n)return;const o=r%e;return n[o]}const Ys=100;class Xs extends M{name="serverSide";get defaultConfig(){return{pageSize:100,cacheBlockSize:100,maxConcurrentRequests:2}}dataSource=null;totalRowCount=0;loadedBlocks=new Map;loadingBlocks=new Set;lastRequestId=0;scrollDebounceTimer;detach(){this.dataSource=null,this.totalRowCount=0,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.lastRequestId=0,this.scrollDebounceTimer&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=void 0)}loadRequiredBlocks(){if(!this.dataSource)return;const e=this.grid,t=this.config.cacheBlockSize??100,i={startRow:e._virtualization.start,endRow:e._virtualization.end},n=Us(i.startRow,i.endRow,t);for(const o of n)if(!(this.loadedBlocks.has(o)||this.loadingBlocks.has(o))){if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2))break;this.loadingBlocks.add(o),Ui(this.dataSource,o,t,{}).then(s=>{this.loadedBlocks.set(o,s.rows),this.totalRowCount=s.totalRowCount,this.loadingBlocks.delete(o),this.requestRender(),this.loadRequiredBlocks()}).catch(()=>{this.loadingBlocks.delete(o)})}}processRows(e){if(!this.dataSource)return[...e];const t=[];for(let i=0;i<this.totalRowCount;i++){const n=js(i,this.config.cacheBlockSize??100,this.loadedBlocks);t.push(n??{__loading:!0,__index:i})}return t}onScroll(e){this.dataSource&&(this.loadRequiredBlocks(),this.scrollDebounceTimer&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.loadRequiredBlocks()},Ys))}setDataSource(e){this.dataSource=e,this.loadedBlocks.clear(),this.loadingBlocks.clear();const t=this.config.cacheBlockSize??100;Ui(e,0,t,{}).then(i=>{this.loadedBlocks.set(0,i.rows),this.totalRowCount=i.totalRowCount,this.requestRender()})}refresh(){this.dataSource&&(this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.requestRender())}purgeCache(){this.loadedBlocks.clear()}getTotalRowCount(){return this.totalRowCount}isRowLoaded(e){const t=this.config.cacheBlockSize??100,i=Fe(e,t);return this.loadedBlocks.has(i)}getLoadedBlockCount(){return this.loadedBlocks.size}}function ji(r,e,t){return r.id!==void 0?String(r.id):t?`${t}-${e}`:String(e)}function yt(r,e){const t=new Set(r);return t.has(e)?t.delete(e):t.add(e),t}function Ct(r,e,t=null,i=0){const n=e.childrenField??"children",o=new Set;for(let s=0;s<r.length;s++){const l=r[s],a=ji(l,s,t),c=l[n];if(Array.isArray(c)&&c.length>0){o.add(a);const d=Ct(c,e,a,i+1);for(const u of d)o.add(u)}}return o}function Qs(){return new Set}function Yi(r,e,t,i=null,n=0){const o=t.childrenField??"children";for(let s=0;s<r.length;s++){const l=r[s],a=ji(l,s,i);if(a===e)return[a];const c=l[o];if(Array.isArray(c)&&c.length>0){const d=Yi(c,e,t,a,n+1);if(d)return[a,...d]}}return null}function Zs(r,e,t,i){const n=Yi(r,e,t);if(!n)return i;const o=new Set(i);for(let s=0;s<n.length-1;s++)o.add(n[s]);return o}function Xi(r,e="children"){if(!Array.isArray(r)||r.length===0)return!1;for(const t of r){if(!t)continue;const i=t[e];if(Array.isArray(i)&&i.length>0)return!0}return!1}function Js(r){if(!Array.isArray(r)||r.length===0)return null;const e=["children","items","nodes","subRows","nested"];for(const t of r)if(!(!t||typeof t!="object"))for(const i of e){const n=t[i];if(Array.isArray(n)&&n.length>0)return i}return null}const el="@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-inline-end:none!important;padding:0;display:flex;align-items:center;justify-content:flex-start}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1 / 3}tbw-grid .tree-cell-wrapper{display:inline-flex;align-items:center;padding-inline-start:calc(var(--tbw-tree-depth, 0) * var(--tbw-tree-indent-width, var(--tbw-tree-toggle-size, 1.25em)))}tbw-grid .tree-expander{display:flex;align-items:center;justify-content:flex-start;width:100%;height:100%;box-sizing:border-box}tbw-grid .tree-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-tree-toggle-size, 1.25em);height:var(--tbw-tree-toggle-size, 1.25em);flex-shrink:0}tbw-grid .tree-toggle:hover{color:var(--tbw-tree-accent, var(--tbw-color-accent))}tbw-grid .tree-spacer{width:var(--tbw-tree-toggle-size, 1.25em);display:inline-block;flex-shrink:0}tbw-grid .data-grid-row.tbw-tree-slide-in{animation:tbw-tree-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .data-grid-row.tbw-tree-fade-in{animation:tbw-tree-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-tree-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}@keyframes tbw-tree-fade-in{0%{opacity:0}to{opacity:1}}}";class tl extends M{static manifest={events:[{type:"tree-state-change",description:"Emitted when tree expansion state changes (toggle, expand all, collapse all)"}],queries:[{type:"canMoveRow",description:"Returns false for rows with children (parent nodes cannot be reordered)"}]};name="tree";styles=el;get defaultConfig(){return{childrenField:"children",autoDetect:!0,defaultExpanded:!1,indentWidth:20,showExpandIcons:!0,animation:"slide"}}expandedKeys=new Set;initialExpansionDone=!1;flattenedRows=[];rowKeyMap=new Map;previousVisibleKeys=new Set;keysToAnimate=new Set;sortState=null;detach(){this.expandedKeys.clear(),this.initialExpansionDone=!1,this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.sortState=null}handleQuery(e){if(e.type==="canMoveRow"){const t=e.context,i=this.config.childrenField??"children",n=t?.[i];if(Array.isArray(n)&&n.length>0)return!1}}get animationStyle(){return this.isAnimationEnabled?this.config.animation??"slide":!1}detect(e){if(!this.config.autoDetect)return!1;const t=e,i=this.config.childrenField??Js(t)??"children";return Xi(t,i)}processRows(e){const t=this.config.childrenField??"children",i=e;if(!Xi(i,t))return this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),[...e];let n=this.withStableKeys(i);this.sortState&&(n=this.sortTree(n,this.sortState.field,this.sortState.direction)),this.config.defaultExpanded&&!this.initialExpansionDone&&(this.expandedKeys=Ct(n,this.config),this.initialExpansionDone=!0),this.flattenedRows=this.flattenTree(n,this.expandedKeys),this.rowKeyMap.clear(),this.keysToAnimate.clear();const o=new Set;for(const s of this.flattenedRows)this.rowKeyMap.set(s.key,s),o.add(s.key),!this.previousVisibleKeys.has(s.key)&&s.depth>0&&this.keysToAnimate.add(s.key);return this.previousVisibleKeys=o,this.flattenedRows.map(s=>({...s.data,__treeKey:s.key,__treeDepth:s.depth,__treeHasChildren:s.hasChildren,__treeExpanded:s.isExpanded}))}withStableKeys(e,t=null){const i=this.config.childrenField??"children";return e.map((n,o)=>{const s=n.__stableKey,l=n.id!==void 0?String(n.id):s??(t?`${t}-${o}`:String(o)),a=n[i],c=Array.isArray(a)&&a.length>0;return{...n,__stableKey:l,...c?{[i]:this.withStableKeys(a,l)}:{}}})}flattenTree(e,t,i=0){const n=this.config.childrenField??"children",o=[];for(const s of e){const a=s.__stableKey??String(s.id??"?"),c=s[n],d=Array.isArray(c)&&c.length>0,u=t.has(a);o.push({key:a,data:s,depth:i,hasChildren:d,isExpanded:u,parentKey:i>0&&a.substring(0,a.lastIndexOf("-"))||null}),d&&u&&o.push(...this.flattenTree(c,t,i+1))}return o}sortTree(e,t,i){const n=this.config.childrenField??"children";return[...e].sort((s,l)=>{const a=s[t],c=l[t];return a==null&&c==null?0:a==null?-1:c==null?1:a>c?i:a<c?-i:0}).map(s=>{const l=s[n];return Array.isArray(l)&&l.length>0?{...s,[n]:this.sortTree(l,t,i)}:s})}processColumns(e){if(this.flattenedRows.length===0)return[...e];const t=[...e];if(t.length===0)return t;const i=t[0],n=i.viewRenderer,o=()=>this.config,s=this.setIcon.bind(this),l=this.resolveIcon.bind(this),a=c=>{const{row:d,value:u}=c,{showExpandIcons:h=!0,indentWidth:p}=o(),g=d,f=g.__treeDepth??0,w=document.createElement("span");if(w.className="tree-cell-wrapper",w.style.setProperty("--tbw-tree-depth",String(f)),p!==void 0&&w.style.setProperty("--tbw-tree-indent-width",`${p}px`),h)if(g.__treeHasChildren){const b=document.createElement("span");b.className=`tree-toggle${g.__treeExpanded?" expanded":""}`,s(b,l(g.__treeExpanded?"collapse":"expand")),b.setAttribute("data-tree-key",String(g.__treeKey??"")),w.appendChild(b)}else{const b=document.createElement("span");b.className="tree-spacer",w.appendChild(b)}const y=document.createElement("span");if(y.className="tree-content",n){const b=n(c);b instanceof Node?y.appendChild(b):typeof b=="string"&&(y.innerHTML=b)}else y.textContent=u!=null?String(u):"";return w.appendChild(y),w};return t[0]={...i,viewRenderer:a},t}onCellClick(e){const t=e.originalEvent?.target;if(!t?.classList.contains("tree-toggle"))return!1;const i=t.getAttribute("data-tree-key");if(!i)return!1;const n=this.rowKeyMap.get(i);return n?(this.expandedKeys=yt(this.expandedKeys,i),this.emit("tree-expand",{key:i,row:n.data,expanded:this.expandedKeys.has(i),depth:n.depth}),this.requestRender(),!0):!1}onKeyDown(e){if(e.key!==" ")return;const t=this.grid._focusRow,i=this.flattenedRows[t];if(i?.hasChildren)return e.preventDefault(),this.expandedKeys=yt(this.expandedKeys,i.key),this.emit("tree-expand",{key:i.key,row:i.data,expanded:this.expandedKeys.has(i.key),depth:i.depth}),this.requestRenderWithFocus(),!0}onHeaderClick(e){if(this.flattenedRows.length===0||!e.column.sortable)return!1;const{field:t}=e.column;!this.sortState||this.sortState.field!==t?this.sortState={field:t,direction:1}:this.sortState.direction===1?this.sortState={field:t,direction:-1}:this.sortState=null;const i=this.grid;return i._sortState!==void 0&&(i._sortState=this.sortState?{...this.sortState}:null),this.emit("sort-change",{field:t,direction:this.sortState?.direction??0}),this.requestRender(),!0}afterRender(){const e=this.animationStyle;if(e===!1||this.keysToAnimate.size===0)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const i=e==="fade"?"tbw-tree-fade-in":"tbw-tree-slide-in";for(const n of t.querySelectorAll(".data-grid-row")){const o=n.querySelector(".cell[data-row]"),s=o?parseInt(o.getAttribute("data-row")??"-1",10):-1,l=this.flattenedRows[s]?.key;l&&this.keysToAnimate.has(l)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}expand(e){this.expandedKeys.add(e),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}toggle(e){this.expandedKeys=yt(this.expandedKeys,e),this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}expandAll(){this.expandedKeys=Ct(this.rows,this.config),this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=Qs(),this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}getExpandedKeys(){return[...this.expandedKeys]}getFlattenedRows(){return[...this.flattenedRows]}getRowByKey(e){return this.rowKeyMap.get(e)?.data}expandToKey(e){this.expandedKeys=Zs(this.rows,e,this.config,this.expandedKeys),this.requestRender()}}function il(r,e,t){const i=[...r.undoStack,e];for(;i.length>t;)i.shift();return{undoStack:i,redoStack:[]}}function Qi(r){if(r.undoStack.length===0)return{newState:r,action:null};const e=[...r.undoStack],t=e.pop();return t?{newState:{undoStack:e,redoStack:[...r.redoStack,t]},action:t}:{newState:r,action:null}}function Zi(r){if(r.redoStack.length===0)return{newState:r,action:null};const e=[...r.redoStack],t=e.pop();return t?{newState:{undoStack:[...r.undoStack,t],redoStack:e},action:t}:{newState:r,action:null}}function nl(r){return r.undoStack.length>0}function rl(r){return r.redoStack.length>0}function ol(){return{undoStack:[],redoStack:[]}}function sl(r,e,t,i){return{type:"cell-edit",rowIndex:r,field:e,oldValue:t,newValue:i,timestamp:Date.now()}}class ll extends M{static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];attach(e){super.attach(e),this.on("cell-edit-committed",t=>{this.recordEdit(t.rowIndex,t.field,t.oldValue,t.newValue)})}detach(){this.undoStack=[],this.redoStack=[]}onKeyDown(e){const t=(e.ctrlKey||e.metaKey)&&e.key==="z"&&!e.shiftKey,i=(e.ctrlKey||e.metaKey)&&(e.key==="y"||e.key==="z"&&e.shiftKey);if(t){const n=Qi({undoStack:this.undoStack,redoStack:this.redoStack});if(n.action){const o=this.rows;o[n.action.rowIndex]&&(o[n.action.rowIndex][n.action.field]=n.action.oldValue),this.undoStack=n.newState.undoStack,this.redoStack=n.newState.redoStack,this.emit("undo",{action:n.action,type:"undo"}),this.requestRender()}return!0}if(i){const n=Zi({undoStack:this.undoStack,redoStack:this.redoStack});if(n.action){const o=this.rows;o[n.action.rowIndex]&&(o[n.action.rowIndex][n.action.field]=n.action.newValue),this.undoStack=n.newState.undoStack,this.redoStack=n.newState.redoStack,this.emit("redo",{action:n.action,type:"redo"}),this.requestRender()}return!0}return!1}recordEdit(e,t,i,n){const o=sl(e,t,i,n),s=il({undoStack:this.undoStack,redoStack:this.redoStack},o,this.config.maxHistorySize??100);this.undoStack=s.undoStack,this.redoStack=s.redoStack}undo(){const e=Qi({undoStack:this.undoStack,redoStack:this.redoStack});if(e.action){const t=this.rows;t[e.action.rowIndex]&&(t[e.action.rowIndex][e.action.field]=e.action.oldValue),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.requestRender()}return e.action}redo(){const e=Zi({undoStack:this.undoStack,redoStack:this.redoStack});if(e.action){const t=this.rows;t[e.action.rowIndex]&&(t[e.action.rowIndex][e.action.field]=e.action.newValue),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.requestRender()}return e.action}canUndo(){return nl({undoStack:this.undoStack,redoStack:this.redoStack})}canRedo(){return rl({undoStack:this.undoStack,redoStack:this.redoStack})}clearHistory(){const e=ol();this.undoStack=e.undoStack,this.redoStack=e.redoStack}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}}const al='@layer tbw-plugins{.tbw-visibility-content{display:flex;flex-direction:column;height:100%}.tbw-visibility-list{flex:1;overflow-y:auto;padding:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem))}.tbw-visibility-row{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-menu-item-padding, .375rem .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);border-radius:var(--tbw-border-radius, .25rem);position:relative}.tbw-visibility-row:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-row input[type=checkbox]{cursor:pointer}.tbw-visibility-row.locked span{color:var(--tbw-color-fg-muted)}.tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-row.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-label{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));flex:1;cursor:pointer}.tbw-visibility-row.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-row.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-show-all{margin:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding, .5rem .75rem);border:1px solid var(--tbw-visibility-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius, .25rem);background:var(--tbw-visibility-btn-bg, var(--tbw-color-header-bg));color:var(--tbw-color-fg);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-visibility-show-all:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header{display:flex;align-items:center;padding:var(--tbw-menu-item-padding, .375rem .25rem);font-size:var(--tbw-font-size-sm, .8125rem);font-weight:600;color:var(--tbw-color-fg);border-bottom:1px solid var(--tbw-color-border);margin-top:var(--tbw-spacing-sm, .25rem);position:relative}.tbw-visibility-group-header:first-child{margin-top:0}.tbw-visibility-group-header .tbw-visibility-label{gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-visibility-group-header.reorderable{cursor:grab}.tbw-visibility-group-header.reorderable:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header .tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-group-header.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-group-header.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-group-header.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-group-header.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row--grouped{padding-left:calc(var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem)) + .75rem)}}';function Ji(r){const e=r.meta??{};return e.lockPosition!==!0&&e.suppressMovable!==!0}class ie extends M{static dependencies=[{name:"reorder",required:!1,reason:"Enables drag-to-reorder columns in visibility panel"}];static manifest={queries:[{type:"getContextMenuItems",description:'Contributes "Hide column" item to the header context menu'}]};name="visibility";static PANEL_ID="columns";styles=al;get defaultConfig(){return{allowHideAll:!1}}columnListElement=null;isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;draggedGroupId=null;draggedGroupFields=[];clearDragClasses(e){e.querySelectorAll(".tbw-visibility-row, .tbw-visibility-group-header").forEach(t=>{t.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-move",()=>{this.columnListElement&&requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})},{signal:this.disconnectSignal})}detach(){this.columnListElement=null,this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}handleQuery(e){if(e.type==="getContextMenuItems"){const t=e.context;if(!t.isHeader)return;const i=t.column;return!i?.field||i.meta?.lockVisibility?void 0:[{id:"visibility/hide-column",label:"Hide Column",icon:"👁",order:30,action:()=>this.hideColumn(i.field)}]}}getToolPanel(){return{id:ie.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(ie.PANEL_ID)||this.grid.toggleToolPanelSection(ie.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(ie.PANEL_ID)}isColumnVisible(e){return this.grid.isColumnVisible(e)}setColumnVisible(e,t){this.grid.setColumnVisible(e,t)}getVisibleColumns(){return this.grid.getAllColumns().filter(e=>e.visible).map(e=>e.field)}getHiddenColumns(){return this.grid.getAllColumns().filter(e=>!e.visible).map(e=>e.field)}showAll(){this.grid.showAllColumns()}toggleColumn(e){this.grid.toggleColumnVisibility(e)}showColumn(e){this.setColumnVisible(e,!0)}hideColumn(e){this.setColumnVisible(e,!1)}getAllColumns(){return this.grid.getAllColumns()}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(ie.PANEL_ID)}renderPanelContent(e){const t=document.createElement("div");t.className="tbw-visibility-content";const i=document.createElement("div");i.className="tbw-visibility-list",t.appendChild(i);const n=document.createElement("button");return n.className="tbw-visibility-show-all",n.textContent="Show All",n.addEventListener("click",()=>{this.grid.showAllColumns(),this.rebuildToggles(i)}),t.appendChild(n),this.columnListElement=i,this.rebuildToggles(i),e.appendChild(t),()=>{this.columnListElement=null,t.remove()}}hasReorderPlugin(){const e=this.grid?.getPluginByName?.("reorder");return!!(e&&typeof e.moveColumn=="function")}rebuildToggles(e){const t=this.hasReorderPlugin();e.innerHTML="";const i=this.grid.getAllColumns().filter(a=>!a.utility),o=this.grid.query("getColumnGrouping")?.flat().filter(a=>a&&a.fields.length>0)??[];if(o.length===0){this.renderFlatColumnList(i,t,e);return}const s=new Map;for(const a of o)for(const c of a.fields)s.set(c,a);const l=new Set;for(const a of i){const c=s.get(a.field);if(c){if(!l.has(c.id)){l.add(c.id);const d=new Set(c.fields),u=i.filter(h=>d.has(h.field));u.length>0&&this.renderGroupSection(c,u,t,e)}}else{const d=i.indexOf(a);e.appendChild(this.createColumnRow(a,d,t,e))}}}renderGroupSection(e,t,i,n){const o=document.createElement("div");o.className="tbw-visibility-group-header",o.setAttribute("data-group-id",e.id),i&&(o.draggable=!0,o.classList.add("reorderable"),this.setupGroupDragListeners(o,e,n));const s=document.createElement("label");s.className="tbw-visibility-label";const l=document.createElement("input");l.type="checkbox";const a=t.filter(h=>h.visible).length,c=t.every(h=>h.lockVisible);a===t.length?(l.checked=!0,l.indeterminate=!1):a===0?(l.checked=!1,l.indeterminate=!1):(l.checked=!1,l.indeterminate=!0),l.disabled=c,l.addEventListener("change",()=>{const h=l.checked;for(const p of t)p.lockVisible||this.grid.setColumnVisible(p.field,h);setTimeout(()=>this.rebuildToggles(n),0)});const d=document.createElement("span");if(d.textContent=e.label,s.appendChild(l),s.appendChild(d),o.appendChild(s),i){const h=document.createElement("span");h.className="tbw-visibility-handle",this.setIcon(h,this.resolveIcon("dragHandle")),h.title="Drag to reorder group",o.insertBefore(h,s)}n.appendChild(o);const u=this.grid.getAllColumns().filter(h=>!h.utility);for(const h of t){const p=u.findIndex(f=>f.field===h.field),g=this.createColumnRow(h,p,i,n);g.classList.add("tbw-visibility-row--grouped"),n.appendChild(g)}}renderFlatColumnList(e,t,i){const n=this.grid.getAllColumns().filter(o=>!o.utility);for(const o of e){const s=n.findIndex(l=>l.field===o.field);i.appendChild(this.createColumnRow(o,s,t,i))}}createColumnRow(e,t,i,n){const o=e.header||e.field,s=document.createElement("div");s.className=e.lockVisible?"tbw-visibility-row locked":"tbw-visibility-row",s.setAttribute("data-field",e.field),s.setAttribute("data-index",String(t)),i&&Ji(e)&&(s.draggable=!0,s.classList.add("reorderable"),this.setupDragListeners(s,e.field,t,n));const l=document.createElement("label");l.className="tbw-visibility-label";const a=document.createElement("input");a.type="checkbox",a.checked=e.visible,a.disabled=e.lockVisible??!1,a.addEventListener("change",()=>{this.grid.toggleColumnVisibility(e.field),setTimeout(()=>this.rebuildToggles(n),0)});const c=document.createElement("span");if(c.textContent=o,l.appendChild(a),l.appendChild(c),i&&Ji(e)){const d=document.createElement("span");d.className="tbw-visibility-handle",this.setIcon(d,this.resolveIcon("dragHandle")),d.title="Drag to reorder",s.appendChild(d)}return s.appendChild(l),s}setupGroupDragListeners(e,t,i){e.addEventListener("dragstart",n=>{this.isDragging=!0,this.draggedGroupId=t.id,this.draggedGroupFields=[...t.fields],this.draggedField=null,this.draggedIndex=null,n.dataTransfer&&(n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",`group:${t.id}`)),e.classList.add("dragging"),i.querySelectorAll(".tbw-visibility-row--grouped").forEach(o=>{const s=o.getAttribute("data-field");s&&this.draggedGroupFields.includes(s)&&o.classList.add("dragging")})}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedGroupId=null,this.draggedGroupFields=[],this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(i)}),e.addEventListener("dragover",n=>{if(n.preventDefault(),!this.isDragging||this.draggedGroupId===t.id||!this.draggedGroupId)return;const o=e.getBoundingClientRect(),s=o.top+o.height/2,l=n.clientY<s;this.clearDragClasses(i),e.classList.add("drop-target"),e.classList.toggle("drop-before",l),e.classList.toggle("drop-after",!l)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",n=>{if(n.preventDefault(),!this.isDragging||!this.draggedGroupId||this.draggedGroupId===t.id)return;const o=e.getBoundingClientRect(),s=n.clientY<o.top+o.height/2;this.executeGroupDrop(this.draggedGroupFields,t.fields,s,i)})}executeGroupDrop(e,t,i,n){const s=this.grid.getAllColumns().map(h=>h.field),l=s.filter(h=>!e.includes(h)),a=i?t[0]:t[t.length-1],c=l.indexOf(a);if(c===-1)return;const d=i?c:c+1,u=s.filter(h=>e.includes(h));l.splice(d,0,...u),this.grid.setColumnOrder(l),requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})}setupDragListeners(e,t,i,n){e.addEventListener("dragstart",o=>{this.isDragging=!0,this.draggedField=t,this.draggedIndex=i,this.draggedGroupId=null,this.draggedGroupFields=[],o.dataTransfer&&(o.dataTransfer.effectAllowed="move",o.dataTransfer.setData("text/plain",t)),e.classList.add("dragging")}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(n)}),e.addEventListener("dragover",o=>{if(o.preventDefault(),!this.isDragging)return;if(this.draggedGroupId){if(e.classList.contains("tbw-visibility-row--grouped"))return}else if(this.draggedField===t)return;const s=e.getBoundingClientRect(),l=s.top+s.height/2;this.dropIndex=o.clientY<l?i:i+1,this.clearDragClasses(n),this.draggedGroupId?(n.querySelector(`.tbw-visibility-group-header[data-group-id="${this.draggedGroupId}"]`)?.classList.add("dragging"),n.querySelectorAll(".tbw-visibility-row--grouped").forEach(a=>{const c=a.getAttribute("data-field");c&&this.draggedGroupFields.includes(c)&&a.classList.add("dragging")})):this.draggedField&&n.querySelector(`.tbw-visibility-row[data-field="${this.draggedField}"]`)?.classList.add("dragging"),e.classList.add("drop-target"),e.classList.toggle("drop-before",o.clientY<l),e.classList.toggle("drop-after",o.clientY>=l)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",o=>{if(o.preventDefault(),!this.isDragging)return;if(this.draggedGroupId&&this.draggedGroupFields.length>0){if(e.classList.contains("tbw-visibility-row--grouped"))return;const d=e.getBoundingClientRect(),u=o.clientY<d.top+d.height/2;this.executeGroupDrop(this.draggedGroupFields,[t],u,n);return}const s=this.draggedField,l=this.draggedIndex,a=this.dropIndex;if(s===null||l===null||a===null)return;const c=a>l?a-1:a;if(c!==l){const d=this.grid.getAllColumns(),h=d.filter(f=>!f.utility)[c]?.field,p=h?d.findIndex(f=>f.field===h):d.length,g={field:s,fromIndex:l,toIndex:p};this.emit("column-reorder-request",g)}})}}S.BLANK_FILTER_VALUE=Ce,S.BaseGridPlugin=M,S.ClipboardPlugin=Yr,S.ColumnVirtualizationPlugin=Jr,S.ContextMenuPlugin=ct,S.DEFAULT_ANIMATION_CONFIG=xt,S.DEFAULT_GRID_ICONS=K,S.DGEvents=Wr,S.DataGridElement=j,S.EditingPlugin=fo,S.ExportPlugin=bo,S.FilteringPlugin=X,S.FitModeEnum=ne,S.GridCSSVars=Gr,S.GridClasses=q,S.GridDataAttrs=ve,S.GridElement=j,S.GridSelectors=qr,S.GroupingColumnsPlugin=Po,S.GroupingRowsPlugin=qo,S.MasterDetailPlugin=ft,S.MultiSortPlugin=Xo,S.PLUGIN_QUERIES=Nr,S.PinnedColumnsPlugin=es,S.PinnedRowsPlugin=ls,S.PivotPlugin=te,S.PluginEvents=Kr,S.PluginManager=be,S.PrintPlugin=Ls,S.ROW_DRAG_HANDLE_FIELD=Wi,S.RenderPhase=O,S.ReorderPlugin=Is,S.ResponsivePlugin=Ms,S.RowReorderPlugin=Os,S.SelectionPlugin=Ks,S.ServerSidePlugin=Xs,S.TreePlugin=tl,S.UndoRedoPlugin=ll,S.VisibilityPlugin=ie,S.builtInSort=Ke,S.createGrid=Br,S.defaultComparator=Ft,S.defaultEditorFor=pi,S.defaultPasteHandler=li,S.getUniqueValuesBatch=yi,S.printGridIsolated=Bi,S.queryGrid=$r,Object.defineProperty(S,Symbol.toStringTag,{value:"Module"})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGrid={})}(this,function(e){"use strict";const t={STRETCH:"stretch",FIXED:"fixed"},i={mode:"reduced-motion",duration:200,easing:"ease-out"},n='<svg viewBox="0 0 16 16" width="12" height="12"><path fill="currentColor" d="M6 10.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/></svg>',r={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:n,filterActive:n,print:"🖨️"};function o(e,t){if(!(e&&e.length||t&&t.length))return[];if(!e||!e.length)return t||[];if(!t||!t.length)return e;const i={};t.forEach(e=>{const t=i[e.field];if(t){e.header&&!t.header&&(t.header=e.header),e.type&&!t.type&&(t.type=e.type),e.sortable&&(t.sortable=!0),e.editable&&(t.editable=!0),e.resizable&&(t.resizable=!0),null!=e.width&&null==t.width&&(t.width=e.width),null!=e.minWidth&&null==t.minWidth&&(t.minWidth=e.minWidth),e.__viewTemplate&&(t.__viewTemplate=e.__viewTemplate),e.__editorTemplate&&(t.__editorTemplate=e.__editorTemplate),e.__headerTemplate&&(t.__headerTemplate=e.__headerTemplate);const i=e.renderer||e.viewRenderer,n=t.renderer||t.viewRenderer;i&&!n&&(t.viewRenderer=i,e.renderer&&(t.renderer=i)),e.editor&&!t.editor&&(t.editor=e.editor)}else i[e.field]={...e}});const n=e.map(e=>{const t=i[e.field];if(!t)return e;const n={...e};t.header&&!n.header&&(n.header=t.header),t.type&&!n.type&&(n.type=t.type),n.sortable=e.sortable||t.sortable,!0!==e.resizable&&!0!==t.resizable||(n.resizable=!0),n.editable=e.editable||t.editable,null!=t.width&&null==n.width&&(n.width=t.width),null!=t.minWidth&&null==n.minWidth&&(n.minWidth=t.minWidth),t.__viewTemplate&&(n.__viewTemplate=t.__viewTemplate),t.__editorTemplate&&(n.__editorTemplate=t.__editorTemplate),t.__headerTemplate&&(n.__headerTemplate=t.__headerTemplate);const r=t.renderer||t.viewRenderer,o=n.renderer||n.viewRenderer;return r&&!o&&(n.viewRenderer=r,t.renderer&&(n.renderer=r)),t.editor&&!n.editor&&(n.editor=t.editor),delete i[e.field],n});return Object.keys(i).forEach(e=>n.push(i[e])),n}function s(e,t){try{e.part?.add?.(t)}catch{}const i=e.getAttribute("part");i?i.split(/\s+/).includes(t)||e.setAttribute("part",i+" "+t):e.setAttribute("part",t)}function l(e){const i=e.effectiveConfig?.fitMode||e.fitMode||t.STRETCH;if(i!==t.STRETCH&&i!==t.FIXED)return;if(e.__didInitialAutoSize)return;if(!e.isConnected)return;const n=Array.from(e._headerRowEl?.children||[]);if(!n.length)return;let r=!1;e._visibleColumns.forEach((t,i)=>{if(t.width)return;const o=n[i];let s=o?o.scrollWidth:0;for(const n of e._rowPool){const e=n.children[i];if(e){const t=e.scrollWidth;t>s&&(s=t)}}s>0&&(t.width=s+2,t.__autoSized=!0,r=!0)}),r&&c(e),e.__didInitialAutoSize=!0}const a=/^(?:\d+(?:\.\d+)?(?:px|%|fr|em|rem|ch|vw|vh|vmin|vmax)|calc\(.+\)|min-content|max-content|minmax\(.+\)|fit-content\(.+\)|auto)$/i;function d(e,t){return"number"==typeof e?`${e}px`:(a.test(e)||console.warn(`[tbw-grid] Column '${t??"?"}' has an invalid CSS width value: '${e}'. Expected a number (px) or a valid CSS unit string (e.g. '30%', '2fr', 'calc(...)').`),e)}function c(e){const i=e.effectiveConfig?.fitMode||e.fitMode||t.STRETCH;e._gridTemplate=i===t.STRETCH?e._visibleColumns.map(e=>{if(null!=e.width)return d(e.width,e.field);const t=e.minWidth;return null!=t?`minmax(${t}px, 1fr)`:"1fr"}).join(" ").trim():e._visibleColumns.map(e=>null!=e.width?d(e.width,e.field):"max-content").join(" "),e.style.setProperty("--tbw-column-template",e._gridTemplate)}function h(e,t){const i=e[0]||{},n=Object.keys(i).map(e=>{const t=i[e],n=null==(r=t)?"string":"number"==typeof r?"number":"boolean"==typeof r?"boolean":r instanceof Date||"string"==typeof r&&/\d{4}-\d{2}-\d{2}/.test(r)&&!isNaN(Date.parse(r))?"date":"string";var r;return{field:e,header:e.charAt(0).toUpperCase()+e.slice(1),type:n}}),r={};return n.forEach(e=>{r[e.field]=e.type||"string"}),{columns:n,typeMap:r}}const u=/{{\s*([^}]+)\s*}}/g,g="__DG_EMPTY__",p=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,f=/__(proto|defineGetter|defineSetter)|constructor|window|globalThis|global|process|Function|import|eval|Reflect|Proxy|Error|arguments|document|location|cookie|localStorage|sessionStorage|indexedDB|fetch|XMLHttpRequest|WebSocket|Worker|SharedWorker|ServiceWorker|opener|parent|top|frames|self|this\b/;const w=new Set(["script","iframe","object","embed","form","input","button","textarea","select","link","meta","base","style","template","slot","portal","frame","frameset","applet","noscript","noembed","plaintext","xmp","listing"]),m=/^on\w+$/i,b=new Set(["href","src","action","formaction","data","srcdoc","xlink:href","poster","srcset"]),v=/^\s*(javascript|vbscript|data|blob):/i;function y(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],i=e.querySelectorAll("*");for(const n of i){const e=n.tagName.toLowerCase();if(w.has(e)){t.push(n);continue}if("svg"===e||"http://www.w3.org/2000/svg"===n.namespaceURI){if(Array.from(n.attributes).some(e=>m.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(n);continue}}const i=[];for(const t of n.attributes){const e=t.name.toLowerCase();m.test(e)?i.push(t.name):(b.has(e)&&v.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&i.push(t.name)}i.forEach(e=>n.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}function C(e,t){if(!e||-1===e.indexOf("{{"))return e;const i=[],n=e.replace(u,(e,n)=>{const r=function(e,t){if(e=(e||"").trim(),!e)return g;if(x.test(e))return g;if("value"===e)return null==t.value?g:String(t.value);if(e.startsWith("row.")&&!/[()?]/.test(e)&&!e.includes(":")){const i=e.slice(4),n=t.row?t.row[i]:void 0;return null==n?g:String(n)}if(e.length>80)return g;if(!p.test(e)||f.test(e))return g;const i=e.match(/\./g);if(i&&i.length>1)return g;try{const i=new Function("value","row",`return (${e});`)(t.value,t.row),n=null==i?"":String(i);return x.test(n)?g:n||g}catch{return g}}(n,t);return i.push({expr:n.trim(),result:r}),r}),r=(o=n)?o.replace(new RegExp(g,"g"),"").replace(/Reflect\.[^<>{}\s]+|\bProxy\b|ownKeys\([^)]*\)/g,""):o;var o;const s=i.length&&i.every(e=>""===e.result||e.result===g);return x.test(e)||s?"":r}const x=/Reflect|Proxy|ownKeys/;function E(e){if(x.test(e.textContent||"")){for(const t of e.childNodes)t.nodeType===Node.TEXT_NODE&&x.test(t.textContent||"")&&(t.textContent="");x.test(e.textContent||"")&&(e.textContent="")}}function R(e){const t=x.test(e),i=i=>{if(t)return"";return C(e,i)};return i.__blocked=t,i}class S{#e;#t;#i;#n;#r;#o={};#s={};#l=!0;#a=[];#d;#c;#h;#u;#g;constructor(e){this.#u=e}get original(){return this.#o}get effective(){return this.#s}get columns(){return this.#s.columns??[]}set columns(e){this.#s.columns=e}get lightDomColumnsCache(){return this.#n}set lightDomColumnsCache(e){this.#n=e}get originalColumnNodes(){return this.#r}set originalColumnNodes(e){this.#r=e}get lightDomTitle(){return this.#g}set lightDomTitle(e){this.#g=e}get initialColumnState(){return this.#h}set initialColumnState(e){this.#h=e}get sourcesChanged(){return this.#l}markSourcesChanged(){this.#l=!0}setGridConfig(e){this.#e=e,this.#l=!0,this.#n=void 0}getGridConfig(){return this.#e}setColumns(e){this.#t=e,this.#l=!0}getColumns(){return this.#t}setFitMode(e){this.#i=e,this.#l=!0}getFitMode(){return this.#i}merge(){const e=(this.#s.columns?.length??0)>0;if(!this.#l&&e)return;const t=this.#p();this.#l=!1,this.#o=t,Object.freeze(this.#o),this.#o.columns&&Object.freeze(this.#o.columns),this.#s=this.#f(this.#o),this.#w()}#f(e){const t={...e};return e.columns&&(t.columns=e.columns.map(e=>({...e}))),e.shell&&(t.shell={...e.shell,header:e.shell.header?{...e.shell.header}:void 0,toolPanel:e.shell.toolPanel?{...e.shell.toolPanel}:void 0,toolPanels:e.shell.toolPanels?.map(e=>({...e})),headerContents:e.shell.headerContents?.map(e=>({...e}))}),t}#w(){const e=this.#s;if(this.#m(),"number"==typeof e.rowHeight&&e.rowHeight>0&&this.#u.setRowHeight(e.rowHeight),"fixed"===e.fitMode){this.columns.forEach(e=>{null==e.width&&(e.width=80)})}this.#u.applyAnimationConfig(e)}#m(){const e=this.#s.typeDefaults;if(!e)return;const t=this.columns;for(const i of t){if(!i.type)continue;const t=e[i.type];t&&(i.renderer||i.viewRenderer||!t.renderer||(i.renderer=t.renderer),!i.format&&t.format&&(i.format=t.format),!i.editor&&t.editor&&(i.editor=t.editor),!i.editorParams&&t.editorParams&&(i.editorParams=t.editorParams))}}#p(){const e=this.#e?{...this.#e}:{},t=Array.isArray(e.columns)?[...e.columns]:[],i=(this.#n??[]).map(e=>({...e}));let n=o(t,i);this.#t&&this.#t.length&&(n=o(this.#t,i));const r=this.#u.getRows();if(0===n.length&&r.length){n=h(r).columns}return n.length&&(n.forEach(e=>{void 0===e.sortable&&(e.sortable=!0),void 0===e.resizable&&(e.resizable=!0),void 0===e.__originalWidth&&"number"==typeof e.width&&(e.__originalWidth=e.width)}),n.forEach(e=>{e.__viewTemplate&&!e.__compiledView&&(e.__compiledView=R(e.__viewTemplate.innerHTML)),e.__editorTemplate&&!e.__compiledEditor&&(e.__compiledEditor=R(e.__editorTemplate.innerHTML))}),e.columns=n),this.#i&&(e.fitMode=this.#i),e.fitMode||(e.fitMode="stretch"),this.#b(e),e.columnState&&!this.#h&&(this.#h=e.columnState),e}#b(e){e.shell=e.shell?{...e.shell}:{},e.shell.header=e.shell.header?{...e.shell.header}:{};const t=this.#u.getShellLightDomTitle();t&&(this.#g=t),this.#g&&!e.shell.header.title&&(e.shell.header.title=this.#g);const i=this.#u.getShellLightDomHeaderContent();i?.length>0&&(e.shell.header.lightDomContent=i),this.#u.getShellHasToolButtonsContainer()&&(e.shell.header.hasToolButtonsContainer=!0);const n=this.#u.getShellToolPanels();if(n.size>0){const t=Array.from(n.values());t.sort((e,t)=>(e.order??100)-(t.order??100)),e.shell.toolPanels=t}const r=this.#u.getShellHeaderContents();if(r.size>0){const t=Array.from(r.values());t.sort((e,t)=>(e.order??100)-(t.order??100)),e.shell.headerContents=t}const o=this.#u.getShellToolbarContents(),s=Array.from(o.values()),l=this.#e?.shell?.header?.toolbarContents??[],a=new Set(l.map(e=>e.id)),d=[...l];for(const c of s)a.has(c.id)||d.push(c);d.sort((e,t)=>(e.order??0)-(t.order??0)),e.shell.header.toolbarContents=d}collectState(e){const t=this.columns,i=this.#v();return{columns:t.map((t,n)=>{const r={field:t.field,order:n,visible:!t.hidden},o=t;void 0!==o.__renderedWidth?r.width=o.__renderedWidth:void 0!==t.width&&(r.width="string"==typeof t.width?parseFloat(t.width):t.width);const s=i.get(t.field);s&&(r.sort=s);for(const i of e)if(i.getColumnState){const e=i.getColumnState(t.field);e&&Object.assign(r,e)}return r})}}applyState(e,t){if(!e.columns||0===e.columns.length)return;const i=this.columns,n=new Map(e.columns.map(e=>[e.field,e])),r=i.map(e=>{const t=n.get(e.field);if(!t)return e;const i={...e};return void 0!==t.width&&(i.width=t.width,i.__renderedWidth=t.width),void 0!==t.visible&&(i.hidden=!t.visible),i});r.sort((e,t)=>(n.get(e.field)?.order??1/0)-(n.get(t.field)?.order??1/0)),this.columns=r;const o=e.columns.filter(e=>void 0!==e.sort).sort((e,t)=>(e.sort?.priority??0)-(t.sort?.priority??0));if(o.length>0){const e=o[0];e.sort&&this.#u.setSortState({field:e.field,direction:"asc"===e.sort.direction?1:-1})}else this.#u.setSortState(null);for(const s of t)if(s.applyColumnState)for(const t of e.columns)s.applyColumnState(t.field,t)}resetState(e){this.#h=void 0,this.#u.setSortState(null),this.#s=this.#f(this.#o),this.#w();for(const t of e)if(t.applyColumnState)for(const e of this.columns)t.applyColumnState(e.field,{field:e.field,order:0,visible:!0});this.requestStateChange(e)}#v(){const e=new Map,t=this.#u.getSortState();return t&&e.set(t.field,{direction:1===t.direction?"asc":"desc",priority:0}),e}requestStateChange(e){this.#c&&clearTimeout(this.#c),this.#c=setTimeout(()=>{this.#c=void 0;const t=this.collectState(e);this.#u.emit("column-state-change",t)},100)}setColumnVisible(e,t){const i=this.columns,n=i.find(t=>t.field===e);if(!n)return!1;if(!t&&n.lockVisible)return!1;if(!t){if(0===i.filter(t=>!t.hidden&&t.field!==e).length)return!1}return!!n.hidden!=!t&&(n.hidden=!t,this.#u.emit("column-visibility",{field:e,visible:t,visibleColumns:i.filter(e=>!e.hidden).map(e=>e.field)}),this.#u.clearRowPool(),this.#u.setup(),!0)}toggleColumnVisibility(e){const t=this.columns.find(t=>t.field===e);return!!t&&this.setColumnVisible(e,!!t.hidden)}isColumnVisible(e){const t=this.columns.find(t=>t.field===e);return!!t&&!t.hidden}showAllColumns(){const e=this.columns;e.some(e=>e.hidden)&&(e.forEach(e=>e.hidden=!1),this.#u.emit("column-visibility",{visibleColumns:e.map(e=>e.field)}),this.#u.clearRowPool(),this.#u.setup())}getAllColumns(){return this.columns.map(e=>({field:e.field,header:e.header||e.field,visible:!e.hidden,lockVisible:e.lockVisible,utility:!0===e.meta?.utility}))}getColumnOrder(){return this.columns.map(e=>e.field)}setColumnOrder(e){if(!e.length)return;const t=new Map(this.columns.map(e=>[e.field,e])),i=[];for(const n of e){const e=t.get(n);e&&(i.push(e),t.delete(n))}for(const n of t.values())i.push(n);this.columns=i,this.#u.renderHeader(),this.#u.updateTemplate(),this.#u.refreshVirtualWindow()}parseLightDomColumns(e){this.#n||(this.#r=Array.from(e.querySelectorAll("tbw-grid-column")),this.#n=this.#r.length?function(e){return Array.from(e.querySelectorAll("tbw-grid-column")).map(e=>{const t=e.getAttribute("field")||"";if(!t)return null;const i=e.getAttribute("type")||void 0,n={field:t,type:i&&new Set(["number","string","date","boolean","select"]).has(i)?i:void 0,header:e.getAttribute("header")||void 0,sortable:e.hasAttribute("sortable"),editable:e.hasAttribute("editable")},r=e.getAttribute("width");if(r){const e=parseFloat(r);!isNaN(e)&&/^\d+(\.\d+)?$/.test(r.trim())?n.width=e:n.width=r}const o=e.getAttribute("minWidth")||e.getAttribute("min-width");if(o){const e=parseFloat(o);isNaN(e)||(n.minWidth=e)}e.hasAttribute("resizable")&&(n.resizable=!0),e.hasAttribute("sizable")&&(n.resizable=!0);const s=e.getAttribute("editor"),l=e.getAttribute("renderer");s&&(n.__editorName=s),l&&(n.__rendererName=l);const a=e.getAttribute("options");a&&(n.options=a.split(",").map(e=>{const[t,i]=e.includes(":")?e.split(":"):[e.trim(),e.trim()];return{value:t.trim(),label:i?.trim()||t.trim()}}));const d=e.querySelector("tbw-grid-column-view"),c=e.querySelector("tbw-grid-column-editor"),h=e.querySelector("tbw-grid-column-header");d&&(n.__viewTemplate=d),c&&(n.__editorTemplate=c),h&&(n.__headerTemplate=h);const u=globalThis.DataGridElement,g=u?.getAdapters?.()??[],p=d??e,f=g.find(e=>e.canHandle(p));if(f){const e=f.createRenderer(p);e&&(n.viewRenderer=e)}const w=c??e,m=g.find(e=>e.canHandle(w));if(m){const e=m.createEditor(w);e&&(n.editor=e)}return n}).filter(e=>!!e)}(e):[])}clearLightDomCache(){this.#n=void 0}#y=new Map;registerLightDomHandler(e,t){this.#y.set(e.toLowerCase(),t)}unregisterLightDomHandler(e){this.#y.delete(e.toLowerCase())}observeLightDOM(e){this.#d&&this.#d.disconnect();const t=new Set;let i=null;const n=()=>{i=null;for(const e of t){const t=this.#y.get(e);t?.()}t.clear()};this.#d=new MutationObserver(e=>{for(const i of e){for(const e of i.addedNodes){if(e.nodeType!==Node.ELEMENT_NODE)continue;const i=e.tagName.toLowerCase();this.#y.has(i)&&t.add(i)}if("attributes"===i.type&&i.target.nodeType===Node.ELEMENT_NODE){const e=i.target.tagName.toLowerCase();this.#y.has(e)&&t.add(e)}}t.size>0&&!i&&(i=setTimeout(n,0))}),this.#d.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["title","field","header","width","hidden","id","icon","tooltip","order"]})}onChange(e){this.#a.push(e)}notifyChange(){for(const e of this.#a)e()}dispose(){this.#d?.disconnect(),this.#a=[],this.#c&&clearTimeout(this.#c)}}function _(){if("undefined"!=typeof window&&window.location){const e=window.location.hostname;if("localhost"===e||"127.0.0.1"===e||"::1"===e)return!0}return"undefined"!=typeof process&&"production"!==process.env?.NODE_ENV}function A(e){return`<span role="checkbox" aria-checked="${e}" aria-label="${e}">${e?"&#x1F5F9;":"&#9744;"}</span>`}function k(e){if(null==e||""===e)return"";if(e instanceof Date)return isNaN(e.getTime())?"":e.toLocaleDateString();if("number"==typeof e||"string"==typeof e){const t=new Date(e);return isNaN(t.getTime())?"":t.toLocaleDateString()}return""}function T(e){if(!e)return-1;const t=e.getAttribute("data-row");if(t)return parseInt(t,10);const i=e.closest(".data-grid-row");if(!i)return-1;const n=i.parentElement;if(!n)return-1;const r=n.querySelectorAll(":scope > .data-grid-row");for(let o=0;o<r.length;o++)if(r[o]===i)return o;return-1}function L(e){e&&e.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function M(e){try{if("rtl"===getComputedStyle(e).direction)return"rtl"}catch{}try{const t=e.closest?.("[dir]")?.getAttribute("dir");if("rtl"===t)return"rtl"}catch{}return"ltr"}function P(e){return"rtl"===M(e)}function H(e,t){const i=t.renderer||t.viewRenderer;if(i)return i;if(!t.type)return;const n=e.__frameworkAdapter;if(n?.getTypeDefault){const e=n.getTypeDefault(t.type);if(e?.renderer)return e.renderer}}function I(e,t){if(t.format)return t.format;if(!t.type)return;const i=e.__frameworkAdapter;if(i?.getTypeDefault){const e=i.getTypeDefault(t.type);if(e?.format)return e.format}}const D='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function z(e){return(e.__editingCellCount??0)>0}function O(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing");e.querySelectorAll(".cell.editing").forEach(e=>e.classList.remove("editing"))}const q=document.createElement("template");q.innerHTML='<div class="cell" role="gridcell" part="cell"></div>';const F=document.createElement("template");function N(){return q.content.firstElementChild.cloneNode(!0)}function G(){return F.content.firstElementChild.cloneNode(!0)}function V(e){e.__cellDisplayCache=void 0,e.__cellCacheEpoch=void 0,e.__hasSpecialColumns=void 0}function $(e,t,i,n){const r=t.children,o=e._visibleColumns,s=o.length,l=r.length,a=s<l?s:l,d=e._focusRow,c=e._focusCol,h=e._hasAfterCellRenderHook?.()??!1;let u=e.__hasSpecialColumns;if(void 0===u){u=!1;const t=e.__frameworkAdapter;for(let e=0;e<s;e++){const i=o[e];if(i.__viewTemplate||i.__compiledView||i.renderer||i.viewRenderer||i.externalView||i.format||"date"===i.type||"boolean"===i.type||i.type&&t?.getTypeDefault?.(i.type)?.renderer||i.type&&t?.getTypeDefault?.(i.type)?.format){u=!0;break}}e.__hasSpecialColumns=u}const g=String(n);if(u){for(let s=0;s<a;s++){if(o[s].externalView){if(!r[s].querySelector("[data-external-view]"))return void B(e,t,i,n)}}for(let s=0;s<a;s++){const l=o[s],a=r[s];a.getAttribute("data-row")!==g&&a.setAttribute("data-row",g);const u=d===n&&c===s;u!==a.classList.contains("cell-focus")&&(a.classList.toggle("cell-focus",u),a.setAttribute("aria-selected",String(u)));const f=l.cellClass;if(f){const e=a.getAttribute("data-dynamic-classes");e&&e.split(" ").forEach(e=>e&&a.classList.remove(e));try{const e=f(i[l.field],i,l);if(e&&e.length>0){const t=e.filter(e=>e&&"string"==typeof e);t.forEach(e=>a.classList.add(e)),a.setAttribute("data-dynamic-classes",t.join(" "))}else a.removeAttribute("data-dynamic-classes")}catch(p){console.warn(`[tbw-grid] cellClass callback error for column '${l.field}':`,p),a.removeAttribute("data-dynamic-classes")}}if(a.classList.contains("editing"))continue;const w=H(e,l);if(w){const r=i[l.field],o=w({row:i,value:r,field:l.field,column:l,cellEl:a});"string"==typeof o?(e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=y(o)):o instanceof Node?o.parentElement!==a&&(e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML="",a.appendChild(o)):null==o&&(e.__frameworkAdapter?.releaseCell?.(a),a.textContent=null==r?"":String(r)),h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:r,cellElement:a,rowElement:t});continue}if(l.__compiledView){const r=i[l.field],o=l.__compiledView({row:i,value:r,field:l.field,column:l});l.__compiledView.__blocked?a.textContent="":(a.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=y(o),E(a)),h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:r,cellElement:a,rowElement:t});continue}if(l.__viewTemplate){const r=i[l.field],o=l.__viewTemplate.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(o)?a.textContent="":(a.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=y(C(o,{row:i,value:r})),E(a)),h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:r,cellElement:a,rowElement:t});continue}if(l.externalView)continue;const m=i[l.field];let b;const v=I(e,l);if(v){try{const e=v(m,i);b=null==e?"":String(e)}catch(p){console.warn(`[tbw-grid] Format error in column '${l.field}':`,p),b=null==m?"":String(m)}a.textContent=b}else"date"===l.type?(b=k(m),a.textContent=b):"boolean"===l.type?a.innerHTML=A(!!m):(b=null==m?"":String(m),a.textContent=b);h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:m,cellElement:a,rowElement:t})}}else for(let f=0;f<a;f++){const s=r[f];if(s.classList.contains("editing"))continue;s.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(s);const l=o[f],a=i[l.field];s.textContent=null==a?"":String(a),s.getAttribute("data-row")!==g&&s.setAttribute("data-row",g);const u=d===n&&c===f;u!==s.classList.contains("cell-focus")&&(s.classList.toggle("cell-focus",u),s.setAttribute("aria-selected",String(u))),h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:f,value:a,cellElement:s,rowElement:t})}}function B(e,t,i,n){t.classList.remove("tbw-row-loading"),t.removeAttribute("aria-busy");const r=e.__frameworkAdapter;if(r?.releaseCell){const e=t.children;for(let t=e.length-1;t>=0;t--)r.releaseCell(e[t])}t.innerHTML="";const o=e._visibleColumns,s=o.length,l=e._focusRow,a=e._focusCol,d=e,c=e._hasAfterCellRenderHook?.()??!1,h=document.createDocumentFragment();for(let g=0;g<s;g++){const r=o[g],s=N();s.setAttribute("aria-colindex",String(g+1)),s.setAttribute("data-col",String(g)),s.setAttribute("data-row",String(n)),s.setAttribute("data-field",r.field),s.setAttribute("data-header",r.header??r.field),r.type&&s.setAttribute("data-type",r.type);let p=i[r.field];const f=I(e,r);if(f)try{p=f(p,i)}catch(u){console.warn(`[tbw-grid] Format error in column '${r.field}':`,u)}const w=r.__compiledView,m=r.__viewTemplate,b=H(e,r),v=r.externalView;let x=!1;if(b){const e=b({row:i,value:p,field:r.field,column:r,cellEl:s});"string"==typeof e?(s.innerHTML=y(e),x=!0):e instanceof Node?e.parentElement!==s&&(s.textContent="",s.appendChild(e)):null==e&&(s.textContent=null==p?"":String(p))}else if(v){const e=v,t=document.createElement("div");t.setAttribute("data-external-view",""),t.setAttribute("data-field",r.field),s.appendChild(t);const n={row:i,value:p,field:r.field,column:r};if(e.mount)try{e.mount({placeholder:t,context:n,spec:e})}catch(u){console.warn(`[tbw-grid] External view mount error for column '${r.field}':`,u)}else queueMicrotask(()=>{try{d.dispatchEvent(new CustomEvent("mount-external-view",{bubbles:!0,composed:!0,detail:{placeholder:t,spec:e,context:n}}))}catch(u){console.warn(`[tbw-grid] External view event dispatch error for column '${r.field}':`,u)}});t.setAttribute("data-mounted","")}else if(w){const e=w({row:i,value:p,field:r.field,column:r}),t=w.__blocked;s.innerHTML=t?"":y(e),x=!0,t&&(s.textContent="",s.setAttribute("data-blocked-template",""))}else if(m){const e=m.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(e)?(s.textContent="",s.setAttribute("data-blocked-template","")):(s.innerHTML=y(C(e,{row:i,value:p})),x=!0)}else f?s.textContent=null==p?"":String(p):"date"===r.type?s.textContent=k(p):"boolean"===r.type?s.innerHTML=A(!!p):s.textContent=null==p?"":String(p);if(x){E(s);const e=s.textContent||"";/Proxy|Reflect\.ownKeys/.test(e)&&(s.textContent=e.replace(/Proxy|Reflect\.ownKeys/g,"").trim(),/Proxy|Reflect\.ownKeys/.test(s.textContent||"")&&(s.textContent=""))}s.hasAttribute("data-blocked-template")&&(s.textContent||"").trim().length&&(s.textContent=""),r.editable?s.tabIndex=0:"boolean"===r.type&&(s.hasAttribute("tabindex")||(s.tabIndex=0)),l===n&&a===g?(s.classList.add("cell-focus"),s.setAttribute("aria-selected","true")):s.setAttribute("aria-selected","false");const R=r.cellClass;if(R)try{const e=R(i[r.field],i,r);if(e&&e.length>0){const t=e.filter(e=>e&&"string"==typeof e);t.forEach(e=>s.classList.add(e)),s.setAttribute("data-dynamic-classes",t.join(" "))}}catch(u){console.warn(`[tbw-grid] cellClass callback error for column '${r.field}':`,u)}c&&e._afterCellRender?.({row:i,rowIndex:n,column:r,colIndex:g,value:p,cellElement:s,rowElement:t}),h.appendChild(s)}t.appendChild(h)}function W(e,t,i){if(t.target?.closest(".resize-handle"))return;const n=T(i.querySelector(".cell[data-row]"));if(n<0)return;const r=e._rows[n];if(!r)return;if(e._dispatchRowClick?.(t,n,r,i))return;const o=t.target?.closest(".cell[data-col]");if(o){const i=Number(o.getAttribute("data-col"));if(!isNaN(i)){if(e._dispatchCellClick?.(t,n,i,o))return;const r=e._focusRow!==n||e._focusCol!==i;if(e._focusRow=n,e._focusCol=i,o.classList.contains("editing")){r&&(L(e._bodyEl??e),o.classList.add("cell-focus"));const t=o.querySelector(D);try{t?.focus({preventScroll:!0})}catch{}return}K(e)}}}function K(e,t){if(e._virtualization?.enabled){const{rowHeight:t,container:i,viewportEl:n}=e._virtualization,r=i,o=n?.clientHeight??r?.clientHeight??0;if(r&&o>0){const i=e._focusRow*t;i<r.scrollTop?r.scrollTop=i:i+t>r.scrollTop+o&&(r.scrollTop=i-o+t)}}const i=void 0!==e._activeEditRows&&-1!==e._activeEditRows;i||e.refreshVirtualWindow(!1),L(e._bodyEl),Array.from(e._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(e=>{e.setAttribute("aria-selected","false")});const n=e._focusRow,r=e._virtualization.start??0,o=e._virtualization.end??e._rows.length;if(n>=r&&n<o){const o=e._bodyEl.querySelectorAll(".data-grid-row")[n-r];let s=o?.children[e._focusCol];if(s&&s.classList?.contains("cell")||(s=o?.querySelector(`.cell[data-col="${e._focusCol}"]`)??o?.querySelector(".cell[data-col]")),s){s.classList.add("cell-focus"),s.setAttribute("aria-selected","true");const n=e.querySelector(".tbw-scroll-area");if(n&&s&&(!i||t?.forceHorizontalScroll))if(t?.forceScrollLeft)n.scrollLeft=0;else if(t?.forceScrollRight)n.scrollLeft=n.scrollWidth-n.clientWidth;else{const t=e._getHorizontalScrollOffsets?.(o??void 0,s)??{left:0,right:0};if(!t.skipScroll){const e=s.getBoundingClientRect(),i=n.getBoundingClientRect(),r=e.left-i.left+n.scrollLeft,o=r+e.width,l=n.scrollLeft+t.left,a=n.scrollLeft+n.clientWidth-t.right;r<l?n.scrollLeft=r-t.left:o>a&&(n.scrollLeft=o-n.clientWidth+t.right)}}if(i&&s.classList.contains("editing")){const e=s.querySelector(D);if(e&&document.activeElement!==e)try{e.focus({preventScroll:!0})}catch{}}else if(i&&!s.contains(document.activeElement)){s.hasAttribute("tabindex")||s.setAttribute("tabindex","-1");try{s.focus({preventScroll:!0})}catch{}}else if(!i){const t=e;document.activeElement!==t&&t.focus({preventScroll:!0})}}}}F.innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const U=new WeakMap;function j(e,t){const i=T(t),n=function(e){if(!e)return-1;const t=e.getAttribute("data-col");return t?parseInt(t,10):-1}(t);if(i<0||n<0)return;e._focusRow=i,e._focusCol=n,L(e._bodyEl),t.classList.add("cell-focus"),t.setAttribute("aria-selected","true");const r=t.closest("tbw-grid");r&&document.activeElement!==r&&r.focus({preventScroll:!0})}function Y(e,t,i,n){let r=null;const o=i.composedPath?.();if(r=o&&o.length>0?o[0]:i.target,r&&!t.contains(r)){const e=document.elementFromPoint(i.clientX,i.clientY);e&&(r=e)}const s=r?.closest?.("[data-col]"),l=r?.closest?.(".data-grid-row"),a=r?.closest?.(".header-row");let d,c,h,u,g,p;return s&&(d=parseInt(s.getAttribute("data-row")??"-1",10),c=parseInt(s.getAttribute("data-col")??"-1",10),d>=0&&c>=0&&(h=e._rows[d],p=e._visibleColumns[c],u=p?.field,g=h&&u?h[u]:void 0)),{type:n,row:h,rowIndex:void 0!==d&&d>=0?d:void 0,colIndex:void 0!==c&&c>=0?c:void 0,field:u,value:g,column:p,originalEvent:i,cellElement:s??void 0,rowElement:l??void 0,isHeader:!!a,cell:void 0!==d&&void 0!==c&&d>=0&&c>=0?{row:d,col:c}:void 0}}function X(e,t,i,n){t.addEventListener("keydown",t=>function(e,t){if(e._dispatchKeyDown?.(t))return;const i=e._rows.length-1,n=e._visibleColumns.length-1,r=void 0!==e._activeEditRows&&-1!==e._activeEditRows,o=e._visibleColumns[e._focusCol],s=o?.type,l=t.composedPath?.()??[],a=l.length?l[0]:t.target,d=e=>{if(!e)return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t||!!e.isContentEditable};if((!d(a)||"Home"!==t.key&&"End"!==t.key)&&!(d(a)&&("ArrowUp"===t.key||"ArrowDown"===t.key)&&"INPUT"===a.tagName&&"number"===a.type||d(a)&&("ArrowLeft"===t.key||"ArrowRight"===t.key)||d(a)&&("Enter"===t.key||"Escape"===t.key)||r&&"select"===s&&("ArrowDown"===t.key||"ArrowUp"===t.key))){switch(t.key){case"Tab":return t.preventDefault(),t.shiftKey?e._focusCol>0?e._focusCol-=1:e._focusRow>0&&("function"==typeof e.commitActiveRowEdit&&e._activeEditRows===e._focusRow&&e.commitActiveRowEdit(),e._focusRow-=1,e._focusCol=n):e._focusCol<n?e._focusCol+=1:("function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow<i&&(e._focusRow+=1,e._focusCol=0)),void K(e);case"ArrowDown":r&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=Math.min(i,e._focusRow+1),t.preventDefault();break;case"ArrowUp":r&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=Math.max(0,e._focusRow-1),t.preventDefault();break;case"ArrowRight":{const i=P(e);e._focusCol=i?Math.max(0,e._focusCol-1):Math.min(n,e._focusCol+1),t.preventDefault();break}case"ArrowLeft":{const i=P(e);e._focusCol=i?Math.min(n,e._focusCol+1):Math.max(0,e._focusCol-1),t.preventDefault();break}case"Home":return t.ctrlKey||t.metaKey?(r&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=0,e._focusCol=0):e._focusCol=0,t.preventDefault(),void K(e,{forceScrollLeft:!0});case"End":return t.ctrlKey||t.metaKey?(r&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=i,e._focusCol=n):e._focusCol=n,t.preventDefault(),void K(e,{forceScrollRight:!0});case"PageDown":e._focusRow=Math.min(i,e._focusRow+20),t.preventDefault();break;case"PageUp":e._focusRow=Math.max(0,e._focusRow-20),t.preventDefault();break;case"Enter":{const i=e._focusRow,n=e._focusCol,r=e._visibleColumns[n],o=e._rows[i],s=r?.field??"",l=s&&o?o[s]:void 0,a=e.querySelector(`[data-row="${i}"][data-col="${n}"]`),d=new CustomEvent("cell-activate",{cancelable:!0,detail:{rowIndex:i,colIndex:n,column:r,field:s,value:l,row:o,cellEl:a,trigger:"keyboard",originalEvent:t}});e.dispatchEvent(d);const c=new CustomEvent("activate-cell",{cancelable:!0,detail:{row:i,col:n}});if(e.dispatchEvent(c),d.defaultPrevented||c.defaultPrevented)return void t.preventDefault();break}default:return}K(e)}}(e,t),{signal:n}),i.addEventListener("mousedown",t=>function(e,t,i){const n=Y(e,t,i,"mousedown");e._dispatchCellMouseDown?.(n)&&U.set(e,!0)}(e,i,t),{signal:n}),document.addEventListener("mousemove",t=>function(e,t,i){if(!U.get(e))return;const n=Y(e,t,i,"mousemove");e._dispatchCellMouseMove?.(n)}(e,i,t),{signal:n}),document.addEventListener("mouseup",t=>function(e,t,i){if(!U.get(e))return;const n=Y(e,t,i,"mouseup");e._dispatchCellMouseUp?.(n),U.set(e,!1)}(e,i,t),{signal:n})}function Z(e,t){return null==e&&null==t?0:null==e?-1:null==t||e>t?1:e<t?-1:0}function Q(e,t,i){const n=i.find(e=>e.field===t.field),r=n?.sortComparator??Z,{field:o,direction:s}=t;return[...e].sort((e,t)=>r(e[o],t[o],e,t)*s)}function J(e,t,i,n){e._rows=t,e.__rowRenderEpoch++,e._rowPool.forEach(e=>e.__epoch=-1),le(e),e.refreshVirtualWindow(!0),e.dispatchEvent(new CustomEvent("sort-change",{detail:{field:i.field,direction:n}})),e.requestStateChange?.()}function ee(e,t){if(e._sortState&&e._sortState.field===t.field)if(1===e._sortState.direction)te(e,t,-1);else{e._sortState=null,e.__rowRenderEpoch++,e._rowPool.forEach(e=>e.__epoch=-1),e._rows=e.__originalOrder.slice(),le(e);const i=e._headerRowEl?.querySelectorAll('[role="columnheader"].sortable');i?.forEach(t=>{t.getAttribute("aria-sort")&&("ascending"!==t.getAttribute("aria-sort")&&"descending"!==t.getAttribute("aria-sort")||e._sortState)||t.setAttribute("aria-sort","none")}),e.refreshVirtualWindow(!0),e.dispatchEvent(new CustomEvent("sort-change",{detail:{field:t.field,direction:0}})),e.requestStateChange?.()}else e._sortState||(e.__originalOrder=e._rows.slice()),te(e,t,1)}function te(e,t,i){e._sortState={field:t.field,direction:i};const n={field:t.field,direction:i},r=e._columns,o=(e.effectiveConfig?.sortHandler??Q)(e._rows,n,r);o&&"function"==typeof o.then?o.then(n=>{J(e,n,t,i)}):J(e,o,t,i)}function ie(e,t){return!1!==e.effectiveConfig?.sortable&&!0===t.sortable}function ne(e,t){return!1!==e.effectiveConfig?.resizable&&!1!==t.resizable}function re(e,t){const i=document.createElement("span");s(i,"sort-indicator");const n=e._sortState?.field===t.field?e._sortState.direction:0,o={...r,...e.icons};return function(e,t){"string"==typeof t?e.textContent=t:t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}(i,1===n?o.sortAsc:-1===n?o.sortDesc:o.sortNone),i}function oe(e,t,i){const n=document.createElement("div");return n.className="resize-handle",n.setAttribute("aria-hidden","true"),n.addEventListener("mousedown",n=>{n.stopPropagation(),n.preventDefault(),e._resizeController.start(n,t,i)}),n.addEventListener("dblclick",i=>{i.stopPropagation(),i.preventDefault(),e._resizeController.resetColumn(t)}),n}function se(e,t,i,n){n.classList.add("sortable"),n.tabIndex=0;const r=e._sortState?.field===t.field?e._sortState.direction:0;n.setAttribute("aria-sort",0===r?"none":1===r?"ascending":"descending"),n.addEventListener("click",i=>{e._resizeController?.isResizing||e._dispatchHeaderClick?.(i,t,n)||ee(e,t)}),n.addEventListener("keydown",i=>{if("Enter"===i.key||" "===i.key){if(i.preventDefault(),e._dispatchHeaderClick?.(i,t,n))return;ee(e,t)}})}function le(e){e._headerRowEl=e.findHeaderRow();const t=e._headerRowEl;t&&(t.innerHTML="",e._visibleColumns.forEach((i,n)=>{const r=document.createElement("div");r.className="cell",s(r,"header-cell"),r.setAttribute("role","columnheader"),r.setAttribute("aria-colindex",String(n+1)),r.setAttribute("data-field",i.field),r.setAttribute("data-col",String(n)),i.type&&r.setAttribute("data-type",i.type);const o=i.header??i.field,l=e._sortState?.field===i.field?e._sortState.direction:0,a=1===l?"asc":-1===l?"desc":null;if(i.headerRenderer){const t={column:i,value:o,sortState:a,filterActive:!1,cellEl:r,renderSortIcon:()=>ie(e,i)?re(e,i):null,renderFilterButton:()=>null},s=i.headerRenderer(t);!function(e,t){if(null!=t)if("string"==typeof t){const i=document.createElement("span");for(i.innerHTML=y(t);i.firstChild;)e.appendChild(i.firstChild)}else t instanceof Node&&e.appendChild(t)}(r,s),ie(e,i)&&se(e,i,0,r),ne(e,i)&&(r.classList.add("resizable"),r.appendChild(oe(e,n,r)))}else if(i.headerLabelRenderer){const t={column:i,value:o},s=i.headerLabelRenderer(t),l=document.createElement("span");null==s?l.textContent=o:"string"==typeof s?l.innerHTML=y(s):s instanceof Node&&l.appendChild(s),r.appendChild(l),ie(e,i)&&(se(e,i,0,r),r.appendChild(re(e,i))),ne(e,i)&&(r.classList.add("resizable"),r.appendChild(oe(e,n,r)))}else if(i.__headerTemplate)Array.from(i.__headerTemplate.childNodes).forEach(e=>r.appendChild(e.cloneNode(!0))),ie(e,i)&&(se(e,i,0,r),r.appendChild(re(e,i))),ne(e,i)&&(r.classList.add("resizable"),r.appendChild(oe(e,n,r)));else{const t=document.createElement("span");t.textContent=o,r.appendChild(t),ie(e,i)&&(se(e,i,0,r),r.appendChild(re(e,i))),ne(e,i)&&(r.classList.add("resizable"),r.appendChild(oe(e,n,r)))}t.appendChild(r)}),t.querySelectorAll(".cell.sortable").forEach(e=>{e.getAttribute("aria-sort")||e.setAttribute("aria-sort","none")}),t.children.length>0?(t.setAttribute("role","row"),t.setAttribute("aria-rowindex","1")):(t.removeAttribute("role"),t.removeAttribute("aria-rowindex")))}const ae="function"==typeof requestIdleCallback;function de(e){ae?cancelIdleCallback(e):clearTimeout(e)}function ce(e,t){if(t){const i=t({size:e});if("string"==typeof i){const e=document.createElement("div");return e.innerHTML=i,e}return i}return function(e){const t=document.createElement("div");return t.className=`tbw-spinner tbw-spinner--${e}`,t.setAttribute("role","progressbar"),t.setAttribute("aria-label","Loading"),t}(e)}var he=(e=>(e[e.STYLE=1]="STYLE",e[e.VIRTUALIZATION=2]="VIRTUALIZATION",e[e.HEADER=3]="HEADER",e[e.ROWS=4]="ROWS",e[e.COLUMNS=5]="COLUMNS",e[e.FULL=6]="FULL",e))(he||{});class ue{#u;#C=0;#x=0;#E=null;#R=null;#S=null;#_=!1;constructor(e){this.#u=e}requestPhase(e,t){e>this.#C&&(this.#C=e),0===this.#x&&(this.#A(),this.#x=requestAnimationFrame(()=>this.#k()))}whenReady(){return this.#E?this.#E:Promise.resolve()}setInitialReadyResolver(e){this.#S=e}cancel(){0!==this.#x&&(cancelAnimationFrame(this.#x),this.#x=0),this.#C=0,this.#R&&(this.#R(),this.#R=null,this.#E=null)}get isPending(){return 0!==this.#C}get pendingPhase(){return this.#C}#A(){this.#E||(this.#E=new Promise(e=>{this.#R=e}))}#k(){if(this.#x=0,!this.#u.isConnected())return this.#C=0,void(this.#R&&(this.#R(),this.#R=null,this.#E=null));const e=this.#C;this.#C=0,e>=5&&this.#u.mergeConfig(),e>=4&&this.#u.processRows(),e>=5&&(this.#u.processColumns(),this.#u.updateTemplate()),e>=3&&this.#u.renderHeader(),e>=2&&this.#u.renderVirtualWindow(),e>=1&&this.#u.afterRender(),!this.#_&&this.#S&&(this.#_=!0,this.#S()),this.#R&&(this.#R(),this.#R=null,this.#E=null)}}function ge(e){let t=null,i=null,n=null,r=null;const o=n=>{if(!t)return;const r=n.clientX-t.startX,o=Math.max(40,t.startWidth+r),s=e._visibleColumns[t.colIndex];s.width=o,s.__userResized=!0,s.__renderedWidth=o,null==i&&(i=requestAnimationFrame(()=>{i=null,e.updateTemplate?.()})),e.dispatchEvent(new CustomEvent("column-resize",{detail:{field:s.field,width:o}}))};let s=!1;const l=()=>{const i=null!==t;i&&(s=!0,requestAnimationFrame(()=>{s=!1})),window.removeEventListener("mousemove",o),window.removeEventListener("mouseup",l),null!==n&&(document.documentElement.style.cursor=n,n=null),null!==r&&(document.body.style.userSelect=r,r=null),t=null,i&&e.requestStateChange&&e.requestStateChange()};return{get isResizing(){return null!==t||s},start(i,s,a){i.preventDefault();const d=e._visibleColumns[s],c="number"==typeof d?.width?d.width:void 0,h=d?.__renderedWidth??c??a.getBoundingClientRect().width;t={startX:i.clientX,colIndex:s,startWidth:h},window.addEventListener("mousemove",o),window.addEventListener("mouseup",l),null===n&&(n=document.documentElement.style.cursor),document.documentElement.style.cursor="e-resize",null===r&&(r=document.body.style.userSelect),document.body.style.userSelect="none"},resetColumn(t){const i=e._visibleColumns[t];i&&(i.__userResized=!1,i.__renderedWidth=void 0,i.width=i.__originalWidth,e.updateTemplate?.(),e.requestStateChange?.(),e.dispatchEvent(new CustomEvent("column-resize-reset",{detail:{field:i.field,width:i.width}})))},dispose(){l()}}}const pe="data-animating",fe={change:"--tbw-row-change-duration",insert:"--tbw-row-insert-duration",remove:"--tbw-row-remove-duration"},we={change:500,insert:300,remove:200};function me(e,t){const i=fe[t],n=getComputedStyle(e).getPropertyValue(i);if(n){const e=function(e){const t=e.trim().toLowerCase();return t.endsWith("ms")?parseFloat(t):t.endsWith("s")?1e3*parseFloat(t):parseFloat(t)}(n);if(!isNaN(e)&&e>0)return e}return we[t]}function be(e,t,i){if(t<0)return Promise.resolve(!1);const n=e.findRenderedRowElement?.(t);return n?new Promise(e=>{!function(e,t,i){e.removeAttribute(pe),e.offsetWidth,e.setAttribute(pe,t);const n=me(e,t);setTimeout(()=>{"remove"!==t&&e.removeAttribute(pe),i?.()},n)}(n,i,()=>e(!0))}):Promise.resolve(!1)}function ve(e,t,i){const n=document.createElement(e);if(t)for(const r in t){const e=t[r];null!=e&&n.setAttribute(r,e)}return n}function ye(e,t){const i=document.createElement("div");if(e&&(i.className=e),t)for(const n in t){const e=t[n];null!=e&&i.setAttribute(n,e)}return i}function Ce(e,t,i){const n=document.createElement("button");if(e&&(n.className=e),t)for(const r in t){const e=t[r];null!=e&&n.setAttribute(r,e)}return n}const xe=document.createElement("template");function Ee(){return xe.content.cloneNode(!0)}function Re(e){const t=document.createDocumentFragment(),i=ye(e.hasShell?"tbw-grid-root has-shell":"tbw-grid-root");if(e.hasShell&&e.shellHeader&&e.shellBody)i.appendChild(e.shellHeader),i.appendChild(e.shellBody);else{const e=ye("tbw-grid-content");e.appendChild(Ee()),i.appendChild(e)}return t.appendChild(i),t}function Se(e){return e?"string"==typeof e?e:e.outerHTML:""}function _e(e){return!!e?.header?.title||(!!e?.header?.toolbarContents?.length||(!!e?.toolPanels?.length||(!!e?.headerContents?.length||(!!e?.header?.lightDomContent?.length||!!e?.header?.hasToolButtonsContainer))))}function Ae(e,t){const i=e.querySelector("tbw-grid-header");if(!i)return;if(!t.lightDomTitle){const e=i.getAttribute("title");e&&(t.lightDomTitle=e)}const n=i.querySelectorAll("tbw-grid-header-content");n.length>0&&0===t.lightDomHeaderContent.length&&(t.lightDomHeaderContent=Array.from(n)),i.style.display="none"}function ke(e,t,i){const n=e.querySelector(":scope > tbw-grid-tool-buttons");if(!n)return;t.hasToolButtonsContainer=!0;const r="light-dom-toolbar-content";if(t.lightDomToolbarContentIds.has(r))return;const o={id:r,order:0,render:e=>{for(;n.firstChild;)e.appendChild(n.firstChild);return()=>{for(;e.firstChild;)n.appendChild(e.firstChild)}}};t.toolbarContents.set(r,o),t.lightDomToolbarContentIds.add(r),n.style.display="none"}function Te(e,t,i){e.querySelectorAll(":scope > tbw-grid-tool-panel").forEach(e=>{const n=e,r=n.getAttribute("id"),o=n.getAttribute("title");if(!r||!o)return void console.warn(`[parseLightDomToolPanels] Tool panel missing required id or title attribute: id="${r??""}", title="${o??""}"`);const s=n.getAttribute("icon")??void 0,l=n.getAttribute("tooltip")??void 0,a=parseInt(n.getAttribute("order")??"100",10);let d;const c=i?.(n);if(c)d=c;else{const e=n.innerHTML.trim();d=t=>{const i=document.createElement("div");return i.innerHTML=e,t.appendChild(i),()=>i.remove()}}const h=t.toolPanels.get(r);if(h){if(c){h.render=d,h.order=a,h.icon=s,h.tooltip=l;const e=t.panelCleanups.get(r);e&&(e(),t.panelCleanups.delete(r))}return}const u={id:r,title:o,icon:s,tooltip:l,order:a,render:d};t.toolPanels.set(r,u),t.lightDomToolPanelIds.add(r),n.style.display="none"})}function Le(e,t,i){const n=t?.header?.toolbarContents??[],r=[...i.toolbarContents.values()],o=new Set(n.map(e=>e.id)),s=[...n];for(const l of r)o.has(l.id)||s.push(l);for(const l of s){if(i.toolbarContentCleanups.has(l.id))continue;if(!l.render)continue;const t=e.querySelector(`[data-toolbar-content="${l.id}"]`);if(!t)continue;const n=l.render(t);n&&i.toolbarContentCleanups.set(l.id,n)}}function Me(e,t){const i=t.lightDomHeaderContent.length>0&&!t.lightDomContentMoved,n=t.headerContents.size>0;if(!i&&!n)return;const r=e.querySelector(".tbw-shell-content");if(!r)return;if(i){for(const e of t.lightDomHeaderContent)e.style.display="",r.appendChild(e);t.lightDomContentMoved=!0}const o=[...t.headerContents.values()].sort((e,t)=>(e.order??100)-(t.order??100));for(const s of o){const e=t.headerContentCleanups.get(s.id);e&&(e(),t.headerContentCleanups.delete(s.id));let i=r.querySelector(`[data-header-content="${s.id}"]`);i||(i=document.createElement("div"),i.setAttribute("data-header-content",s.id),r.appendChild(i));const n=s.render(i);n&&t.headerContentCleanups.set(s.id,n)}}function Pe(e,t){const i=e.querySelector("[data-panel-toggle]");i&&(i.classList.toggle("active",t.isPanelOpen),i.setAttribute("aria-pressed",String(t.isPanelOpen)))}function He(e,t){const i=e.querySelector(".tbw-tool-panel");i&&(i.classList.toggle("open",t.isPanelOpen),t.isPanelOpen||(i.style.width=""))}function Ie(e){for(const t of e.toolbarContentCleanups.values())t();e.toolbarContentCleanups.clear()}function De(e,t){let i=!1;const n={get isInitialized(){return i},setInitialized(e){i=e},get isPanelOpen(){return e.isPanelOpen},get activePanel(){return e.isPanelOpen&&e.expandedSections.size>0?[...e.expandedSections][0]:null},get expandedSections(){return[...e.expandedSections]},openToolPanel(){if(e.isPanelOpen)return;if(0===e.toolPanels.size)return void console.warn("[tbw-grid] No tool panels registered");if(e.isPanelOpen=!0,0===e.expandedSections.size&&e.toolPanels.size>0){const t=[...e.toolPanels.values()].sort((e,t)=>(e.order??100)-(t.order??100))[0];t&&e.expandedSections.add(t.id)}const i=t.getShadow();Pe(i,e),He(i,e),function(e,t,i){if(!t.isPanelOpen)return;const n=Se(i?.expand??r.expand),o=Se(i?.collapse??r.collapse);for(const[r,s]of t.toolPanels){const i=t.expandedSections.has(r),l=e.querySelector(`[data-section="${r}"]`),a=l?.querySelector(".tbw-accordion-content");if(!l||!a)continue;l.classList.toggle("expanded",i);const d=l.querySelector(".tbw-accordion-header");d&&d.setAttribute("aria-expanded",String(i));const c=l.querySelector(".tbw-accordion-chevron");if(c&&(c.innerHTML=i?o:n),i){if(0===a.children.length){const e=s.render(a);e&&t.panelCleanups.set(r,e)}}else{const e=t.panelCleanups.get(r);e&&(e(),t.panelCleanups.delete(r)),a.innerHTML=""}}}(i,e,t.getAccordionIcons()),t.emit("tool-panel-open",{sections:n.expandedSections})},closeToolPanel(){if(!e.isPanelOpen)return;for(const t of e.panelCleanups.values())t();e.panelCleanups.clear();for(const t of e.toolPanels.values())t.onClose?.();e.isPanelOpen=!1;const i=t.getShadow();Pe(i,e),He(i,e),t.emit("tool-panel-close",{})},toggleToolPanel(){e.isPanelOpen?n.closeToolPanel():n.openToolPanel()},toggleToolPanelSection(i){const n=e.toolPanels.get(i);if(!n)return void console.warn(`[tbw-grid] Tool panel section "${i}" not found`);if(1===e.toolPanels.size)return;const r=t.getShadow(),o=e.expandedSections.has(i);if(o){const t=e.panelCleanups.get(i);t&&(t(),e.panelCleanups.delete(i)),n.onClose?.(),e.expandedSections.delete(i),ze(r,i,!1)}else{for(const[t,n]of e.toolPanels)if(t!==i&&e.expandedSections.has(t)){const i=e.panelCleanups.get(t);i&&(i(),e.panelCleanups.delete(t)),n.onClose?.(),e.expandedSections.delete(t),ze(r,t,!1);const o=r.querySelector(`[data-section="${t}"] .tbw-accordion-content`);o&&(o.innerHTML="")}e.expandedSections.add(i),ze(r,i,!0),function(e,t,i){const n=t.toolPanels.get(i);if(!n?.render)return;const r=e.querySelector(`[data-section="${i}"] .tbw-accordion-content`);if(!r)return;const o=n.render(r);o&&t.panelCleanups.set(i,o)}(r,e,i)}t.emit("tool-panel-section-toggle",{id:i,expanded:!o})},getToolPanels:()=>[...e.toolPanels.values()],registerToolPanel(n){e.toolPanels.has(n.id)?console.warn(`[tbw-grid] Tool panel "${n.id}" already registered`):(e.toolPanels.set(n.id,n),i&&t.refreshShellHeader())},unregisterToolPanel(n){if(e.expandedSections.has(n)){const t=e.panelCleanups.get(n);t&&(t(),e.panelCleanups.delete(n)),e.expandedSections.delete(n)}e.toolPanels.delete(n),i&&t.refreshShellHeader()},getHeaderContents:()=>[...e.headerContents.values()],registerHeaderContent(n){e.headerContents.has(n.id)?console.warn(`[tbw-grid] Header content "${n.id}" already registered`):(e.headerContents.set(n.id,n),i&&Me(t.getShadow(),e))},unregisterHeaderContent(i){const n=e.headerContentCleanups.get(i);n&&(n(),e.headerContentCleanups.delete(i));const r=e.headerContents.get(i);r?.onDestroy?.(),e.headerContents.delete(i);const o=t.getShadow().querySelector(`[data-header-content="${i}"]`);o?.remove()},getToolbarContents:()=>[...e.toolbarContents.values()].sort((e,t)=>(e.order??0)-(t.order??0)),registerToolbarContent(n){e.toolbarContents.has(n.id)?console.warn(`[tbw-grid] Toolbar content "${n.id}" already registered`):(e.toolbarContents.set(n.id,n),i&&t.refreshShellHeader())},unregisterToolbarContent(n){const r=e.toolbarContentCleanups.get(n);r&&(r(),e.toolbarContentCleanups.delete(n));const o=e.toolbarContents.get(n);o?.onDestroy&&o.onDestroy(),e.toolbarContents.delete(n),i&&t.refreshShellHeader()}};return n}function ze(e,t,i){const n=e.querySelector(`[data-section="${t}"]`);n&&n.classList.toggle("expanded",i)}function Oe(e,t,i,n){const o=_e(t),s=[],l=["tbw-grid-header","tbw-grid-tool-buttons","tbw-grid-tool-panel","tbw-grid-column","tbw-grid-detail","tbw-grid-responsive-card"];for(const r of l){e.querySelectorAll(`:scope > ${r}`).forEach(e=>s.push(e))}e.replaceChildren();for(const r of s)e.appendChild(r);if(o){const o=Se(n?.toolPanel??r.toolPanel),s=Se(n?.expand??r.expand),l=Se(n?.collapse??r.collapse),a=[...t?.header?.toolbarContents??[]].sort((e,t)=>(e.order??0)-(t.order??0)),d=[...t?.toolPanels??[]].sort((e,t)=>(e.order??100)-(t.order??100)),c={title:t?.header?.title??void 0,hasPanels:d.length>0,isPanelOpen:i.isPanelOpen,toolPanelIcon:o,configButtons:a.map(e=>({id:e.id,hasElement:!1,hasRender:!!e.render})),apiButtons:[]},h={position:t?.toolPanel?.position??"right",isPanelOpen:i.isPanelOpen,expandIcon:s,collapseIcon:l,panels:d.map(e=>({id:e.id,title:e.title,icon:Se(e.icon),isExpanded:i.expandedSections.has(e.id)}))},u=Re({hasShell:!0,shellHeader:function(e){const t=ye("tbw-shell-header",{part:"shell-header",role:"presentation"});if(e.title){const i=ye("tbw-shell-title");i.textContent=e.title,t.appendChild(i)}const i=ye("tbw-shell-content",{part:"shell-content",role:"presentation","data-light-dom-header-content":""});t.appendChild(i);const n=ye("tbw-shell-toolbar",{part:"shell-toolbar",role:"presentation"});for(const r of e.configButtons)r.hasRender&&n.appendChild(ye("tbw-toolbar-content-slot",{"data-toolbar-content":r.id}));for(const r of e.apiButtons)r.hasRender&&n.appendChild(ye("tbw-toolbar-content-slot",{"data-toolbar-content":r.id}));if((e.configButtons.some(e=>e.hasRender)||e.apiButtons.some(e=>e.hasRender))&&e.hasPanels&&n.appendChild(ye("tbw-toolbar-separator")),e.hasPanels){const t=Ce(e.isPanelOpen?"tbw-toolbar-btn active":"tbw-toolbar-btn",{"data-panel-toggle":"",title:"Settings","aria-label":"Toggle settings panel","aria-pressed":String(e.isPanelOpen),"aria-controls":"tbw-tool-panel"});t.innerHTML=e.toolPanelIcon,n.appendChild(t)}return t.appendChild(n),t}(c),shellBody:function(e){const t=ye("tbw-shell-body"),i=e.panels.length>0,n=1===e.panels.length,r=ye("tbw-grid-content");r.appendChild(Ee());let o=null;if(i){o=ve("aside",{class:e.isPanelOpen?"tbw-tool-panel open":"tbw-tool-panel",part:"tool-panel","data-position":e.position,role:"presentation",id:"tbw-tool-panel"});const t="left"===e.position?"right":"left";o.appendChild(ye("tbw-tool-panel-resize",{"data-resize-handle":"","data-handle-position":t,"aria-hidden":"true"}));const i=ye("tbw-tool-panel-content",{role:"presentation"}),r=ye("tbw-accordion");for(const o of e.panels){const t=ye(`tbw-accordion-section${o.isExpanded?" expanded":""}${n?" single":""}`,{"data-section":o.id}),i=Ce("tbw-accordion-header",{"aria-expanded":String(o.isExpanded),"aria-controls":`tbw-section-${o.id}`});if(n&&i.setAttribute("aria-disabled","true"),o.icon){const e=ve("span",{class:"tbw-accordion-icon"});e.innerHTML=o.icon,i.appendChild(e)}const s=ve("span",{class:"tbw-accordion-title"});if(s.textContent=o.title,i.appendChild(s),!n){const t=ve("span",{class:"tbw-accordion-chevron"});t.innerHTML=o.isExpanded?e.collapseIcon:e.expandIcon,i.appendChild(t)}t.appendChild(i),t.appendChild(ye("tbw-accordion-content",{id:`tbw-section-${o.id}`,role:"presentation"})),r.appendChild(t)}i.appendChild(r),o.appendChild(i)}return"left"===e.position&&o?(t.appendChild(o),t.appendChild(r)):(t.appendChild(r),o&&t.appendChild(o)),t}(h)});e.appendChild(u)}else{const t=Re({hasShell:!1});e.appendChild(t)}return o}xe.innerHTML='\n <div class="tbw-scroll-area">\n <div class="rows-body-wrapper">\n <div class="rows-body" role="grid">\n <div class="header" role="rowgroup">\n <div class="header-row" role="row" part="header-row"></div>\n </div>\n <div class="rows-container" role="presentation">\n <div class="rows-viewport" role="presentation">\n <div class="rows"></div>\n </div>\n </div>\n </div>\n </div>\n </div>\n <div class="faux-vscroll">\n <div class="faux-vscroll-spacer"></div>\n </div>\n';const qe="tbw-grid-styles";let Fe="";const Ne=new Map;function Ge(){const e=function(){let e=document.getElementById(qe);return e||(e=document.createElement("style"),e.id=qe,e.setAttribute("data-tbw-grid","true"),document.head.appendChild(e)),e}(),t=Array.from(Ne.values()).join("\n");e.textContent=`${Fe}\n\n/* Plugin Styles */\n${t}`}async function Ve(e){if(Fe)return;if("string"==typeof e&&e.length>0)return Fe=e,void Ge();await new Promise(e=>setTimeout(e,50));const t=function(){try{for(const e of Array.from(document.styleSheets))try{const t=Array.from(e.cssRules||[]).map(e=>e.cssText).join("\n");if(t.includes(".tbw-grid-root")&&t.includes("tbw-grid"))return t}catch{continue}}catch(e){console.warn("[tbw-grid] Failed to extract grid.css from document stylesheets:",e)}return null}();t?(Fe=t,Ge()):"undefined"!=typeof process&&"test"===process.env?.NODE_ENV||console.warn("[tbw-grid] Could not find grid.css in document.styleSheets. Grid styling will not work.","Available stylesheets:",Array.from(document.styleSheets).map(e=>e.href||"(inline)"))}function $e(e){e.momentumRaf&&(cancelAnimationFrame(e.momentumRaf),e.momentumRaf=0)}function Be(e,t){(Math.abs(e.velocityY)>.1||Math.abs(e.velocityX)>.1)&&function(e,t){const i=.95,n=.01,r=()=>{e.velocityY*=i,e.velocityX*=i;const o=16*e.velocityY,s=16*e.velocityX;Math.abs(e.velocityY)>n&&(t.fauxScrollbar.scrollTop+=o),Math.abs(e.velocityX)>n&&t.scrollArea&&(t.scrollArea.scrollLeft+=s),Math.abs(e.velocityY)>n||Math.abs(e.velocityX)>n?e.momentumRaf=requestAnimationFrame(r):e.momentumRaf=0};e.momentumRaf=requestAnimationFrame(r)}(e,t),function(e){e.startY=null,e.startX=null,e.scrollTop=null,e.scrollLeft=null,e.lastY=null,e.lastX=null,e.lastTime=null}(e)}function We(e,t,i,n){e.addEventListener("touchstart",e=>function(e,t,i){if(1!==e.touches.length)return;$e(t);const n=e.touches[0];t.startY=n.clientY,t.startX=n.clientX,t.lastY=n.clientY,t.lastX=n.clientX,t.lastTime=performance.now(),t.scrollTop=i.fauxScrollbar.scrollTop,t.scrollLeft=i.scrollArea?.scrollLeft??0,t.velocityY=0,t.velocityX=0}(e,t,i),{passive:!0,signal:n}),e.addEventListener("touchmove",e=>{const n=function(e,t,i){if(1!==e.touches.length||null===t.startY||null===t.startX||null===t.scrollTop||null===t.scrollLeft)return!1;const n=e.touches[0],r=n.clientY,o=n.clientX,s=performance.now(),l=t.startY-r,a=t.startX-o;if(null!==t.lastTime&&null!==t.lastY&&null!==t.lastX){const e=s-t.lastTime;e>0&&(t.velocityY=(t.lastY-r)/e,t.velocityX=(t.lastX-o)/e)}t.lastY=r,t.lastX=o,t.lastTime=s;const{scrollTop:d,scrollHeight:c,clientHeight:h}=i.fauxScrollbar,u=l>0&&d<c-h||l<0&&d>0;let g=!1;if(i.scrollArea){const{scrollLeft:e,scrollWidth:t,clientWidth:n}=i.scrollArea;g=a>0&&e<t-n||a<0&&e>0}return u&&(i.fauxScrollbar.scrollTop=t.scrollTop+l),g&&i.scrollArea&&(i.scrollArea.scrollLeft=t.scrollLeft+a),u||g}(e,t,i);n&&e.preventDefault()},{passive:!1,signal:n}),e.addEventListener("touchend",()=>Be(t,i),{passive:!0,signal:n})}const Ke=[{property:"editable",pluginName:"editing",level:"column",description:'the "editable" column property',isUsed:e=>!0===e},{property:"editor",pluginName:"editing",level:"column",description:'the "editor" column property'},{property:"editorParams",pluginName:"editing",level:"column",description:'the "editorParams" column property'},{property:"group",pluginName:"groupingColumns",level:"column",description:'the "group" column property'},{property:"pinned",pluginName:"pinnedColumns",level:"column",description:'the "pinned" column property',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e},{property:"sticky",pluginName:"pinnedColumns",level:"column",description:'the "sticky" column property (deprecated, use "pinned")',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e}],Ue=[{property:"columnGroups",pluginName:"groupingColumns",level:"config",description:'the "columnGroups" config property',isUsed:e=>Array.isArray(e)&&e.length>0}];function je(e){return`import { ${Ye(e)}Plugin } from '@toolbox-web/grid/plugins/${t=e,t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}';`;var t}function Ye(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Xe(e,t){return e.some(e=>e.name===t)}function Ze(e,t){return e&&"object"==typeof e?"__rowCacheKey"in e?e.__rowCacheKey:"rowId"in e&&null!=e.rowId?`id:${e.rowId}`:t?`id:${t(e)}`:e:e}function Qe(e,t,i){const n=Ze(t,i);return"string"==typeof n?e.byKey.get(n):n&&"object"==typeof n?e.byRef.get(n):void 0}function Je(e,t,i){if(t<0||t>=e.length)return;const n=e[t],r=i-n.height;if(0!==r){n.height=i,n.measured=!0;for(let i=t+1;i<e.length;i++)e[i].offset+=r}}function et(e,t){if(0===e.length)return-1;if(t<=0)return 0;let i=0,n=e.length-1;for(;i<=n;){const r=Math.floor((i+n)/2),o=e[r],s=o.offset+o.height;if(t<o.offset)n=r-1;else{if(!(t>=s))return r;i=r+1}}return Math.max(0,Math.min(i,e.length-1))}function tt(e,t){const{positionCache:i,heightCache:n,rows:r,start:o,end:s,getPluginHeight:l,getRowId:a}=e;let d=!1;t.forEach(e=>{const t=e.dataset.rowIndex;if(!t)return;const c=parseInt(t,10);if(c<o||c>=s||c>=r.length)return;const h=r[c],u=l?.(h,c);if(void 0!==u){const e=i[c];return void((!e.measured||Math.abs(e.height-u)>1)&&(Je(i,c,u),d=!0))}const g=e.offsetHeight;if(g>0){const e=i[c];(!e.measured||Math.abs(e.height-g)>1)&&(Je(i,c,g),function(e,t,i,n){const r=Ze(t,n);"string"==typeof r?e.byKey.set(r,i):r&&"object"==typeof r&&e.byRef.set(r,i)}(n,h,g,a),d=!0)}});const c=d?function(e){let t=0;for(const i of e)i.measured&&t++;return t}(i):0,h=d?function(e,t){let i=0,n=0;for(const r of e)r.measured&&(i+=r.height,n++);return n>0?i/n:t}(i,e.defaultHeight):0;return{hasChanges:d,measuredCount:c,averageHeight:h}}class it{constructor(e){this.grid=e}plugins=[];getPlugins(){return this.plugins}pluginMap=new Map;cellRenderers=new Map;headerRenderers=new Map;cellEditors=new Map;eventListeners=new Map;queryHandlers=new Map;static deprecationWarned=new WeakSet;attachAll(e){for(const t of e)this.attach(t)}attach(e){if(function(e,t){const i=e.name,n=e.constructor.dependencies??[];for(const r of n){const e=r.name,n=r.required??!0,o=r.reason;if(!t.some(t=>t.name===e)){const t=o??`${Ye(i)}Plugin requires ${Ye(e)}Plugin`,r=je(e);if(n)throw new Error(`[tbw-grid] Plugin dependency error:\n\n${t}.\n\n → Add the plugin to your gridConfig.plugins array BEFORE ${Ye(i)}Plugin:\n ${r}\n plugins: [new ${Ye(e)}Plugin(), new ${Ye(i)}Plugin()]`);console.info(`[tbw-grid] ${Ye(i)}Plugin: Optional "${e}" plugin not found. Some features may be unavailable.`)}}}(e,this.plugins),this.pluginMap.set(e.constructor,e),this.plugins.push(e),e.cellRenderers)for(const[t,i]of Object.entries(e.cellRenderers))this.cellRenderers.set(t,i);if(e.headerRenderers)for(const[t,i]of Object.entries(e.headerRenderers))this.headerRenderers.set(t,i);if(e.cellEditors)for(const[t,i]of Object.entries(e.cellEditors))this.cellEditors.set(t,i);this.registerQueryHandlers(e),this.warnDeprecatedHooks(e),e.attach(this.grid);for(const t of this.plugins)t!==e&&t.onPluginAttached&&t.onPluginAttached(e.name,e)}registerQueryHandlers(e){const t=e.constructor.manifest;if(t?.queries)for(const i of t.queries){let t=this.queryHandlers.get(i.type);t||(t=new Set,this.queryHandlers.set(i.type,t)),t.add(e)}}warnDeprecatedHooks(e){const t=e.constructor;if(it.deprecationWarned.has(t))return;if(!_())return;const i="function"==typeof e.getExtraHeight||"function"==typeof e.getExtraHeightBefore,n="function"==typeof e.getRowHeight;i&&!n&&(it.deprecationWarned.add(t),console.warn(`[tbw-grid] Deprecation warning: "${e.name}" uses getExtraHeight() / getExtraHeightBefore() which are deprecated and will be removed in v3.0.\n → Migrate to getRowHeight(row, index) for better variable row height support.\n → See: https://toolbox-web.dev/docs/grid/plugins/migration#row-height-hooks`))}unregisterQueryHandlers(e){for(const[t,i]of this.queryHandlers)i.delete(e),0===i.size&&this.queryHandlers.delete(t)}detachAll(){for(const e of this.plugins)for(const t of this.plugins)t!==e&&t.onPluginDetached&&t.onPluginDetached(e.name);for(let e=this.plugins.length-1;e>=0;e--){const t=this.plugins[e];this.unsubscribeAll(t),this.unregisterQueryHandlers(t),t.detach()}this.plugins=[],this.pluginMap.clear(),this.cellRenderers.clear(),this.headerRenderers.clear(),this.cellEditors.clear(),this.eventListeners.clear(),this.queryHandlers.clear()}getPlugin(e){return this.pluginMap.get(e)}getPluginByName(e){return this.plugins.find(t=>t.name===e)}hasPlugin(e){return this.pluginMap.has(e)}getAll(){return this.plugins}getRegisteredPluginNames(){return this.plugins.map(e=>e.name)}getCellRenderer(e){return this.cellRenderers.get(e)}getHeaderRenderer(e){return this.headerRenderers.get(e)}getCellEditor(e){return this.cellEditors.get(e)}getPluginStyles(){return this.plugins.filter(e=>e.styles).map(e=>({name:e.name,styles:e.styles}))}processRows(e){let t=[...e];for(const i of this.plugins)i.processRows&&(t=i.processRows(t));return t}processColumns(e){let t=[...e];for(const i of this.plugins)i.processColumns&&(t=i.processColumns(t));return t}beforeRender(){for(const e of this.plugins)e.beforeRender?.()}afterRender(){for(const e of this.plugins)e.afterRender?.()}afterCellRender(e){for(const t of this.plugins)t.afterCellRender?.(e)}hasAfterCellRenderHook(){return this.plugins.some(e=>"function"==typeof e.afterCellRender)}afterRowRender(e){for(const t of this.plugins)t.afterRowRender?.(e)}hasAfterRowRenderHook(){return this.plugins.some(e=>"function"==typeof e.afterRowRender)}onScrollRender(){for(const e of this.plugins)e.onScrollRender?.()}getExtraHeight(){let e=0;for(const t of this.plugins)"function"==typeof t.getExtraHeight&&(e+=t.getExtraHeight());return e}hasExtraHeight(){for(const e of this.plugins)if("function"==typeof e.getExtraHeight&&e.getExtraHeight()>0)return!0;return!1}getExtraHeightBefore(e){let t=0;for(const i of this.plugins)"function"==typeof i.getExtraHeightBefore&&(t+=i.getExtraHeightBefore(e));return t}getRowHeight(e,t){for(const i of this.plugins)if("function"==typeof i.getRowHeight){const n=i.getRowHeight(e,t);if(void 0!==n)return n}}hasRowHeightPlugin(){for(const e of this.plugins)if("function"==typeof e.getRowHeight)return!0;return!1}adjustVirtualStart(e,t,i){let n=e;for(const r of this.plugins)if("function"==typeof r.adjustVirtualStart){const o=r.adjustVirtualStart(e,t,i);o<n&&(n=o)}return n}renderRow(e,t,i){for(const n of this.plugins)if(n.renderRow?.(e,t,i))return!0;return!1}queryPlugins(e){const t=[],i=this.queryHandlers.get(e.type);if(i&&i.size>0){for(const n of i){const i=n.handleQuery?.(e)??n.onPluginQuery?.(e);void 0!==i&&t.push(i)}return t}for(const n of this.plugins){const i=n.handleQuery?.(e)??n.onPluginQuery?.(e);void 0!==i&&t.push(i)}return t}subscribe(e,t,i){let n=this.eventListeners.get(t);n||(n=new Map,this.eventListeners.set(t,n)),n.set(e,i)}unsubscribe(e,t){const i=this.eventListeners.get(t);i&&(i.delete(e),0===i.size&&this.eventListeners.delete(t))}unsubscribeAll(e){for(const[t,i]of this.eventListeners)i.delete(e),0===i.size&&this.eventListeners.delete(t)}emitPluginEvent(e,t){const i=this.eventListeners.get(e);if(i)for(const r of i.values())try{r(t)}catch(n){console.error(`[tbw-grid] Error in plugin event handler for "${e}":`,n)}}onKeyDown(e){for(const t of this.plugins)if(t.onKeyDown?.(e))return!0;return!1}onCellClick(e){for(const t of this.plugins)if(t.onCellClick?.(e))return!0;return!1}onRowClick(e){for(const t of this.plugins)if(t.onRowClick?.(e))return!0;return!1}onHeaderClick(e){for(const t of this.plugins)if(t.onHeaderClick?.(e))return!0;return!1}onScroll(e){for(const t of this.plugins)t.onScroll?.(e)}onCellMouseDown(e){for(const t of this.plugins)if(t.onCellMouseDown?.(e))return!0;return!1}onCellMouseMove(e){for(const t of this.plugins)if(t.onCellMouseMove?.(e))return!0;return!1}onCellMouseUp(e){for(const t of this.plugins)if(t.onCellMouseUp?.(e))return!0;return!1}getHorizontalScrollOffsets(e,t){let i=0,n=0,r=!1;for(const o of this.plugins){const s=o.getHorizontalScrollOffsets?.(e,t);s&&(i+=s.left,n+=s.right,s.skipScroll&&(r=!0))}return{left:i,right:n,skipScroll:r}}getToolPanels(){const e=[];for(const t of this.plugins){const i=t.getToolPanel?.();i&&e.push({plugin:t,panel:i})}return e.sort((e,t)=>(e.panel.order??0)-(t.panel.order??0))}getHeaderContents(){const e=[];for(const t of this.plugins){const i=t.getHeaderContent?.();i&&e.push({plugin:t,content:i})}return e.sort((e,t)=>(e.content.order??0)-(t.content.order??0))}}class nt extends HTMLElement{static tagName="tbw-grid";static version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";static#T=0;static adapters=[];static registerAdapter(e){this.adapters.push(e)}static getAdapters(){return this.adapters}static clearAdapters(){this.adapters=[]}static get observedAttributes(){return["rows","columns","grid-config","fit-mode","loading"]}get#L(){return this}#M=!1;#E;#R;#P=[];get#s(){return this.#H?.effective??{}}#I=!1;#D=!1;#z={rows:!1,columns:!1,gridConfig:!1,fitMode:!1};#O;#q=0;#F=null;#N=!1;#G=!1;#V=0;#$;#B={startY:null,startX:null,scrollTop:null,scrollLeft:null,lastY:null,lastX:null,lastTime:null,velocityY:0,velocityX:0,momentumRaf:0};#W;#K;#U;#j;#Y={scrollTop:0,scrollLeft:0,scrollHeight:0,scrollWidth:0,clientHeight:0,clientWidth:0};#X;#Z;#Q=!1;#J;#ee;#h;#H;#te=function(){return{toolPanels:new Map,headerContents:new Map,toolbarContents:new Map,hasToolButtonsContainer:!1,lightDomHeaderContent:[],lightDomTitle:null,lightDomToolPanelIds:new Set,lightDomToolbarContentIds:new Set,apiToolPanelIds:new Set,isPanelOpen:!1,expandedSections:new Set,headerContentCleanups:new Map,panelCleanups:new Map,toolbarContentCleanups:new Map,lightDomContentMoved:!1}}();#ie;#ne;#re;#oe=!1;#se=new Set;#le=new Map;#ae;#de=new Map;_rows=[];#ce=[];get _columns(){return this.#s.columns??[]}set _columns(e){this.#s.columns=e}get _visibleColumns(){return this._columns.filter(e=>!e.hidden)}_headerRowEl;_bodyEl;_rowPool=[];_resizeController;_virtualization={enabled:!0,rowHeight:28,bypassThreshold:24,start:0,end:0,container:null,viewportEl:null,totalHeightEl:null,positionCache:null,heightCache:{byKey:new Map,byRef:new WeakMap},averageHeight:28,measuredCount:0,variableHeights:!1,cachedViewportHeight:0,cachedFauxHeight:0,cachedScrollAreaHeight:0,scrollAreaEl:null};_focusRow=0;_focusCol=0;_restoreFocusAfterRender=!1;_sortState=null;_gridTemplate="";__rowRenderEpoch=0;__didInitialAutoSize=!1;get __lightDomColumnsCache(){return this.#H?.lightDomColumnsCache}set __lightDomColumnsCache(e){this.#H&&(this.#H.lightDomColumnsCache=e)}get __originalColumnNodes(){return this.#H?.originalColumnNodes}set __originalColumnNodes(e){this.#H&&(this.#H.originalColumnNodes=e)}__originalOrder=[];__frameworkAdapter;__rowsBodyEl=null;get rows(){return this._rows}set rows(e){const t=this.#P;this.#P=e,t!==e&&this.#he("rows")}get sourceRows(){return this.#P}get columns(){return[...this._columns]}set columns(e){const t=this.#H?.getColumns();this.#H?.setColumns(e),t!==e&&this.#he("columns")}get gridConfig(){return this.#s}set gridConfig(e){const t=this.#H?.getGridConfig();this.#H?.setGridConfig(e),t!==e&&(this.#H.clearLightDomCache(),this.#he("gridConfig"))}get fitMode(){return this.#s.fitMode??"stretch"}set fitMode(e){const t=this.#H?.getFitMode();this.#H?.setFitMode(e),t!==e&&this.#he("fitMode")}get loading(){return this.#oe}set loading(e){const t=this.#oe;this.#oe=e,e?this.setAttribute("loading",""):this.removeAttribute("loading"),t!==e&&this.#ue()}setRowLoading(e,t){const i=this.#se.has(e);t?this.#se.add(e):this.#se.delete(e),i!==t&&this.#ge(e,t)}setCellLoading(e,t,i){let n=this.#le.get(e);const r=n?.has(t)??!1;i?(n||(n=new Set,this.#le.set(e,n)),n.add(t)):(n?.delete(t),0===n?.size&&this.#le.delete(e)),r!==i&&this.#pe(e,t,i)}isRowLoading(e){return this.#se.has(e)}isCellLoading(e,t){return this.#le.get(e)?.has(t)??!1}clearAllLoading(){this.loading=!1;for(const e of this.#se)this.#ge(e,!1);this.#se.clear();for(const[e,t]of this.#le)for(const i of t)this.#pe(e,i,!1);this.#le.clear()}get effectiveConfig(){return this.#s}get disconnectSignal(){return this.#W||(this.#W=new AbortController),this.#W.signal}constructor(){super(),this.#fe(),this.#E=new Promise(e=>this.#R=e),this.#O=new ue({mergeConfig:()=>{this.#H.parseLightDomColumns(this),this.#H.merge(),this.#we(),function(e,t){const i=Ke,n=Ue,r=new Map;function o(e,t,i,n,o=!1){r.has(e)||r.set(e,{description:t,importHint:i,fields:[],isConfigProperty:o});const s=r.get(e);s.fields.includes(n)||s.fields.push(n)}for(const l of n){const i=e[l.property];(l.isUsed?l.isUsed(i):void 0!==i)&&!Xe(t,l.pluginName)&&o(l.pluginName,l.description,je(l.pluginName),l.property,!0)}const s=e.columns;if(s&&s.length>0)for(const l of s)for(const e of i){const i=l[e.property];if((e.isUsed?e.isUsed(i):void 0!==i)&&!Xe(t,e.pluginName)){const t=l.field||"<unknown>";o(e.pluginName,e.description,je(e.pluginName),t)}}if(r.size>0){const e=[];for(const[t,{description:i,importHint:n,fields:o,isConfigProperty:s}]of r)if(s)e.push(`Config uses ${i}, but the required plugin is not loaded.\n → Add the plugin to your gridConfig.plugins array:\n ${n}\n plugins: [new ${Ye(t)}Plugin(), ...]`);else{const r=o.slice(0,3).join(", ")+(o.length>3?`, ... (${o.length} total)`:"");e.push(`Column(s) [${r}] use ${i}, but the required plugin is not loaded.\n → Add the plugin to your gridConfig.plugins array:\n ${n}\n plugins: [new ${Ye(t)}Plugin(), ...]`)}throw new Error(`[tbw-grid] Configuration error:\n\n${e.join("\n\n")}\n\nThis validation helps catch misconfigurations early. The properties listed above require their respective plugins to function.`)}}(this.#s,this.#X?.getPlugins()??[]),function(e){const t=[],i=[];for(const n of e){const e=n.constructor.manifest;if(e?.configRules)for(const r of e.configRules){const e=n.config;if(r.check(e)){const e=`[tbw-grid:${Ye(n.name)}Plugin] Configuration warning: ${r.message}`;"error"===r.severity?t.push(e):i.push(e)}}}if(i.length>0&&_())for(const n of i)console.warn(n);if(t.length>0)throw new Error(`[tbw-grid] Configuration error:\n\n${t.join("\n\n")}`)}(this.#X?.getPlugins()??[]),function(e){if(!_())return;const t=new Set(e.map(e=>e.name)),i=new Set;for(const n of e){const e=n.constructor.manifest;if(e?.incompatibleWith)for(const r of e.incompatibleWith)if(t.has(r.name)){const e=[n.name,r.name].sort().join("↔");if(i.has(e))continue;i.add(e),console.warn(`[tbw-grid] Plugin incompatibility warning:\n\n${Ye(n.name)}Plugin and ${Ye(r.name)}Plugin are both loaded, but they are currently incompatible.\n\n → ${r.reason}\n\n Consider removing one of these plugins to avoid unexpected behavior.`)}}}(this.#X?.getPlugins()??[]),this.#me(),this.#ce=[...this._columns]},processColumns:()=>this.#be(),processRows:()=>this.#ve(),renderHeader:()=>le(this),updateTemplate:()=>c(this),renderVirtualWindow:()=>this.refreshVirtualWindow(!0,!0),afterRender:()=>{this.#X?.afterRender(),this._virtualization.enabled&&this._virtualization.totalHeightEl&&queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const e=this.#ye(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`});"fixed"!==this.#s.fitMode||this.__didInitialAutoSize||(this.__didInitialAutoSize=!0,l(this)),this._restoreFocusAfterRender&&(this._restoreFocusAfterRender=!1,K(this)),this._virtualization.enabled&&!this.#Ce&&this.#xe(),this.#G&&(this.#G=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.#Ee()})})),this.#oe&&this.#ue()},isConnected:()=>this.isConnected&&this.#I}),this.#O.setInitialReadyResolver(()=>this.#R?.()),this.#ie=De(this.#te,{getShadow:()=>this.#L,getShellConfig:()=>this.#s?.shell,getAccordionIcons:()=>({expand:this.#s?.icons?.expand??r.expand,collapse:this.#s?.icons?.collapse??r.collapse}),emit:(e,t)=>this.#Re(e,t),refreshShellHeader:()=>this.refreshShellHeader()}),this.#H=new S({getRows:()=>this.#P,getSortState:()=>this._sortState,setSortState:e=>{this._sortState=e},onConfigChange:()=>{this.#O.requestPhase(he.FULL,"configChange")},emit:(e,t)=>this.#Re(e,t),clearRowPool:()=>{this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++},setup:()=>this.#Se(),renderHeader:()=>le(this),updateTemplate:()=>c(this),refreshVirtualWindow:()=>this.#O.requestPhase(he.VIRTUALIZATION,"configManager"),getVirtualization:()=>this._virtualization,setRowHeight:e=>{this._virtualization.rowHeight=e},applyAnimationConfig:e=>this.#_e(e),getShellLightDomTitle:()=>this.#te.lightDomTitle,getShellToolPanels:()=>this.#te.toolPanels,getShellHeaderContents:()=>this.#te.headerContents,getShellToolbarContents:()=>this.#te.toolbarContents,getShellLightDomHeaderContent:()=>this.#te.lightDomHeaderContent,getShellHasToolButtonsContainer:()=>this.#te.hasToolButtonsContainer})}async#fe(){await Ve('@layer tbw-base, tbw-plugins, tbw-theme;\n\n@layer tbw-base{tbw-grid{--tbw-base-icon-size: 1em;--tbw-base-radius: .25em;--tbw-font-size: 1em;--tbw-font-size-sm: .9285em;--tbw-font-size-xs: .7857em;--tbw-font-size-2xs: .7142em;--tbw-spacing-xs: .25em;--tbw-spacing-sm: .375em;--tbw-spacing-md: .5em;--tbw-spacing-lg: .75em;--tbw-spacing-xl: 1em;--tbw-icon-size: var(--tbw-base-icon-size);--tbw-icon-size-sm: .875em;--tbw-checkbox-size: var(--tbw-base-icon-size);--tbw-toggle-size: 1.25em;--tbw-border-radius: var(--tbw-base-radius);--tbw-color-bg: transparent;--tbw-color-panel-bg: light-dark(#eeeeee, #222222);--tbw-color-fg: light-dark(#222222, #eeeeee);--tbw-color-fg-muted: light-dark(#555555, #aaaaaa);--tbw-color-accent: light-dark(#3b82f6, #3b82f6);--tbw-color-accent-fg: light-dark(#ffffff, #000000);--tbw-color-success: light-dark(hsl(122, 39%, 40%), hsl(122, 39%, 49%));--tbw-color-warning: light-dark(hsl(38, 92%, 50%), hsl(38, 92%, 50%));--tbw-color-error: light-dark(hsl(0, 65%, 51%), hsl(0, 65%, 55%));--tbw-color-danger: var(--tbw-color-error);--tbw-color-selection: light-dark(#fff7d6, #333333);--tbw-color-row-alt: var(--tbw-color-bg);--tbw-color-row-hover: light-dark(#f0f6ff, #1c1c1c);--tbw-color-header-bg: color-mix(in hsl, var(--tbw-color-panel-bg) 85%, var(--tbw-color-fg));--tbw-color-header-fg: color-mix(in hsl, var(--tbw-color-fg) 75%, var(--tbw-color-panel-bg));--tbw-color-border: light-dark(#d0d0d4, #454545);--tbw-color-border-strong: light-dark(#777777, #666666);--tbw-color-border-cell: var(--tbw-color-border);--tbw-color-border-header: var(--tbw-color-border);--tbw-color-shadow: light-dark(rgba(0, 0, 0, .1), rgba(0, 0, 0, .3));--tbw-font-family: inherit;--tbw-font-size-header: var(--tbw-font-size);--tbw-font-weight-header: bold;--tbw-cell-padding-header: var(--tbw-spacing-xs) var(--tbw-spacing-md);--tbw-cell-padding-v: var(--tbw-spacing-xs);--tbw-cell-padding-h: var(--tbw-spacing-md);--tbw-cell-padding: var(--tbw-cell-padding-v) var(--tbw-cell-padding-h);--tbw-cell-padding-input: var(--tbw-spacing-xs) var(--tbw-spacing-sm);--tbw-row-height: 1.75em;--tbw-header-height: 1.875em;--tbw-cell-white-space: nowrap;--tbw-border-width: 1px;--tbw-border-style: solid;--tbw-border-input: var(--tbw-border-width) var(--tbw-border-style) var(--tbw-color-border-strong);--tbw-border-header: var(--tbw-border-width) var(--tbw-border-style) var(--tbw-color-border-header);--tbw-row-divider: var(--tbw-border-width) var(--tbw-border-style) var(--tbw-color-border-cell);--tbw-row-hover-outline: 0;--tbw-color-active-row-bg: var(--tbw-color-selection);--tbw-active-row-outline: 0;--tbw-focus-outline-width: 2px;--tbw-focus-outline: var(--tbw-focus-outline-width) var(--tbw-border-style) var(--tbw-color-accent);--tbw-focus-outline-offset: -2px;--tbw-focus-background: rgba(from var(--tbw-color-accent) r g b / 12%);--tbw-range-border-color: var(--tbw-color-accent);--tbw-range-selection-bg: rgba(from var(--tbw-range-border-color) r g b / 12%);--tbw-resize-handle-width: var(--tbw-spacing-sm);--tbw-resize-handle-color: transparent;--tbw-resize-handle-color-hover: var(--tbw-color-accent);--tbw-resize-handle-border-radius: 0;--tbw-resize-indicator-width: 2px;--tbw-resize-indicator-color: var(--tbw-color-accent);--tbw-resize-indicator-opacity: .6;--tbw-transition-duration: .12s;--tbw-transition-ease: ease;--tbw-animation-duration: .2s;--tbw-animation-easing: ease-out;--tbw-animation-enabled: 1;--tbw-row-change-duration: .5s;--tbw-row-insert-duration: .3s;--tbw-row-remove-duration: .2s;--tbw-row-change-color: rgba(from var(--tbw-color-accent) r g b / 25%);--tbw-sort-indicator-color: var(--tbw-color-fg-muted);--tbw-sort-indicator-active-color: var(--tbw-color-accent);--tbw-sort-indicator-display: inline-flex;--tbw-sort-indicator-visibility: visible;--tbw-header-text-transform: none;--tbw-header-letter-spacing: normal;--tbw-color-header-separator: var(--tbw-color-border-cell);--tbw-density-scale: 1;--tbw-shell-header-height: 2.75em;--tbw-shell-header-bg: var(--tbw-color-panel-bg);--tbw-shell-header-border: var(--tbw-color-border);--tbw-shell-title-font-size: var(--tbw-font-size);--tbw-shell-title-font-weight: 600;--tbw-tool-panel-width: 17.5em;--tbw-tool-panel-bg: var(--tbw-color-panel-bg);--tbw-tool-panel-border: var(--tbw-color-border);--tbw-tool-panel-header-height: 2.5em;--tbw-tool-panel-transition: var(--tbw-animation-duration) var(--tbw-animation-easing);--tbw-toolbar-button-size: 2em;--tbw-toolbar-button-gap: var(--tbw-spacing-xs);--tbw-panel-padding: var(--tbw-spacing-lg);--tbw-panel-gap: var(--tbw-spacing-md);--tbw-menu-item-padding: var(--tbw-spacing-sm) var(--tbw-spacing-lg);--tbw-menu-item-gap: var(--tbw-spacing-md);--tbw-menu-min-width: 10rem;--tbw-button-padding: var(--tbw-spacing-sm) var(--tbw-spacing-lg);--tbw-button-padding-sm: var(--tbw-spacing-xs) var(--tbw-spacing-md);--tbw-input-height: var(--tbw-row-height);--tbw-input-padding: 0 var(--tbw-spacing-md);--tbw-detail-padding: var(--tbw-spacing-xl);--tbw-detail-max-height: 31.25rem;--tbw-indicator-size: var(--tbw-spacing-sm)}}\n@layer tbw-base{tbw-grid{color-scheme:inherit;position:relative;display:block;width:100%;height:100%;min-height:0;contain:content;font-family:var(--tbw-font-family);font-size:var(--tbw-font-size);font-feature-settings:"tnum","lnum";background:var(--tbw-color-bg);color:var(--tbw-color-fg);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);overflow:clip;outline:none}tbw-grid,tbw-grid *{box-sizing:border-box}tbw-grid .tbw-grid-root{position:relative;display:flex;flex-direction:column;height:100%}tbw-grid .tbw-grid-root.has-shell{display:flex;flex-direction:column;height:100%}tbw-grid .tbw-grid-root:has(.selected){-webkit-user-select:none;user-select:none}tbw-grid .rows-body-wrapper{flex:1;min-height:0;display:flex;flex-direction:row;width:100%;min-width:fit-content}tbw-grid .rows-body{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:visible}tbw-grid .rows-container{display:flex;flex-direction:row;flex:1;min-height:0;overflow:visible}tbw-grid .rows-viewport{flex:1;min-width:0;position:relative;display:block;overflow:clip}tbw-grid .rows-viewport .rows{position:absolute;top:0;left:0;min-width:100%;will-change:transform;z-index:var(--tbw-z-layer-rows, 1)}tbw-grid .faux-vscroll{position:sticky;inset-inline-end:0;flex-shrink:0;width:auto;overflow-y:auto;overflow-x:hidden;z-index:var(--tbw-z-layer-header, 30)}tbw-grid .faux-vscroll-spacer{width:1px}tbw-grid[data-has-focus] .cell-focus,tbw-grid[data-has-focus] .row-focus{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}tbw-grid .sticky-left,tbw-grid .sticky-right{position:sticky;z-index:25}tbw-grid .sticky-left{box-shadow:1px 0 0 var(--tbw-color-border)}tbw-grid .sticky-right{box-shadow:-1px 0 0 var(--tbw-color-border)}}\n@layer tbw-base{tbw-grid .header{display:block;flex-shrink:0;z-index:var(--tbw-z-layer-header, 30);background:var(--tbw-color-header-bg);overflow:visible}tbw-grid .header-group-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-color-header-bg);z-index:var(--tbw-z-layer-header, 30)}tbw-grid .header-group-cell{display:flex;align-items:center;justify-content:flex-start;padding:var(--tbw-cell-padding-header, 2px 8px);color:var(--tbw-color-header-group-fg, var(--tbw-color-header-fg));font-weight:var(--tbw-font-weight-header-group, var(--tbw-font-weight-header));justify-content:var(--tbw-align-header-group, var(--tbw-align-header, flex-start))}tbw-grid .header-group-cell:not(:last-child){border-right:2px solid var(--tbw-color-border)}tbw-grid .header-row{display:grid;grid-template-columns:var(--tbw-column-template);color:var(--tbw-color-header-fg);font-size:var(--tbw-font-size-header);min-height:var(--tbw-header-height);border-bottom:var(--tbw-border-header);z-index:var(--tbw-z-layer-header, 30);text-transform:var(--tbw-header-text-transform);letter-spacing:var(--tbw-header-letter-spacing)}tbw-grid .header-row>.cell{display:flex;align-items:center;gap:4px;padding:var(--tbw-cell-padding-header, 2px 8px);background-color:var(--tbw-color-header-bg);font-weight:var(--tbw-font-weight-header);border-right:1px solid var(--tbw-color-border-cell);overflow:visible;min-width:0}tbw-grid .header-row>.cell>span:first-child{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:inherit}tbw-grid .header-row>.cell>span[part~=sort-indicator]{flex-shrink:0;opacity:.6;color:var(--tbw-sort-indicator-color);display:var(--tbw-sort-indicator-display, inline-flex);visibility:var(--tbw-sort-indicator-visibility, visible);transition:opacity .15s,visibility 0s,display 0s allow-discrete;transition-behavior:allow-discrete}tbw-grid .header-row>.cell:hover>span[part~=sort-indicator]{display:inline-flex;visibility:visible}tbw-grid .header-row>.cell[aria-sort=ascending]>span[part~=sort-indicator],tbw-grid .header-row>.cell[aria-sort=descending]>span[part~=sort-indicator]{display:inline-flex;visibility:visible;opacity:1;color:var(--tbw-sort-indicator-active-color)}tbw-grid .header-row>.cell:last-child{border-right:0}tbw-grid .header-row>.cell:last-child .resize-handle{right:0;width:calc(var(--tbw-resize-handle-width) / 2)}tbw-grid .header-row>.cell.grouped.group-end:not(:last-child){border-right:2px solid var(--tbw-color-border)}tbw-grid .header-row>.cell.resizable{position:relative}tbw-grid .header-row>.cell.sticky-left,tbw-grid .header-row>.cell.sticky-right{background:var(--tbw-color-header-bg);z-index:35}tbw-grid .sortable{cursor:pointer;-webkit-user-select:none;user-select:none}tbw-grid .resize-handle{position:absolute;top:0;right:calc(var(--tbw-resize-handle-width) / -2);width:var(--tbw-resize-handle-width);height:100%;cursor:e-resize;-webkit-user-select:none;user-select:none;touch-action:none;z-index:20;background:var(--tbw-resize-handle-color);transition:background .12s ease;border-radius:var(--tbw-resize-handle-border-radius)}tbw-grid .resize-handle:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);width:var(--tbw-resize-indicator-width, 2px);height:0;background:var(--tbw-resize-indicator-color, var(--tbw-color-accent));opacity:0;pointer-events:none;transition:opacity .12s ease,height 0s .12s;z-index:1000}tbw-grid .resize-handle:hover{background:var(--tbw-resize-handle-color-hover)}tbw-grid .resize-handle:hover:after{height:100vh;opacity:var(--tbw-resize-indicator-opacity, .6);transition:opacity .12s ease,height 0s}}\n@layer tbw-base{tbw-grid .data-grid-row{display:grid;grid-template-columns:var(--tbw-column-template);contain:layout style}tbw-grid .data-grid-row:nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid .data-grid-row:hover{background:var(--tbw-color-row-hover)}tbw-grid .data-grid-row>.cell{display:block;padding:var(--tbw-cell-padding, 2px 8px);border-bottom:var(--tbw-row-divider);min-height:var(--tbw-row-height);align-content:center;border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;min-width:0;white-space:var(--tbw-cell-white-space, nowrap);text-overflow:ellipsis}tbw-grid .data-grid-row>.cell>*{overflow:hidden;text-overflow:ellipsis;white-space:inherit;min-width:0}tbw-grid .data-grid-row>.cell:last-child{border-right:0}tbw-grid .data-grid-row>.cell[data-type=boolean]{text-align:center}tbw-grid .data-grid-row>.cell[data-type=boolean] input[type=checkbox]{margin:0;width:var(--tbw-checkbox-size);height:var(--tbw-checkbox-size);vertical-align:middle}tbw-grid .data-grid-row>.cell.selected:focus-visible,tbw-grid .data-grid-row>.cell:focus-visible:not(.cell-focus){outline:none}tbw-grid .data-grid-row>.cell.sticky-left,tbw-grid .data-grid-row>.cell.sticky-right{background:var(--tbw-color-panel-bg)}tbw-grid .selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}}\n@layer tbw-base{tbw-grid .tbw-shell-header{display:flex;align-items:center;gap:8px;min-height:var(--tbw-shell-header-height);padding:0 8px;background:var(--tbw-shell-header-bg);border-bottom:1px solid var(--tbw-shell-header-border);flex-shrink:0}tbw-grid .tbw-shell-title{font-size:var(--tbw-shell-title-font-size);font-weight:var(--tbw-shell-title-font-weight);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}tbw-grid .tbw-shell-content{flex:1;display:flex;align-items:center;gap:12px;min-width:0;overflow:hidden}tbw-grid .tbw-shell-toolbar{display:flex;align-items:center;gap:var(--tbw-toolbar-button-gap);flex-shrink:0}tbw-grid .tbw-toolbar-btn{display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-toolbar-button-size);height:var(--tbw-toolbar-button-size);padding:0;border:1px solid transparent;border-radius:var(--tbw-border-radius);background:transparent;color:var(--tbw-color-fg);cursor:pointer;font-size:16px;transition:background var(--tbw-transition-duration) var(--tbw-transition-ease),border-color var(--tbw-transition-duration) var(--tbw-transition-ease)}tbw-grid .tbw-toolbar-btn:hover{background:var(--tbw-color-row-hover)}tbw-grid .tbw-toolbar-btn:focus-visible{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}tbw-grid .tbw-toolbar-btn.active{background:var(--tbw-focus-background);border-color:var(--tbw-color-accent)}tbw-grid .tbw-toolbar-btn:disabled{opacity:.5;cursor:not-allowed}tbw-grid .tbw-toolbar-separator{width:1px;height:20px;background:var(--tbw-color-border);margin:0 4px}tbw-grid .tbw-shell-body{position:relative;display:flex;flex:1;min-height:0;overflow:visible}tbw-grid .tbw-grid-content{flex:1;min-width:0;min-height:0;display:flex;flex-direction:row;overflow:hidden}tbw-grid .tbw-scroll-area{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow-x:auto;overflow-y:hidden;overflow-anchor:none}}\n@layer tbw-base{tbw-grid .tbw-tool-panel{position:absolute;top:0;bottom:0;right:0;width:0;overflow:hidden;background:var(--tbw-tool-panel-bg);border-left:1px solid var(--tbw-tool-panel-border);transition:width var(--tbw-tool-panel-transition);display:flex;flex-direction:column;z-index:30;box-shadow:-2px 0 8px var(--tbw-color-shadow)}tbw-grid .tbw-tool-panel[data-position=left]{right:auto;left:0;border-left:none;border-right:1px solid var(--tbw-tool-panel-border);box-shadow:2px 0 8px var(--tbw-color-shadow)}tbw-grid .tbw-tool-panel.open{width:var(--tbw-tool-panel-width)}tbw-grid .tbw-tool-panel-resize{position:absolute;top:0;bottom:0;width:6px;cursor:col-resize;background:transparent;z-index:10;transition:background var(--tbw-transition-duration) var(--tbw-transition-ease)}tbw-grid .tbw-tool-panel-resize[data-handle-position=left]{left:0}tbw-grid .tbw-tool-panel-resize[data-handle-position=right]{right:0}tbw-grid .tbw-tool-panel-resize:hover,tbw-grid .tbw-tool-panel-resize.resizing{background:var(--tbw-color-accent)}tbw-grid .tbw-tool-panel-header{display:flex;align-items:center;justify-content:space-between;min-height:var(--tbw-tool-panel-header-height);padding:0 12px;border-bottom:1px solid var(--tbw-tool-panel-border);flex-shrink:0}tbw-grid .tbw-tool-panel-title{font-weight:600;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}tbw-grid .tbw-tool-panel-close{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:none;border-radius:var(--tbw-border-radius);background:transparent;color:var(--tbw-color-fg-muted);cursor:pointer;font-size:14px}tbw-grid .tbw-tool-panel-close:hover{background:var(--tbw-color-row-hover);color:var(--tbw-color-fg)}tbw-grid .tbw-tool-panel-content{flex:1;overflow:auto}tbw-grid .tbw-accordion{display:flex;flex-direction:column;gap:0}tbw-grid .tbw-accordion-section{border-bottom:1px solid var(--tbw-tool-panel-border)}tbw-grid .tbw-accordion-section:last-child{border-bottom:none}tbw-grid .tbw-accordion-section.single .tbw-accordion-header{cursor:default}tbw-grid .tbw-accordion-section.single .tbw-accordion-header:hover{background:transparent}tbw-grid .tbw-accordion-section.expanded .tbw-accordion-chevron{transform:rotate(90deg)}tbw-grid .tbw-accordion-section.expanded .tbw-accordion-content{display:block}tbw-grid .tbw-accordion-header{display:flex;align-items:center;gap:8px;width:100%;padding:10px 12px;border:none;background:transparent;color:var(--tbw-color-fg);font-size:13px;font-weight:600;text-align:start;cursor:pointer;-webkit-user-select:none;user-select:none}tbw-grid .tbw-accordion-header:hover{background:var(--tbw-color-row-hover)}tbw-grid .tbw-accordion-chevron{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;font-size:10px;color:var(--tbw-color-fg-muted);transition:transform .15s ease;flex-shrink:0}tbw-grid .tbw-accordion-icon{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;font-size:14px;flex-shrink:0}tbw-grid .tbw-accordion-title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}tbw-grid .tbw-accordion-content{display:none}}\n@layer tbw-base{.tbw-loading-overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:1000;pointer-events:all;animation:tbw-fade-in .15s ease-out}.tbw-spinner{--tbw-spinner-size: 48px;--tbw-spinner-border-width: 3px;--tbw-spinner-color: var(--tbw-color-accent);--tbw-spinner-track-color: var(--tbw-color-border);width:var(--tbw-spinner-size);height:var(--tbw-spinner-size);border:var(--tbw-spinner-border-width) solid var(--tbw-spinner-track-color);border-top-color:var(--tbw-spinner-color);border-radius:50%;animation:tbw-spin .8s linear infinite}.tbw-spinner--large{--tbw-spinner-size: min(48px, calc(100% - 16px) )}.tbw-spinner--small{--tbw-spinner-size: calc(var(--tbw-row-height, 28px) * .6);--tbw-spinner-border-width: 2px}.data-grid-row.tbw-row-loading{position:relative;pointer-events:none}.tbw-row-loading-overlay{position:absolute;inset:0;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:26;animation:tbw-fade-in .15s ease-out;pointer-events:none;display:flex;align-items:center}.tbw-row-loading-spinner{--_spinner-size: calc(var(--tbw-row-height, 28px) * .6);margin-left:var(--tbw-spacing-md);width:var(--_spinner-size);height:var(--_spinner-size);border:2px solid var(--tbw-spinner-track-color, var(--tbw-color-border));border-top-color:var(--tbw-spinner-color, var(--tbw-color-accent));border-radius:50%;animation:tbw-spin .8s linear infinite}.cell.tbw-cell-loading{position:relative;pointer-events:none}.cell.tbw-cell-loading:before{content:"";position:absolute;inset:0;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:26;animation:tbw-fade-in .15s ease-out}.cell.tbw-cell-loading:after{--_spinner-size: calc(var(--tbw-row-height, 28px) * .5);content:"";position:absolute;left:var(--tbw-spacing-sm);top:0;bottom:0;margin:auto 0;width:var(--_spinner-size);height:var(--_spinner-size);border:2px solid var(--tbw-spinner-track-color, var(--tbw-color-border));border-top-color:var(--tbw-spinner-color, var(--tbw-color-accent));border-radius:50%;animation:tbw-spin .8s linear infinite;z-index:27}}\n@layer tbw-base{tbw-grid .tbw-expanding{animation:tbw-expand var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}tbw-grid .tbw-collapsing{animation:tbw-collapse var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}tbw-grid[data-animation-mode=off]{--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}tbw-grid[data-animation-mode=off] .data-grid-row[data-animating]{animation:none}tbw-grid .data-grid-row[data-animating=change]{animation:tbw-row-change var(--tbw-row-change-duration) ease-out}tbw-grid .data-grid-row[data-animating=insert]{animation:tbw-row-insert var(--tbw-row-insert-duration) ease-out;will-change:max-height,opacity}tbw-grid .data-grid-row[data-animating=remove]{animation:tbw-row-remove var(--tbw-row-remove-duration) ease-out forwards;will-change:max-height,opacity,transform;pointer-events:none}}@keyframes tbw-expand{0%{opacity:0;max-height:0;transform:translateY(-8px)}to{opacity:1;max-height:500px;transform:translateY(0)}}@keyframes tbw-collapse{0%{opacity:1;max-height:500px;transform:translateY(0)}to{opacity:0;max-height:0;transform:translateY(-8px)}}@keyframes tbw-row-change{0%{background-color:transparent}20%{background-color:var(--tbw-row-change-color)}to{background-color:transparent}}@keyframes tbw-row-insert{0%{opacity:0;max-height:0;overflow:hidden}to{opacity:1;max-height:var(--tbw-row-height, 28px);overflow:hidden}}@keyframes tbw-row-remove{0%{opacity:1;transform:translateY(0);max-height:var(--tbw-row-height, 28px)}to{opacity:0;max-height:0;transform:translateY(-8px)}}@keyframes tbw-spin{to{transform:rotate(360deg)}}@keyframes tbw-fade-in{0%{opacity:0}to{opacity:1}}\n@layer tbw-base{@media(forced-colors:active){tbw-grid{--tbw-color-border: CanvasText;--tbw-color-border-strong: CanvasText;--tbw-color-border-cell: CanvasText;--tbw-color-border-header: CanvasText;--tbw-color-fg: CanvasText;--tbw-color-bg: Canvas;--tbw-color-panel-bg: Canvas;--tbw-color-header-bg: Canvas;--tbw-color-header-fg: CanvasText;--tbw-color-accent: Highlight;--tbw-color-accent-fg: HighlightText;--tbw-color-selection: Highlight;--tbw-color-row-hover: Highlight;--tbw-focus-outline: 2px solid Highlight;--tbw-range-border-color: Highlight}tbw-grid .cell:focus,tbw-grid .cell.active-cell{outline:2px solid Highlight!important;outline-offset:-2px}tbw-grid .data-grid-row[aria-selected=true]{background:Highlight!important;color:HighlightText!important}}@media(prefers-reduced-motion:reduce){tbw-grid[data-animation-mode=reduced-motion]{--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}tbw-grid[data-animation-mode=reduced-motion] .data-grid-row[data-animating]{animation:none}}}\n')}getPlugin(e){return this.#X?.getPlugin(e)}getPluginByName(e){return this.#X?.getPluginByName(e)}requestRender(){this.#O.requestPhase(he.ROWS,"plugin:requestRender")}requestColumnsRender(){this.#O.requestPhase(he.COLUMNS,"plugin:requestColumnsRender")}requestRenderWithFocus(){this._restoreFocusAfterRender=!0,this.#O.requestPhase(he.ROWS,"plugin:requestRenderWithFocus")}updateTemplate(){c(this)}requestAfterRender(){this.#O.requestPhase(he.STYLE,"plugin:requestAfterRender")}#Ae(){this.#X=new it(this);const e=this.#s?.plugins,t=Array.isArray(e)?e:[];this.#X.attachAll(t)}#ke(){!function(e){let t=!1;for(const{name:i,styles:n}of e)Ne.has(i)||(Ne.set(i,n),t=!0);t&&Ge()}(this.#X?.getPluginStyles()??[])}#we(){const e=this.#s?.plugins,t=Array.isArray(e)?e:[];if(this.#Z===t)return;if(this.#Z&&this.#Z.length===t.length&&this.#Z.every((e,i)=>e===t[i]))return void(this.#Z=t);this.#X&&this.#X.detachAll();for(const n of this.#te.toolPanels.keys()){const e=this.#te.lightDomToolPanelIds.has(n),t=this.#te.apiToolPanelIds.has(n);if(!e&&!t){const e=this.#te.panelCleanups.get(n);e&&(e(),this.#te.panelCleanups.delete(n)),this.#te.toolPanels.delete(n)}}for(const n of this.#te.headerContents.keys()){const e=this.#te.headerContentCleanups.get(n);e&&(e(),this.#te.headerContentCleanups.delete(n)),this.#te.headerContents.delete(n)}this.#Ae(),this.#ke(),this.#Z=t,this.#Te(),this.#Le();const i=this.#N;if(this.#N=this.#X?.getAll().some(e=>e.onScroll)??!1,!i&&this.#N){const e=this.#L.querySelector(".tbw-grid-content")??this.#L.querySelector(".tbw-grid-root");this.#Me(e)}}#Pe(){this.#X?.detachAll()}#Le(){if(!this.#X)return;const e=this.#X.getToolPanels();for(const{panel:i}of e)this.#te.toolPanels.has(i.id)||this.#te.toolPanels.set(i.id,i);const t=this.#X.getHeaderContents();for(const{content:i}of t)this.#te.headerContents.has(i.id)||this.#te.headerContents.set(i.id,i)}#He(){const e=nt.getAdapters();if(0===e.length&&!this.__frameworkAdapter)return;const t=this.__frameworkAdapter;return i=>{if(t?.createToolPanelRenderer){const e=t.createToolPanelRenderer(i);if(e)return e}for(const t of e)if(t.createToolPanelRenderer){const e=t.createToolPanelRenderer(i);if(e)return e}}}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=0),this.hasAttribute("version")||this.setAttribute("version",nt.version),this.id||(this.id="tbw-grid-"+ ++nt.#T),this._rows=Array.isArray(this.#P)?[...this.#P]:[],this.#W&&(this.#W.abort(),this.#Q=!1),this.#W=new AbortController,this.#j&&(de(this.#j),this.#j=void 0),this.#Ie(),this.#H.parseLightDomColumns(this),this.#H.merge(),this.#Ae();const e=this.#s?.plugins;var t,i;this.#Z=Array.isArray(e)?e:[],this.#Le(),this.#M||(this.#De(),this.#ke(),this.#M=!0),this.#ze(),this.#j=(t=()=>{this.#Oe()},i={timeout:100},ae?requestIdleCallback(t,i):window.setTimeout(()=>{const e=Date.now();t({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-e))})},1))}disconnectedCallback(){this.#j&&(de(this.#j),this.#j=void 0),this.#V&&(clearTimeout(this.#V),this.#V=0),this.#Pe(),function(e){for(const t of e.headerContentCleanups.values())t();e.headerContentCleanups.clear();for(const t of e.panelCleanups.values())t();e.panelCleanups.clear();for(const t of e.toolbarContentCleanups.values())t();e.toolbarContentCleanups.clear();for(const t of e.toolbarContents.values())t.onDestroy?.();if(e.isPanelOpen)for(const t of e.expandedSections){const i=e.toolPanels.get(t);i?.onClose?.()}e.isPanelOpen=!1,e.expandedSections.clear(),e.toolPanels.clear(),e.headerContents.clear(),e.toolbarContents.clear(),e.lightDomHeaderContent=[],e.lightDomToolPanelIds.clear(),e.lightDomToolbarContentIds.clear(),e.lightDomContentMoved=!1}(this.#te),this.#ie.setInitialized(!1),this.#ne?.(),this.#ne=void 0,this.#re?.(),this.#re=void 0,$e(this.#B),this.#W&&(this.#W.abort(),this.#W=void 0),this.#J?.abort(),this.#J=void 0,this.#Q=!1,this._resizeController&&this._resizeController.dispose(),this.#K&&(this.#K.disconnect(),this.#K=void 0),this.#U&&(this.#U.disconnect(),this.#U=void 0,this.#Ce=!1),V(this),this.#qe.clear(),this.#Z=void 0;for(const e of this._rowPool)e.remove();this._rowPool.length=0,this.__rowsBodyEl=null,this.#I=!1}attributeChangedCallback(e,t,i){if("loading"===e){const e=null!==i&&"false"!==i;return void(this.loading!==e&&(this.loading=e))}if(t!==i&&i&&"null"!==i&&"undefined"!==i)if("rows"===e||"columns"===e||"grid-config"===e)try{const t=JSON.parse(i);"rows"===e?this.rows=t:"columns"===e?this.columns=t:"grid-config"===e&&(this.gridConfig=t)}catch{console.warn(`[tbw-grid] Invalid JSON for '${e}' attribute:`,i)}else"fit-mode"===e&&(this.fitMode=i)}#ze(){const e=this.#L.querySelector(".tbw-grid-content")??this.#L.querySelector(".tbw-grid-root");if(this._headerRowEl=e?.querySelector(".header-row"),this._virtualization.totalHeightEl=e?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=e?.querySelector(".rows-viewport"),this._bodyEl=e?.querySelector(".rows"),this.__rowsBodyEl=e?.querySelector(".rows-body"),this.#ie.isInitialized){Me(this.#L,this.#te),Le(this.#L,this.#s?.shell,this.#te);const e=this.#s?.shell?.toolPanel?.defaultOpen;e&&this.#te.toolPanels.has(e)&&(this.openToolPanel(),this.#te.expandedSections.add(e))}if(this.setAttribute("data-upgraded",""),this.#I=!0,this._resizeController=ge(this),this.#Se(),this.#Me(e),this.#Q)return;this.#Q=!0;const t=this.disconnectSignal;X(this,this,this.#L,t),this.#Te(),queueMicrotask(()=>this.#Fe()),this.#O.requestPhase(he.FULL,"afterConnect")}#Te(){const e=this.#s.rowHeight,t=this.#X.hasRowHeightPlugin();"function"==typeof e||t?this._virtualization.variableHeights||(this._virtualization.variableHeights=!0,this._virtualization.rowHeight="number"==typeof e&&e>0?e:this._virtualization.rowHeight||28,this.#Ne(),"function"!=typeof e&&(this.#G=!0)):!t&&"function"!=typeof e&&this._virtualization.variableHeights?(this._virtualization.variableHeights=!1,this._virtualization.positionCache=null):"number"==typeof e&&e>0?(this._virtualization.rowHeight=e,this._virtualization.variableHeights=!1):requestAnimationFrame(()=>this.#Ge())}#Ge(){if(this.#X.hasExtraHeight())return;const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;const t=e.querySelectorAll(".cell");let i=0;t.forEach(e=>{const t=e.offsetHeight;t>i&&(i=t)});const n=e.getBoundingClientRect(),r=Math.max(n.height,i);r>0&&Math.abs(r-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=r,this.#O.requestPhase(he.VIRTUALIZATION,"measureRowHeight"))}#Ee(){const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;const t=e.querySelectorAll(".cell");let i=0;t.forEach(e=>{const t=e.offsetHeight;t>i&&(i=t)});const n=e.getBoundingClientRect(),r=Math.max(n.height,i);if(r>0){if(Math.abs(r-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=r),this.#Ne(),this._virtualization.totalHeightEl){const e=this.#ye(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}}#Me(e){this.#J?.abort(),this.#J=new AbortController;const t=this.#J.signal,i=e?.querySelector(".faux-vscroll"),n=e?.querySelector(".rows");if(this._virtualization.container=i??this,this.#N=this.#X?.getAll().some(e=>e.onScroll)??!1,i&&n){i.addEventListener("scroll",()=>{if(!this._virtualization.enabled&&!this.#N)return;const e=i.scrollTop,t=this._virtualization.rowHeight;if(this._rows.length<=this._virtualization.bypassThreshold)n.style.transform=`translateY(${-e}px)`;else{const i=this._virtualization.positionCache;let r,o;if(this._virtualization.variableHeights&&i&&i.length>0){r=et(i,e),-1===r&&(r=0);const n=r-r%2;o=i[n]?.offset??n*t}else{r=Math.floor(e/t);o=(r-r%2)*t}const s=-(e-o);n.style.transform=`translateY(${s}px)`}this.#F=e,this.#q||(this.#q=requestAnimationFrame(()=>{this.#q=0,null!==this.#F&&(this.#Ve(this.#F),this.#F=null)}))},{passive:!0,signal:t});const e=this.#L.querySelector(".tbw-scroll-area");this.#ee=e,this._virtualization.scrollAreaEl=e,e&&this.#N&&e.addEventListener("scroll",()=>{const t=this.#Y;t.scrollTop=i.scrollTop,t.scrollLeft=e.scrollLeft,t.scrollHeight=i.scrollHeight,t.scrollWidth=e.scrollWidth,t.clientHeight=i.clientHeight,t.clientWidth=e.clientWidth,this.#X?.onScroll(t)},{passive:!0,signal:t});const r=this.#L.querySelector(".tbw-grid-content"),o=this.#ee;r&&(r.addEventListener("wheel",e=>{const t=e.shiftKey||Math.abs(e.deltaX)>Math.abs(e.deltaY);if(t&&o){const t=e.shiftKey?e.deltaY:e.deltaX,{scrollLeft:i,scrollWidth:n,clientWidth:r}=o;(t>0&&i<n-r||t<0&&i>0)&&(e.preventDefault(),o.scrollLeft+=t)}else if(!t){const{scrollTop:t,scrollHeight:n,clientHeight:r}=i;(e.deltaY>0&&t<n-r||e.deltaY<0&&t>0)&&(e.preventDefault(),i.scrollTop+=e.deltaY)}},{passive:!1,signal:t}),We(r,this.#B,{fauxScrollbar:i,scrollArea:o},t))}var r,o,s;this._bodyEl&&(r=this,o=this._bodyEl,s=t,o.addEventListener("mousedown",e=>{const t=e.target.closest(".cell[data-col]");t&&(t.classList.contains("editing")||(e.preventDefault(),j(r,t)))},{signal:s}),o.addEventListener("click",e=>{const t=e.target.closest(".data-grid-row");if(t&&W(r,e,t),!document.activeElement?.closest(".cell.editing")){const t=e.target.closest("tbw-grid");t&&t.focus({preventScroll:!0})}},{signal:s}),o.addEventListener("dblclick",e=>{const t=e.target.closest(".data-grid-row");t&&W(r,e,t)},{signal:s})),this.#K?.disconnect(),this._virtualization.viewportEl&&(this.#K=new ResizeObserver(()=>{this.#$e(),this.#O.requestPhase(he.VIRTUALIZATION,"resize-observer")}),this.#K.observe(this._virtualization.viewportEl)),this.#L.addEventListener("focusin",()=>{this.dataset.hasFocus=""},{signal:t}),this.#L.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&this.#L.contains(t)||delete this.dataset.hasFocus},{signal:t})}#Ce=!1;#xe(){if(this.#Ce)return;const e=this._bodyEl?.querySelector(".data-grid-row");e&&(this.#Ce=!0,this.#U?.disconnect(),this.#U=new ResizeObserver(()=>{this.#Ge()}),this.#U.observe(e))}addEventListener(e,t,i){super.addEventListener(e,t,i)}removeEventListener(e,t,i){super.removeEventListener(e,t,i)}#Re(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}#Fe(){const e=this._bodyEl?.querySelectorAll(".data-grid-row");e?.forEach((e,t)=>{const i=t===this._focusRow;e.setAttribute("aria-selected",String(i)),e.querySelectorAll(".cell").forEach((e,t)=>{e.setAttribute("aria-selected",String(i&&t===this._focusCol))})})}#he(e){this.#z[e]=!0,this.#D||(this.#D=!0,queueMicrotask(()=>this.#Be()))}#Be(){if(!this.#D||!this.#I)return void(this.#D=!1);const e=this.#z;if(this.#D=!1,this.#z={rows:!1,columns:!1,gridConfig:!1,fitMode:!1},e.gridConfig)return this.#We(),void(e.rows&&this.#Ke());e.columns&&this.#Ue(),e.rows&&this.#Ke(),e.fitMode&&this.#je()}#Ke(){this._rows=Array.isArray(this.#P)?[...this.#P]:[],this.#Ye(),this.#O.requestPhase(he.ROWS,"applyRowsUpdate")}#Ye(){this.#de.clear();const e=this.#s.getRowId;this._rows.forEach((t,i)=>{const n=this.#Xe(t,e);void 0!==n&&this.#de.set(n,{row:t,index:i})})}#Xe(e,t){if(t)return t(e);const i=e;return"id"in i&&null!=i.id?String(i.id):"_id"in i&&null!=i._id?String(i._id):void 0}#Ze(e,t){const i=this.#Xe(e,t);if(void 0===i)throw new Error('[tbw-grid] Cannot determine row ID. Configure getRowId in gridConfig or ensure rows have an "id" property.');return i}#Ue(){V(this),this.#H.merge(),this.#Se()}#je(){this.#H.merge();"fixed"===this.#s.fitMode?(this.__didInitialAutoSize=!1,l(this)):(this._columns.forEach(e=>{!e.__userResized&&e.__autoSized&&delete e.width}),c(this))}#We(){Ae(this,this.#te),ke(this,this.#te);const e=!!this.#L.querySelector(".has-shell"),t=!!this.#L.querySelector(".tbw-tool-panel"),i=this.#L.querySelectorAll(".tbw-accordion-section").length;this.#H.parseLightDomColumns(this),this.#H.merge(),this.#we(),Te(this,this.#te,this.#He()),this.#H.markSourcesChanged(),this.#H.merge();const n=_e(this.#s?.shell),r=(this.#s?.shell?.toolPanels?.length??0)>0,o=this.#s?.shell?.toolPanels?.length??0;if(e!==n||!t&&r||t&&o!==i)return Ie(this.#te),this.#De(),this.#ke(),this.#ze(),void this.#Ye();e&&this.#Qe(),this.#Ye(),this.#O.requestPhase(he.COLUMNS,"applyGridConfigUpdate")}#Qe(){const e=this.#L.querySelector(".tbw-shell-header");if(!e)return;const t=this.#s.shell?.header?.title??this.#te.lightDomTitle;let i=e.querySelector(".tbw-shell-title");t?(i||(i=document.createElement("h2"),i.className="tbw-shell-title",i.setAttribute("part","shell-title"),e.insertBefore(i,e.firstChild)),i.textContent=t):i&&i.remove()}#be(){if(this.__rowRenderEpoch++,this.#X){const e=this.#ce.length>0?this.#ce:this._columns,t=e.filter(e=>!e.hidden),i=e.filter(e=>e.hidden),n=this.#X.processColumns([...t]);if(n!==t){const r=new Set(n.map(e=>e.field));!t.some(e=>r.has(e.field))&&n.length>0?this._columns=[...n,...i]:this._columns=this.#Je(e,n,i)}else this._columns=[...e]}}#Je(e,t,i){if(0===i.length)return t;const n=new Map;for(const l of t)n.set(l.field,l);const r=new Set(e.map(e=>e.field)),o=[];for(const l of t)r.has(l.field)||o.push(l);const s=[];for(const l of e){const e=n.get(l.field);e?s.push(e):l.hidden&&s.push(l)}return s.push(...o),s}#ve(){V(this);const e=function(e,t){if(!e._sortState)return t;e.__originalOrder=[...t];const i=(e.effectiveConfig?.sortHandler??Q)(t,e._sortState,e._columns);return i&&"function"==typeof i.then?t:i}(this,Array.isArray(this.#P)?[...this.#P]:[]),t=this.#X?.processRows(e)??e;this._rows=t,this.#Ye(),this._virtualization.variableHeights&&this.#Ne()}#_e(e){const t={...i,...e.animation},n=t.mode??"reduced-motion";let r=1;!1===n||"off"===n?r=0:!0!==n&&"on"!==n||(r=1),this.style.setProperty("--tbw-animation-duration",`${t.duration}ms`),this.style.setProperty("--tbw-animation-easing",t.easing??"ease-out"),this.style.setProperty("--tbw-animation-enabled",String(r)),this.dataset.animationMode="boolean"==typeof n?n?"on":"off":n}#et(e,t,i=this.__rowRenderEpoch){if(this.#$||(this.#$=(e,t,i)=>this.#X?.renderRow(e,t,i)??!1),function(e,t,i,n,r){const o=Math.max(0,i-t),s=e._bodyEl,l=e._visibleColumns,a=l.length;let d=e.__cachedHeaderRowCount;for(void 0===d&&(d=e.querySelector(".header-group-row")?2:1,e.__cachedHeaderRowCount=d);e._rowPool.length<o;){const t=G();e._rowPool.push(t)}if(e._rowPool.length>o){for(let t=o;t<e._rowPool.length;t++){const i=e._rowPool[t];i.parentNode===s&&i.remove()}e._rowPool.length=o}const c=r&&!1!==e.__hasRenderRowPlugins,h=e._hasAfterRowRenderHook?.()??!1;for(let g=0;g<o;g++){const i=t+g,o=e._rows[i],p=e._rowPool[g];if(p.setAttribute("aria-rowindex",String(i+d+1)),c&&r(o,p,i)){p.__epoch=n,p.__rowDataRef=o,p.parentNode!==s&&s.appendChild(p);continue}const f=p.__epoch,w=p.__rowDataRef;let m=p.children.length;m>a&&p.lastElementChild?.classList.contains("tbw-row-loading-overlay")&&m--;const b=f===n&&m===a,v=w!==o,y=!!e._isGridEditMode;let C=!1;if(b&&v)for(let e=0;e<a;e++)if(l[e].externalView&&!p.querySelector(`.cell[data-col="${e}"] [data-external-view]`)){C=!0;break}if(!b||C){const t=z(p),r=y||e._activeEditRows===i;t&&!r?(p.__isCustomRow&&(p.className="data-grid-row",p.setAttribute("role","row"),p.__isCustomRow=!1),O(p),B(e,p,o,i),p.__epoch=n,p.__rowDataRef=o):t&&r?($(e,p,o,i),p.__rowDataRef=o):(p.__isCustomRow&&(p.className="data-grid-row",p.setAttribute("role","row"),p.__isCustomRow=!1),B(e,p,o,i),p.__epoch=n,p.__rowDataRef=o)}else if(v){const t=z(p),r=y||e._activeEditRows===i;t&&!r?(O(p),B(e,p,o,i),p.__epoch=n,p.__rowDataRef=o):($(e,p,o,i),p.__rowDataRef=o)}else{const t=z(p),r=y||e._activeEditRows===i;t&&!r?(O(p),B(e,p,o,i),p.__epoch=n,p.__rowDataRef=o):$(e,p,o,i)}let x=!1;const E=e.changedRowIds;if(E&&E.length>0)try{const t=e.getRowId?.(o);t&&(x=E.includes(t))}catch{}x!==p.classList.contains("changed")&&p.classList.toggle("changed",x);const R=e.effectiveConfig?.rowClass;if(R){const e=p.getAttribute("data-dynamic-classes");e&&e.split(" ").forEach(e=>e&&p.classList.remove(e));try{const e=R(o);if(e&&e.length>0){const t=e.filter(e=>e&&"string"==typeof e);t.forEach(e=>p.classList.add(e)),p.setAttribute("data-dynamic-classes",t.join(" "))}else p.removeAttribute("data-dynamic-classes")}catch(u){console.warn("[tbw-grid] rowClass callback error:",u),p.removeAttribute("data-dynamic-classes")}}h&&e._afterRowRender?.({row:o,rowIndex:i,rowElement:p}),p.parentNode!==s&&s.appendChild(p)}}(this,e,t,i,this.#$),this.#se.size>0)for(const n of this.#se)this.#ge(n,!0)}#tt={rowCount:-1,colCount:-1,ariaLabel:void 0,ariaDescribedBy:void 0};#it(e,t){!function(e,t,i,n,r){if(n===e.rowCount&&r===e.colCount)return!1;const o=e.rowCount;e.rowCount=n,e.colCount=r,t&&(t.setAttribute("aria-rowcount",String(n)),t.setAttribute("aria-colcount",String(r))),n!==o&&i&&(n>0?i.setAttribute("role","rowgroup"):i.removeAttribute("role"))}(this.#tt,this.__rowsBodyEl,this._bodyEl,e,t)}#me(){!function(e,t,i,n){if(!t)return!1;let r=!1;const o=function(e,t){const i=e?.gridAriaLabel;return i||(e?.shell?.header?.title??t?.lightDomTitle??void 0)}(i,n);o!==e.ariaLabel&&(e.ariaLabel=o,o?t.setAttribute("aria-label",o):t.removeAttribute("aria-label"),r=!0);const s=i?.gridAriaDescribedBy;s!==e.ariaDescribedBy&&(e.ariaDescribedBy=s,s?t.setAttribute("aria-describedby",s):t.removeAttribute("aria-describedby"),r=!0)}(this.#tt,this.__rowsBodyEl,this.#s,this.#te)}#ue(){const e=this.querySelector(".tbw-grid-root");var t;e&&(this.#oe?(this.#ae||(this.#ae=function(e){const t=document.createElement("div");return t.className="tbw-loading-overlay",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.appendChild(ce("large",e)),t}(this.#s?.loadingRenderer)),function(e,t){e.appendChild(t)}(e,this.#ae)):(t=this.#ae,t?.remove()))}#ge(e,t){const i=this.#de.get(e);if(!i)return;const n=this.findRenderedRowElement?.(i.index);n&&function(e,t){if(t){if(e.classList.add("tbw-row-loading"),e.setAttribute("aria-busy","true"),!e.querySelector(".tbw-row-loading-overlay")){const t=document.createElement("div");t.className="tbw-row-loading-overlay",t.setAttribute("aria-hidden","true");const i=document.createElement("div");i.className="tbw-row-loading-spinner",t.appendChild(i),e.appendChild(t)}}else e.classList.remove("tbw-row-loading"),e.removeAttribute("aria-busy"),e.querySelector(".tbw-row-loading-overlay")?.remove()}(n,t)}#pe(e,t,i){const n=this.#de.get(e);if(!n)return;const r=this.findRenderedRowElement?.(n.index);if(!r)return;const o=this._visibleColumns.findIndex(e=>e.field===t);if(o<0)return;const s=r.children[o];s&&function(e,t){t?(e.classList.add("tbw-cell-loading"),e.setAttribute("aria-busy","true")):(e.classList.remove("tbw-cell-loading"),e.removeAttribute("aria-busy"))}(s,i)}#Se(){if(this.isConnected&&this._headerRowEl&&this._bodyEl){if(this.#H.parseLightDomColumns(this),this.#h){const e=this.#h;this.#h=void 0,this.#H.merge();const t=this.#X?.getAll()??[];this.#H.applyState(e,t)}this._bodyEl&&(this._bodyEl.style.display="",this._bodyEl.style.gridTemplateColumns=""),this.#O.requestPhase(he.FULL,"setup")}}#Ve(e){let t=0,i=0,n=0,r=0,o=0;if(this.#N){const e=this._virtualization.container,s=this.#ee;t=s?.scrollLeft??0,i=e?.scrollHeight??0,n=s?.scrollWidth??0,r=e?.clientHeight??0,o=s?.clientWidth??0}if(this.refreshVirtualWindow(!1)&&this.#X?.onScrollRender(),this._virtualization.variableHeights&&(this.#V&&clearTimeout(this.#V),this.#V=window.setTimeout(()=>{this.#V=0,this.#nt(this._virtualization.start,this._virtualization.end)},100)),this.#N){const s=this.#Y;s.scrollTop=e,s.scrollLeft=t,s.scrollHeight=i,s.scrollWidth=n,s.clientHeight=r,s.clientWidth=o,this.#X?.onScroll(s)}}findHeaderRow(){return this.#L.querySelector(".header-row")}findRenderedRowElement(e){return Array.from(this._bodyEl.querySelectorAll(".data-grid-row")).find(t=>{const i=t.querySelector(".cell[data-row]");return i&&Number(i.getAttribute("data-row"))===e})||null}_dispatchCellClick(e,t,i,n){const r=this._rows[t],o=this._visibleColumns[i];if(!r||!o)return!1;const s=o.field,l=r[s],a=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,composed:!0,detail:{rowIndex:t,colIndex:i,column:o,field:s,value:l,row:r,cellEl:n,trigger:"pointer",originalEvent:e}});if(this.dispatchEvent(a),a.defaultPrevented)return!0;const d={row:r,rowIndex:t,colIndex:i,column:o,field:s,value:l,cellEl:n,originalEvent:e},c=this.#X?.onCellClick(d)??!1;return this.#Re("cell-click",d),c}_dispatchRowClick(e,t,i,n){if(!i)return!1;const r={rowIndex:t,row:i,rowEl:n,originalEvent:e},o=this.#X?.onRowClick(r)??!1;return this.#Re("row-click",r),o}_dispatchHeaderClick(e,t,i){if(!t)return!1;const n={colIndex:this._columns.indexOf(t),field:t.field,column:t,headerEl:i,originalEvent:e};return this.#X?.onHeaderClick(n)??!1}_dispatchKeyDown(e){return this.#X?.onKeyDown(e)??!1}_getHorizontalScrollOffsets(e,t){return this.#X?.getHorizontalScrollOffsets(e,t)??{left:0,right:0}}queryPlugins(e){return this.#X?.queryPlugins(e)??[]}query(e,t){return this.#X?.queryPlugins({type:e,context:t})??[]}_dispatchCellMouseDown(e){return this.#X?.onCellMouseDown(e)??!1}_dispatchCellMouseMove(e){this.#X?.onCellMouseMove(e)}_dispatchCellMouseUp(e){this.#X?.onCellMouseUp(e)}_afterCellRender(e){this.#X?.afterCellRender(e)}_hasAfterCellRenderHook(){return this.#X?.hasAfterCellRenderHook()??!1}_afterRowRender(e){this.#X?.afterRowRender(e)}_hasAfterRowRenderHook(){return this.#X?.hasAfterRowRenderHook()??!1}async ready(){return this.#E}async forceLayout(){return this.#O.requestPhase(he.FULL,"forceLayout"),this.#O.whenReady()}async getConfig(){return Object.freeze({...this.#s||{}})}getRowId(e){return this.#Ze(e,this.#s.getRowId)}getRow(e){return this.#de.get(e)?.row}_getRowEntry(e){return this.#de.get(e)}updateRow(e,t,i="api"){const n=this.#de.get(e);if(!n)throw new Error(`[tbw-grid] Row with ID "${e}" not found. Ensure the row exists and getRowId is correctly configured.`);const{row:r,index:o}=n,s=[];for(const[l,a]of Object.entries(t)){const e=r[l];e!==a&&(s.push({field:l,oldValue:e,newValue:a}),r[l]=a)}for(const{field:l,oldValue:a,newValue:d}of s)this.#Re("cell-change",{row:r,rowId:e,rowIndex:o,field:l,oldValue:a,newValue:d,changes:t,source:i});s.length>0&&this.#O.requestPhase(he.ROWS,"updateRow")}updateRows(e,t="api"){let i=!1;for(const{id:n,changes:r}of e){const e=this.#de.get(n);if(!e)throw new Error(`[tbw-grid] Row with ID "${n}" not found. Ensure the row exists and getRowId is correctly configured.`);const{row:o,index:s}=e;for(const[l,a]of Object.entries(r)){const e=o[l];e!==a&&(i=!0,o[l]=a,this.#Re("cell-change",{row:o,rowId:n,rowIndex:s,field:l,oldValue:e,newValue:a,changes:r,source:t}))}}i&&this.#O.requestPhase(he.ROWS,"updateRows")}animateRow(e,t){return be(this,e,t)}animateRows(e,t){return function(e,t,i){return Promise.all(t.map(t=>be(e,t,i))).then(e=>e.filter(Boolean).length)}(this,e,t)}animateRowById(e,t){return function(e,t,i){const n=e._rows??[],r=e.getRowId;if(!r)return Promise.resolve(!1);const o=n.findIndex(e=>{if(null==e)return!1;try{return r(e)===t}catch{return!1}});return o<0?Promise.resolve(!1):be(e,o,i)}(this,e,t)}async insertRow(e,t,i=!0){const n=Math.max(0,Math.min(e,this._rows.length));this.#P=[...this.#P,t];const r=[...this._rows];r.splice(n,0,t),this._rows=r,this._sortState&&(this.__originalOrder=[...this.__originalOrder,t]),V(this),this.#Ye(),this.__rowRenderEpoch++;for(const o of this._rowPool)o.__epoch=-1;this.refreshVirtualWindow(!0),i&&(await new Promise(e=>requestAnimationFrame(()=>e())),await this.animateRow(n,"insert"))}async removeRow(e,t=!0){const i=this._rows[e];if(!i)return;t&&await this.animateRow(e,"remove");const n=this._rows.indexOf(i);if(n<0)return i;const r=[...this._rows];r.splice(n,1),this._rows=r;const o=this.#P.indexOf(i);if(o>=0){const e=[...this.#P];e.splice(o,1),this.#P=e}if(this._sortState){const e=this.__originalOrder.indexOf(i);if(e>=0){const t=[...this.__originalOrder];t.splice(e,1),this.__originalOrder=t}}V(this),this.#Ye(),this.__rowRenderEpoch++;for(const s of this._rowPool)s.__epoch=-1;return this.refreshVirtualWindow(!0),t&&requestAnimationFrame(()=>{this.querySelectorAll('[data-animating="remove"]').forEach(e=>{e.removeAttribute("data-animating")})}),i}suspendProcessing(){}setColumnVisible(e,t){const i=this.#H.setColumnVisible(e,t);return i&&this.requestStateChange(),i}toggleColumnVisibility(e){const t=this.#H.toggleColumnVisibility(e);return t&&this.requestStateChange(),t}isColumnVisible(e){return this.#H.isColumnVisible(e)}showAllColumns(){this.#H.showAllColumns(),this.requestStateChange()}getAllColumns(){return this.#H.getAllColumns()}setColumnOrder(e){this.#H.setColumnOrder(e),this.requestStateChange()}getColumnOrder(){return this.#H.getColumnOrder()}getColumnState(){const e=this.#X?.getAll()??[];return this.#H.collectState(e)}set columnState(e){e&&(this.#h=e,this.#H.initialColumnState=e,this.#M&&this.#rt(e))}get columnState(){return this.getColumnState()}#rt(e){const t=this.#X?.getAll()??[];this.#H.applyState(e,t),this.#Se()}requestStateChange(){const e=this.#X?.getAll()??[];this.#H.requestStateChange(e)}resetColumnState(){this.#h=void 0,this.__originalOrder=[];const e=this.#X?.getAll()??[];this.#H.resetState(e),this.#H.merge(),this.#Se()}get isToolPanelOpen(){return this.#ie.isPanelOpen}get defaultRowHeight(){return this._virtualization.rowHeight}get expandedToolPanelSections(){return this.#ie.expandedSections}openToolPanel(){this.#ie.openToolPanel()}closeToolPanel(){this.#ie.closeToolPanel()}toggleToolPanel(){this.#ie.toggleToolPanel()}toggleToolPanelSection(e){this.#ie.toggleToolPanelSection(e)}getToolPanels(){return this.#ie.getToolPanels()}registerToolPanel(e){this.#te.apiToolPanelIds.add(e.id),this.#ie.registerToolPanel(e)}unregisterToolPanel(e){this.#te.apiToolPanelIds.delete(e),this.#ie.unregisterToolPanel(e)}getHeaderContents(){return this.#ie.getHeaderContents()}registerHeaderContent(e){this.#ie.registerHeaderContent(e)}unregisterHeaderContent(e){this.#ie.unregisterHeaderContent(e)}getToolbarContents(){return this.#ie.getToolbarContents()}registerToolbarContent(e){this.#ie.registerToolbarContent(e)}unregisterToolbarContent(e){this.#ie.unregisterToolbarContent(e)}#ot=!1;refreshShellHeader(){this.#ot||(this.#ot=!0,queueMicrotask(()=>{this.#ot=!1,this.isConnected&&(this.#Ie(),this.#H.markSourcesChanged(),this.#H.merge(),Ie(this.#te),this.#De(),this.#ke(),this.#st())}))}#st(){const e=this.#L.querySelector(".tbw-grid-content")??this.#L.querySelector(".tbw-grid-root");if(this._headerRowEl=e?.querySelector(".header-row"),this._virtualization.totalHeightEl=e?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=e?.querySelector(".rows-viewport"),this._bodyEl=e?.querySelector(".rows"),this.__rowsBodyEl=e?.querySelector(".rows-body"),this.#ie.isInitialized){Me(this.#L,this.#te),Le(this.#L,this.#s?.shell,this.#te);const e=this.#s?.shell?.toolPanel?.defaultOpen;e&&this.#te.toolPanels.has(e)&&(this.openToolPanel(),this.#te.expandedSections.add(e))}this._resizeController=ge(this),this.#Me(e),this.#O.requestPhase(he.COLUMNS,"shellRefresh")}#qe=new Map;registerStyles(e,t){let i=this.#qe.get(e);i||(i=new CSSStyleSheet,this.#qe.set(e,i)),i.replaceSync(t),this.#lt()}unregisterStyles(e){this.#qe.delete(e)&&this.#lt()}getRegisteredStyles(){return Array.from(this.#qe.keys())}#lt(){const e=Array.from(this.#qe.values()),t=document.adoptedStyleSheets.filter(e=>!Array.from(this.#qe.values()).includes(e));document.adoptedStyleSheets=[...t,...e]}#Ie(){Ae(this,this.#te),ke(this,this.#te),Te(this,this.#te,this.#He())}#at(){const e=this.#L.querySelector(".tbw-shell-header");if(!e)return;Ie(this.#te);const t=function(e,t,i="☰"){const n=e?.header?.title??t.lightDomTitle??"",r=!!n,o=Se(i),s=e?.header?.toolbarContents??[],l=[...t.toolbarContents.values()],a=new Set(s.map(e=>e.id)),d=[...s];for(const w of l)a.has(w.id)||d.push(w);const c=d.length>0,h=t.toolPanels.size>0,u=c&&h,g=[...d].sort((e,t)=>(e.order??0)-(t.order??0));let p="";for(const w of g)p+=`<div class="tbw-toolbar-content-slot" data-toolbar-content="${w.id}"></div>`;if(u&&(p+='<div class="tbw-toolbar-separator"></div>'),h){const e=t.isPanelOpen;p+=`<button class="${e?"tbw-toolbar-btn active":"tbw-toolbar-btn"}" data-panel-toggle title="Settings" aria-label="Toggle settings panel" aria-pressed="${e}" aria-controls="tbw-tool-panel">${o}</button>`}return`\n <div class="tbw-shell-header" part="shell-header" role="presentation">\n ${r?`<div class="tbw-shell-title">${f=n,f&&"string"==typeof f?f.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"):""}</div>`:""}\n <div class="tbw-shell-content" part="shell-content" role="presentation" data-light-dom-header-content></div>\n <div class="tbw-shell-toolbar" part="shell-toolbar" role="presentation">\n ${p}\n </div>\n </div>\n `;var f}(this.#s.shell,this.#te,this.#s.icons?.toolPanel),i=document.createElement("div");i.innerHTML=t;const n=i.firstElementChild;n&&(e.replaceWith(n),this.#dt(),Le(this.#L,this.#s?.shell,this.#te))}#Oe(){const e=()=>{const e=this.#te.lightDomTitle,t=this.#te.hasToolButtonsContainer;this.#Ie();const i=this.#te.lightDomTitle,n=this.#te.hasToolButtonsContainer;(i&&!e||n&&!t)&&(this.#H.markSourcesChanged(),this.#H.merge(),this.#at())},t=()=>{this.__lightDomColumnsCache=void 0,this.#Se()};this.#H.registerLightDomHandler("tbw-grid-header",e),this.#H.registerLightDomHandler("tbw-grid-tool-buttons",e),this.#H.registerLightDomHandler("tbw-grid-tool-panel",e),this.#H.registerLightDomHandler("tbw-grid-column",t),this.#H.registerLightDomHandler("tbw-grid-detail",t),this.#H.observeLightDOM(this)}refreshColumns(){this.__lightDomColumnsCache=void 0,V(this),this.#H.parseLightDomColumns(this);const e=this.#te.lightDomTitle,t=this.#te.hasToolButtonsContainer;this.#Ie();const i=this.#te.lightDomTitle,n=this.#te.hasToolButtonsContainer;(i&&!e||n&&!t)&&(this.#H.markSourcesChanged(),this.#H.merge(),this.#at()),this.#O.requestPhase(he.COLUMNS,"refreshColumns")}#$e(){const e=this._virtualization.container,t=this._virtualization.viewportEl??e;t&&(this._virtualization.cachedViewportHeight=t.clientHeight),e&&(this._virtualization.cachedFauxHeight=e.clientHeight);const i=this._virtualization.scrollAreaEl;i&&(this._virtualization.cachedScrollAreaHeight=i.clientHeight)}#ye(e,t=!1){const i=this._virtualization;let n,r,o;if(t){const e=i.container??this,t=i.viewportEl??e,s=i.scrollAreaEl;n=e.clientHeight,r=t.clientHeight,o=s?s.clientHeight:n,i.cachedFauxHeight=n,i.cachedViewportHeight=r,i.cachedScrollAreaHeight=o}else n=i.cachedFauxHeight,r=i.cachedViewportHeight,o=i.cachedScrollAreaHeight||n;const s=o-r,l=Math.max(0,n-o);let a,d=0;i.variableHeights&&i.positionCache?a=function(e){if(0===e.length)return 0;const t=e[e.length-1];return t.offset+t.height}(i.positionCache):(a=e*i.rowHeight,d=this.#X?.getExtraHeight()??0);return a+s+d+l}#Ne(){if(!this._virtualization.variableHeights)return;const e=this._rows,t=this._virtualization.rowHeight||28,i=this.#s.rowHeight,n=this.#s.getRowId,r=n?e=>n(e):void 0;this._virtualization.positionCache=function(e,t,i,n,r){const o=new Array(e.length);let s=0;for(let l=0;l<e.length;l++){const a=e[l];let d=r?.(a,l),c=void 0!==d;void 0===d&&(d=Qe(t,a,n.rowId),c=void 0!==d),void 0===d&&(d=i,c=!1),o[l]={offset:s,height:d,measured:c},s+=d}return o}(e,this._virtualization.heightCache,t,{rowId:r},(e,t)=>{const n=this.#X?.getRowHeight?.(e,t);if(void 0!==n)return n;if(i){const n=i(e,t);if(void 0!==n&&n>0)return n}});const o=function(e,t,i,n){let r=0,o=0;for(let s=0;s<e.length;s++){const i=e[s];if(i.measured){const e=n?.(t[s],s);void 0===e&&(o+=i.height,r++)}}return{measuredCount:r,averageHeight:r>0?o/r:i}}(this._virtualization.positionCache,e,t,(e,t)=>this.#X?.getRowHeight?.(e,t));this._virtualization.measuredCount=o.measuredCount,o.measuredCount>0&&(this._virtualization.averageHeight=o.averageHeight)}invalidateRowHeight(e,t){if(!this._virtualization.variableHeights)return;if(!this._virtualization.positionCache)return;if(e<0||e>=this._rows.length)return;const i=this._virtualization.positionCache,n=this._rows[e];let r=t;void 0===r&&(r=this.#X?.getRowHeight?.(n,e)),void 0===r&&(r=this._virtualization.rowHeight);const o=i[e];if(o&&!(Math.abs(o.height-r)<1)&&(Je(i,e,r),this._virtualization.totalHeightEl)){const e=this.#ye(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}#nt(e,t){if(!this._virtualization.variableHeights)return;if(!this._virtualization.positionCache)return;if(!this._bodyEl)return;const i=this._bodyEl.querySelectorAll(".data-grid-row"),n=this.#s.getRowId,r=tt({positionCache:this._virtualization.positionCache,heightCache:this._virtualization.heightCache,rows:this._rows,defaultHeight:this._virtualization.rowHeight,start:e,end:t,getPluginHeight:(e,t)=>this.#X?.getRowHeight?.(e,t),getRowId:n?e=>n(e):void 0},i);if(r.hasChanges&&(this._virtualization.measuredCount=r.measuredCount,this._virtualization.averageHeight=r.averageHeight,this._virtualization.totalHeightEl)){const e=this.#ye(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}refreshVirtualWindow(e=!1,t=!1){if(!this._bodyEl)return!1;const i=this._rows.length;if(!this._virtualization.enabled)return this.#et(0,i),t||this.#X?.afterRender(),!0;if(this._rows.length<=this._virtualization.bypassThreshold)return this._virtualization.start=0,this._virtualization.end=i,e&&(this._bodyEl.style.transform="translateY(0px)"),this.#et(0,i,this.__rowRenderEpoch),e&&this._virtualization.totalHeightEl&&(this._virtualization.totalHeightEl.style.height=`${this.#ye(i,!0)}px`),this.#it(i,this._visibleColumns.length),t||this.#X?.afterRender(),!0;const n=this._virtualization.container??this,r=this._virtualization.viewportEl??n,o=e?this._virtualization.cachedViewportHeight=r.clientHeight:this._virtualization.cachedViewportHeight||(this._virtualization.cachedViewportHeight=r.clientHeight),s=this._virtualization.rowHeight,l=n.scrollTop;let a;const d=this._virtualization.positionCache;if(this._virtualization.variableHeights&&d&&d.length>0)a=et(d,l),-1===a&&(a=0);else{a=Math.floor(l/s);let e=0;const t=10;for(;e<t;){const t=this.#X?.getExtraHeightBefore?.(a)??0,i=Math.floor((l-t)/s);if(i>=a||i<0)break;a=i,e++}}a-=a%2,a<0&&(a=0);const c=this.#X?.adjustVirtualStart(a,l,s);let h;if(void 0!==c&&c<a&&(a=c,a-=a%2,a<0&&(a=0)),this._virtualization.variableHeights&&d&&d.length>0){const e=o+3*s;let t=0;for(h=a;h<i&&t<e;)t+=d[h].height,h++;const n=Math.ceil(o/s)+3;h-a<n&&(h=Math.min(a+n,i))}else{h=a+(Math.ceil(o/s)+3)}h>i&&(h=i);const u=this._virtualization.start,g=this._virtualization.end;if(!e&&a===u&&h===g)return!1;this._virtualization.start=a,this._virtualization.end=h;const p=e?this._virtualization.cachedFauxHeight=n.clientHeight:this._virtualization.cachedFauxHeight||(this._virtualization.cachedFauxHeight=n.clientHeight);if(e){const e=this._virtualization.scrollAreaEl;e&&(this._virtualization.cachedScrollAreaHeight=e.clientHeight)}if(0===p&&o>0)return this.#O.requestPhase(he.VIRTUALIZATION,"stale-refs-retry"),!1;if(e&&this._virtualization.totalHeightEl){const e=this.#ye(i);this._virtualization.totalHeightEl.style.height=`${e}px`}let f;if(this._virtualization.variableHeights&&d&&d[a])f=d[a].offset;else{f=a*s+(this.#X?.getExtraHeightBefore?.(a)??0)}const w=-(l-f);return this._bodyEl.style.transform=`translateY(${w}px)`,this.#et(a,h,this.__rowRenderEpoch),e&&this._virtualization.variableHeights&&this.#nt(a,h),this.#it(i,this._visibleColumns.length),e&&!t&&(this.#X?.afterRender(),queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const e=this.#ye(i);0===this._virtualization.cachedFauxHeight&&this._virtualization.cachedViewportHeight>0||(this._virtualization.totalHeightEl.style.height=`${e}px`)})),!0}#De(){this.#Ie(),this.#H.markSourcesChanged(),this.#H.merge();const e=this.#s?.shell;Oe(this.#L,e,{isPanelOpen:this.#te.isPanelOpen,expandedSections:this.#te.expandedSections},this.#s?.icons)&&(this.#dt(),this.#ie.setInitialized(!0))}#dt(){!function(e,t,i,n){const r=e.querySelector(".tbw-shell-toolbar");r&&r.addEventListener("click",e=>{e.target.closest("[data-panel-toggle]")&&n.onPanelToggle()});const o=e.querySelector(".tbw-accordion");o&&o.addEventListener("click",e=>{const t=e.target.closest(".tbw-accordion-header");if(t){const e=t.closest("[data-section]"),i=e?.getAttribute("data-section");i&&n.onSectionToggle(i)}})}(this.#L,this.#s,this.#te,{onPanelToggle:()=>this.toggleToolPanel(),onSectionToggle:e=>this.toggleToolPanelSection(e)}),this.#ne?.(),this.#ne=function(e,t,i){const n=e.querySelector(".tbw-tool-panel"),r=e.querySelector("[data-resize-handle]"),o=e.querySelector(".tbw-shell-body");if(!n||!r||!o)return()=>{};const s=t?.toolPanel?.position??"right";let l=0,a=0,d=0,c=!1;const h=e=>{if(!c)return;e.preventDefault();const t="left"===s?e.clientX-l:l-e.clientX,i=Math.min(d,Math.max(200,a+t));n.style.width=`${i}px`},u=()=>{if(!c)return;c=!1,r.classList.remove("resizing"),n.style.transition="",document.body.style.cursor="",document.body.style.userSelect="";const e=n.getBoundingClientRect().width;i(e),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",u)},g=e=>{e.preventDefault(),c=!0,l=e.clientX,a=n.getBoundingClientRect().width,d=o.getBoundingClientRect().width-20,r.classList.add("resizing"),n.style.transition="none",document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",h),document.addEventListener("mouseup",u)};return r.addEventListener("mousedown",g),()=>{r.removeEventListener("mousedown",g),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",u)}}(this.#L,this.#s?.shell,e=>{this.style.setProperty("--tbw-tool-panel-width",`${e}px`)}),this.#re?.(),this.#re=function(e,t,i,n){if(!t?.toolPanel?.closeOnClickOutside)return()=>{};const r=e=>{if(!i.isPanelOpen)return;const t=e.target;t&&(t.closest(".tbw-tool-panel")||t.closest("[data-panel-toggle]")||n())};return e.addEventListener("mousedown",r),()=>e.removeEventListener("mousedown",r)}(this,this.#s?.shell,this.#te,()=>this.closeToolPanel())}}customElements.get(nt.tagName)||customElements.define(nt.tagName,nt),globalThis.DataGridElement=nt;class rt{static dependencies;static manifest;version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#ct;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}attach(e){this.#ct?.abort(),this.#ct=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#ct?.abort(),this.#ct=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const i=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(i),i.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid}get disconnectSignal(){return this.#ct?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...r,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),i=parseInt(t,10);if(!isNaN(i))return i}return 200}resolveIcon(e,t){return void 0!==t?t:this.gridIcons[e]}setIcon(e,t){"string"==typeof t?e.innerHTML=t:t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}warn(e){console.warn(`[tbw-grid:${this.name}] ${e}`)}}const ot={ROOT:"tbw-grid-root",HEADER:"header",HEADER_ROW:"header-row",HEADER_CELL:"header-cell",ROWS_VIEWPORT:"rows-viewport",ROWS_SPACER:"rows-spacer",ROWS_CONTAINER:"rows",DATA_ROW:"data-row",GROUP_ROW:"group-row",DATA_CELL:"data-cell",SELECTED:"selected",FOCUSED:"focused",EDITING:"editing",EXPANDED:"expanded",COLLAPSED:"collapsed",DRAGGING:"dragging",RESIZING:"resizing",SORTABLE:"sortable",SORTED_ASC:"sorted-asc",SORTED_DESC:"sorted-desc",HIDDEN:"hidden",STICKY_LEFT:"sticky-left",STICKY_RIGHT:"sticky-right",PINNED_TOP:"pinned-top",PINNED_BOTTOM:"pinned-bottom",TREE_TOGGLE:"tree-toggle",TREE_INDENT:"tree-indent",GROUP_TOGGLE:"group-toggle",GROUP_LABEL:"group-label",GROUP_COUNT:"group-count",RANGE_SELECTION:"range-selection",SELECTION_OVERLAY:"selection-overlay"},st={ROW_INDEX:"data-row-index",COL_INDEX:"data-col-index",FIELD:"data-field",GROUP_KEY:"data-group-key",TREE_LEVEL:"data-tree-level",STICKY:"data-sticky"},lt={ROOT:`.${ot.ROOT}`,HEADER:`.${ot.HEADER}`,HEADER_ROW:`.${ot.HEADER_ROW}`,HEADER_CELL:`.${ot.HEADER_CELL}`,ROWS_VIEWPORT:`.${ot.ROWS_VIEWPORT}`,ROWS_CONTAINER:`.${ot.ROWS_CONTAINER}`,DATA_ROW:`.${ot.DATA_ROW}`,DATA_CELL:`.${ot.DATA_CELL}`,GROUP_ROW:`.${ot.GROUP_ROW}`,ROW_BY_INDEX:e=>`.${ot.DATA_ROW}[${st.ROW_INDEX}="${e}"]`,CELL_BY_FIELD:e=>`.${ot.DATA_CELL}[${st.FIELD}="${e}"]`,CELL_AT:(e,t)=>`.${ot.DATA_ROW}[${st.ROW_INDEX}="${e}"] .${ot.DATA_CELL}[${st.COL_INDEX}="${t}"]`,SELECTED_ROWS:`.${ot.DATA_ROW}.${ot.SELECTED}`,EDITING_CELL:`.${ot.DATA_CELL}.${ot.EDITING}`};function at(e,t,i=!0){let n=e;if(i&&(n=n.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.meta?.utility)),t?.length){const e=new Set(t);n=n.filter(t=>e.has(t.field))}return n}function dt(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}function ct(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}function ht(e,t){const i=t.delimiter??"\t",n=t.newline??"\n",r=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),o=[];let s=[],l="",a=!1;for(let d=0;d<r.length;d++){const e=r[d];'"'!==e||a?'"'===e&&a?'"'===r[d+1]?(l+='"',d++):a=!1:e!==i||a?e!==n||a?l+=e:(s.push(l),l="",(s.length>1||s.some(e=>""!==e.trim()))&&o.push(s),s=[]):(s.push(l),l=""):a=!0}return s.push(l),(s.length>1||s.some(e=>""!==e.trim()))&&o.push(s),o}function ut(e,t){const{rows:i,target:n,fields:r}=e;if(!n)return;const o=t.rows,s=t.effectiveConfig.columns??[],l=s.map(e=>e.field),a=new Map;s.forEach(e=>{a.set(e.field,!0===e.editable)});const d=[...o],c=n.bounds?n.bounds.endRow:1/0;i.forEach((e,t)=>{const i=n.row+t;if(!(i>c)){if(n.bounds){if(i>=d.length)return}else for(;i>=d.length;){const e={};l.forEach(t=>e[t]=""),d.push(e)}d[i]={...d[i]},e.forEach((e,t)=>{const n=r[t];n&&a.get(n)&&(d[i][n]=e)})}}),t.rows=d}function gt(e){if(null==e)return 100;if("number"==typeof e)return e;const t=parseFloat(e);return isNaN(t)?100:t}function pt(e){return e.map(e=>gt(e.width))}function ft(e){const t=[];let i=0;for(const n of e)t.push(i),i+=gt(n.width);return t}function wt(e){return e.reduce((e,t)=>e+gt(t.width),0)}function mt(e,t,i,n,r){const o=i.length;if(0===o)return{startCol:0,endCol:0,visibleColumns:[]};let s=function(e,t,i){let n=0,r=t.length-1;for(;n<r;){const o=Math.floor((n+r)/2);t[o]+i[o]<=e?n=o+1:r=o}return n}(e,i,n);s=Math.max(0,s-r);const l=e+t;let a=s;for(let c=s;c<o;c++){if(i[c]>=l){a=c-1;break}a=c}a=Math.min(o-1,a+r);const d=[];for(let c=s;c<=a;c++)d.push(c);return{startCol:s,endCol:a,visibleColumns:d}}const bt="@layer tbw-plugins{.tbw-context-menu{position:fixed;background:var(--tbw-context-menu-bg, var(--tbw-color-panel-bg));color:var(--tbw-context-menu-fg, var(--tbw-color-fg));border:1px solid var(--tbw-context-menu-border, var(--tbw-color-border));border-radius:var(--tbw-context-menu-radius, var(--tbw-border-radius));box-shadow:var(--tbw-context-menu-shadow, 0 2px 10px var(--tbw-color-shadow));min-width:var(--tbw-context-menu-min-width, var(--tbw-menu-min-width));padding:var(--tbw-spacing-xs) 0;z-index:10000;font-size:var(--tbw-context-menu-font-size, var(--tbw-font-size-sm));font-family:var(--tbw-context-menu-font-family, var(--tbw-font-family))}.tbw-context-menu-item{display:flex;align-items:center;padding:var(--tbw-context-menu-item-padding, var(--tbw-menu-item-padding));cursor:pointer;gap:var(--tbw-context-menu-item-gap, var(--tbw-menu-item-gap))}.tbw-context-menu-item:hover:not(.disabled){background:var(--tbw-context-menu-hover, var(--tbw-color-row-hover))}.tbw-context-menu-item.disabled{opacity:.5;cursor:default}.tbw-context-menu-item.danger{color:var(--tbw-context-menu-danger, var(--tbw-color-danger))}.tbw-context-menu-icon{width:var(--tbw-context-menu-icon-size, var(--tbw-icon-size));text-align:center}.tbw-context-menu-label{flex:1}.tbw-context-menu-shortcut kbd{color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted));font-size:var(--tbw-context-menu-shortcut-size, var(--tbw-font-size-xs))}.tbw-context-menu-arrow{font-size:var(--tbw-context-menu-arrow-size, var(--tbw-font-size-2xs));color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted))}.tbw-context-menu-separator{height:1px;background:var(--tbw-context-menu-border, var(--tbw-color-border));margin:var(--tbw-spacing-xs) 0}}";function vt(e,t){return("function"==typeof e?e(t):e).filter(e=>!0!==e.hidden&&("function"!=typeof e.hidden||!e.hidden(t)))}function yt(e){const t=[];for(const i of e)i.separator&&(0===t.length||t[t.length-1].separator)||t.push(i);return t.length>0&&t[t.length-1].separator&&t.pop(),t}function Ct(e,t){return!0===e.disabled||"function"==typeof e.disabled&&e.disabled(t)}function xt(e,t,i,n=r.submenuArrow){const o=document.createElement("div");o.className="tbw-context-menu",o.setAttribute("role","menu");const s=e.some(e=>!e.separator&&e.icon);for(const r of e){if(r.separator){const e=document.createElement("div");e.className="tbw-context-menu-separator",e.setAttribute("role","separator"),o.appendChild(e);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",r.cssClass&&e.classList.add(r.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",r.id);const l=Ct(r,t);if(l&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),r.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=r.icon,e.appendChild(t)}else if(s){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML="&nbsp;",e.appendChild(t)}const a=document.createElement("span");if(a.className="tbw-context-menu-label",a.textContent=r.name,e.appendChild(a),r.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(r.shortcut))r.shortcut.forEach((e,i)=>{i>0&&t.appendChild(document.createTextNode("+"));const n=document.createElement("kbd");n.textContent=e,t.appendChild(n)});else{const e=document.createElement("kbd");e.textContent=r.shortcut,t.appendChild(e)}e.appendChild(t)}if(r.subMenu?.length){const o=document.createElement("span");o.className="tbw-context-menu-arrow","string"==typeof n?o.innerHTML=n:n instanceof HTMLElement&&o.appendChild(n.cloneNode(!0)),e.appendChild(o),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!r.subMenu)return;const o=xt(vt(r.subMenu,t),t,i,n);o.classList.add("tbw-context-submenu"),o.style.position="absolute",o.style.left="100%",o.style.top="0",e.style.position="relative",e.appendChild(o)}),e.addEventListener("mouseleave",()=>{const t=e.querySelector(".tbw-context-menu");t&&t.remove()})}l||!r.action||r.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),i(r)}),o.appendChild(e)}return o}function Et(e,t,i){e.style.position="fixed",e.style.left=`${t}px`,e.style.top=`${i}px`,e.style.visibility="hidden",e.style.zIndex="10000";const n=e.getBoundingClientRect(),r=window.innerWidth,o=window.innerHeight;let s=t,l=i;t+n.width>r&&(s=t-n.width),i+n.height>o&&(l=i-n.height),s=Math.max(0,s),l=Math.max(0,l),e.style.left=`${s}px`,e.style.top=`${l}px`,e.style.visibility="visible"}const Rt="getContextMenuItems";let St=null,_t=null,At=null,kt=0;const Tt=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:e=>{const t=e.grid;t?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:e=>{const t=e.grid;t?.plugins?.export?.exportCsv?.()}}];class Lt extends rt{static manifest={queries:[{type:Rt,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:Tt}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),kt++}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,this.uninstallGlobalHandlers()}syncSelectionOnContextMenu(e){if(e<0)return[];const t=this.grid?.query("getSelectedRowIndices"),i=t?.[0];return i?i.includes(e)?i:(this.grid?.query("selectRows",[e]),[e]):[e]}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size"];copyGridStyles(e){const t=this.gridElement;if(!t)return;const i=getComputedStyle(t),n=[],r=i.getPropertyValue("color-scheme").trim();r&&n.push(`color-scheme: ${r}`);for(const o of Lt.CSS_VARS_TO_COPY){const e=i.getPropertyValue(o).trim();e&&n.push(`${o}: ${e}`)}if(n.length>0){const t=e.getAttribute("style")||"";e.setAttribute("style",t+n.join("; ")+";")}}installGlobalHandlers(){!At&&"undefined"!=typeof document&&bt&&(At=document.createElement("style"),At.id="tbw-context-menu-styles",At.textContent=bt,document.head.appendChild(At)),St||(St=()=>{document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())},document.addEventListener("click",St)),_t||(_t=e=>{if("Escape"===e.key){document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())}},document.addEventListener("keydown",_t))}uninstallGlobalHandlers(){kt--,kt>0||(St&&(document.removeEventListener("click",St),St=null),_t&&(document.removeEventListener("keydown",_t),_t=null),At&&(At.remove(),At=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(Rt,e),i=[];for(const n of t)Array.isArray(n)&&i.push(...n);return i.sort((e,t)=>(e.order??100)-(t.order??100)),this.insertGroupSeparators(i)}insertGroupSeparators(e){if(e.length<=1)return e;const t=[];let i=-1;for(const n of e){if(n.separator){t.push(n);continue}const e=Math.floor((n.order??100)/10);i>=0&&e!==i&&t.push({id:`__sep-${i}-${e}`,label:"",separator:!0,action:()=>{}}),i=e,t.push(n)}return t}convertPluginItems(e){return e.map(e=>({id:e.id,name:e.label,icon:e.icon,shortcut:e.shortcut,disabled:e.disabled??!1,action:()=>e.action(),separator:e.separator,cssClass:e.cssClass}))}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root");t&&"true"!==t.getAttribute("data-context-menu-bound")&&(t.setAttribute("data-context-menu-bound","true"),t.addEventListener("contextmenu",e=>{const t=e;t.preventDefault();const i=t.target,n=i.closest("[data-row][data-col]"),r=i.closest('[part~="header-cell"]');let o;if(n){const e=parseInt(n.getAttribute("data-row")??"-1",10),i=parseInt(n.getAttribute("data-col")??"-1",10),r=this.visibleColumns[i],s=this.rows[e],l=this.syncSelectionOnContextMenu(e);o={row:s,rowIndex:e,column:r,columnIndex:i,field:r?.field??"",value:s?.[r?.field]??null,isHeader:!1,event:t,selectedRows:l}}else{if(!r)return;{const e=parseInt(r.getAttribute("data-col")??"-1",10),i=this.visibleColumns[e];o={row:null,rowIndex:-1,column:i,columnIndex:e,field:i?.field??"",value:null,isHeader:!0,event:t,selectedRows:[]}}}this.params=o,this.position={x:t.clientX,y:t.clientY};const s=this.collectPluginItems(o);let l=vt(this.config.items??Tt,o);if(s.length>0){const e=this.convertPluginItems(s);l=l.length>0&&e.length>0?[...l,{id:"__plugin-sep",name:"",separator:!0},...e]:[...l,...e]}l=yt(l),l.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=xt(l,o,e=>{e.action&&e.action(o),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),Et(this.menuElement,t.clientX,t.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:o,items:l}))}))}showMenu(e,t,i){const n={row:i.row??null,rowIndex:i.rowIndex??-1,column:i.column??null,columnIndex:i.columnIndex??-1,field:i.field??"",value:i.value??null,isHeader:i.isHeader??!1,event:i.event??new MouseEvent("contextmenu"),selectedRows:i.selectedRows??[]},r=this.collectPluginItems(n);let o=vt(this.config.items??Tt,n);if(r.length>0){const e=this.convertPluginItems(r);o=o.length>0&&e.length>0?[...o,{id:"__plugin-sep",name:"",separator:!0},...e]:[...o,...e]}o=yt(o),this.menuElement&&this.menuElement.remove(),this.menuElement=xt(o,n,e=>{e.action&&e.action(n),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),Et(this.menuElement,e,t),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}function Mt(e){switch(e.type){case"number":return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");n.type="number",n.value=null!=t.value?String(t.value):"",void 0!==i?.min&&(n.min=String(i.min)),void 0!==i?.max&&(n.max=String(i.max)),void 0!==i?.step&&(n.step=String(i.step)),i?.placeholder&&(n.placeholder=i.placeholder);const r=()=>t.commit(""===n.value?null:Number(n.value));return n.addEventListener("blur",r),n.addEventListener("keydown",e=>{"Enter"===e.key&&r(),"Escape"===e.key&&t.cancel()}),n}}(e);case"boolean":return e=>{const t=document.createElement("input");return t.type="checkbox",t.checked=!!e.value,t.addEventListener("change",()=>e.commit(t.checked)),t};case"date":return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");return n.type="date",t.value instanceof Date?n.valueAsDate=t.value:"string"==typeof t.value&&t.value&&(n.value=t.value.split("T")[0]),i?.min&&(n.min=i.min),i?.max&&(n.max=i.max),i?.placeholder&&(n.placeholder=i.placeholder),n.addEventListener("change",()=>{"string"==typeof t.value?t.commit(n.value):t.commit(n.valueAsDate)}),n.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),n}}(e);case"select":return function(e){return t=>{const i=e.editorParams,n=document.createElement("select");if(e.multi&&(n.multiple=!0),i?.includeEmpty){const e=document.createElement("option");e.value="",e.textContent=i.emptyLabel??"",n.appendChild(e)}const r=function(e){const t=e.options;return t?"function"==typeof t?t():t:[]}(e);r.forEach(i=>{const r=document.createElement("option");r.value=String(i.value),r.textContent=i.label,e.multi&&Array.isArray(t.value)&&t.value.includes(i.value)?r.selected=!0:e.multi||t.value!==i.value||(r.selected=!0),n.appendChild(r)});const o=()=>{if(e.multi){const e=Array.from(n.selectedOptions).map(e=>e.value);t.commit(e)}else t.commit(n.value)};return n.addEventListener("change",o),n.addEventListener("blur",o),n.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),n}}(e);default:return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");n.type="text",n.value=null!=t.value?String(t.value):"",void 0!==i?.maxLength&&(n.maxLength=i.maxLength),i?.pattern&&(n.pattern=i.pattern),i?.placeholder&&(n.placeholder=i.placeholder);const r=()=>{const e=n.value;(null!==t.value&&void 0!==t.value||""!==e)&&("string"==typeof t.value&&e===t.value.replace(/[\n\r]/g,"")||("number"==typeof t.value&&""!==e?t.commit(Number(e)):t.commit(e)))};return n.addEventListener("blur",r),n.addEventListener("keydown",e=>{"Enter"===e.key&&r(),"Escape"===e.key&&t.cancel()}),n}}(e)}}function Pt(e){return"string"==typeof e&&("__proto__"!==e&&"constructor"!==e&&"prototype"!==e)}function Ht(e,t,i){return e instanceof HTMLInputElement?"checkbox"===e.type?e.checked:"number"===e.type?""===e.value?null:Number(e.value):"date"===e.type?"string"==typeof i?e.value:e.valueAsDate:"number"==typeof i?""===e.value?null:Number(e.value):null==i&&""===e.value||"string"==typeof i&&e.value===i.replace(/[\n\r]/g,"")?i:e.value:"number"===t?.type&&""!==e.value||"number"==typeof i&&""!==e.value?Number(e.value):null==i&&""===e.value?i:e.value}function It(e){}function Dt(e,t=!0){if(null==e)return"";if(e instanceof Date)return e.toISOString();if("object"==typeof e)return JSON.stringify(e);const i=String(e);return t&&(i.includes(",")||i.includes('"')||i.includes("\n")||i.includes("\r"))?`"${i.replace(/"/g,'""')}"`:i}function zt(e,t){const i=URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(i)}function Ot(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}const qt="(Blank)";function Ft(e){if(e instanceof Date)return e.getTime();const t=Number(e);if(!isNaN(t))return t;return new Date(e).getTime()}function Nt(e,t,i=!1,n){return t.length?e.filter(e=>t.every(t=>function(e,t,i=!1,n){const r=e[t.field];if("blank"===t.operator)return null==r||""===r;if("notBlank"===t.operator)return null!=r&&""!==r;if(n&&("notIn"===t.operator||"in"===t.operator)){const i=n(r,e),o=Array.isArray(i)?i:null!=i?[i]:[];if("notIn"===t.operator){const e=t.value;return!Array.isArray(e)||(0===o.length?!e.includes(qt):!o.some(t=>e.includes(t)))}if("in"===t.operator){const e=t.value;return!!Array.isArray(e)&&(0===o.length?e.includes(qt):o.some(t=>e.includes(t)))}}if("notIn"===t.operator)return null==r||""===r?!Array.isArray(t.value)||!t.value.includes(qt):Array.isArray(t.value)&&!t.value.includes(r);if("in"===t.operator)return null==r||""===r?Array.isArray(t.value)&&t.value.includes(qt):Array.isArray(t.value)&&t.value.includes(r);if(null==r)return!1;const o=String(r),s=i?o:o.toLowerCase(),l=i?String(t.value):String(t.value).toLowerCase();switch(t.operator){case"contains":return s.includes(l);case"notContains":return!s.includes(l);case"equals":return s===l;case"notEquals":return s!==l;case"startsWith":return s.startsWith(l);case"endsWith":return s.endsWith(l);case"lessThan":return Ft(r)<Ft(t.value);case"lessThanOrEqual":return Ft(r)<=Ft(t.value);case"greaterThan":return Ft(r)>Ft(t.value);case"greaterThanOrEqual":return Ft(r)>=Ft(t.value);case"between":return Ft(r)>=Ft(t.value)&&Ft(r)<=Ft(t.valueTo);default:return!0}}(e,t,i,n?.get(t.field)))):e}function Gt(e,t,i){const n=new Set;let r=!1;for(const o of e){const e=o[t];if(i){const t=i(e,o);if(Array.isArray(t)){0===t.length&&(r=!0);for(const e of t)null!=e&&n.add(e)}else null!=t?n.add(t):r=!0}else null!=e&&""!==e?n.add(e):r=!0}return r&&n.add(qt),[...n].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t)))}function Vt(e,t){const i=new Map;for(const{field:r,filterValue:o}of t)i.set(r,{values:new Set,hasBlank:!1,hasExtractor:!!o});for(const r of e)for(const{field:e,filterValue:n}of t){const t=i.get(e),o=r[e];if(n){const e=n(o,r);if(Array.isArray(e)){0===e.length&&(t.hasBlank=!0);for(const i of e)null!=i&&t.values.add(i)}else null!=e?t.values.add(e):t.hasBlank=!0}else null!=o&&""!==o?t.values.add(o):t.hasBlank=!0}const n=new Map;for(const[r,{values:o,hasBlank:s}]of i)s&&o.add(qt),n.set(r,[...o].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t))));return n}const $t="__tbw_expander";function Bt(e){return e.field===$t}function Wt(e){return!0===e.meta?.utility}class Kt extends rt{static manifest={events:[{type:"filter-applied",description:"Emitted when filter criteria change. Subscribers can react to row visibility changes."}],queries:[{type:"getContextMenuItems",description:"Contributes filter-related items to the header context menu"}]};name="filtering";styles='@layer tbw-plugins{tbw-grid .tbw-quick-filter-input{flex:1;max-width:300px;height:var(--tbw-input-height, 1.75rem);padding:var(--tbw-input-padding, 0 .5rem);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);background:var(--tbw-color-bg);color:var(--tbw-color-fg);font-size:var(--tbw-font-size-sm, .8125rem)}tbw-grid .tbw-quick-filter-input:focus{outline:none;border-color:var(--tbw-color-accent)}tbw-grid .header-cell.filtered:before{content:"";position:absolute;top:var(--tbw-spacing-xs, .25rem);right:var(--tbw-spacing-xs, .25rem);width:var(--tbw-indicator-size, .375rem);height:var(--tbw-indicator-size, .375rem);background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border-radius:50%}tbw-grid .tbw-filter-btn{display:var(--tbw-filter-btn-display, inline-flex);visibility:var(--tbw-filter-btn-visibility, visible);align-items:center;justify-content:center;background:transparent;border:none;cursor:pointer;padding:2px;margin-left:var(--tbw-spacing-xs, .25rem);opacity:.4;transition:opacity .15s,visibility 0s,display 0s allow-discrete;color:inherit;vertical-align:middle;transition-behavior:allow-discrete}tbw-grid .tbw-filter-btn:hover,tbw-grid .tbw-filter-btn.active{opacity:1;visibility:visible;display:inline-flex}tbw-grid .tbw-filter-btn.active{color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6))}tbw-grid .header-row .cell:hover .tbw-filter-btn,tbw-grid .header-row .cell.filtered .tbw-filter-btn{display:inline-flex;visibility:visible}}';get defaultConfig(){return{debounceMs:300,caseSensitive:!1,trimInput:!0,useWorker:!0}}isFilteringEnabled(){return!1!==this.grid.effectiveConfig?.filterable}isColumnFilterable(e){return!!this.isFilteringEnabled()&&!1!==e.filterable}getFilterValues(){const e=this.grid.effectiveConfig?.columns;if(!e)return;let t;for(const i of e)i.field&&i.filterValue&&(t||(t=new Map),t.set(i.field,i.filterValue));return t}filters=new Map;cachedResult=null;cacheKey=null;cachedInputSpot=null;openPanelField=null;panelElement=null;panelAnchorElement=null;searchText=new Map;excludedValues=new Map;panelAbortController=null;globalStylesInjected=!1;static DEFAULT_LIST_ITEM_HEIGHT=28;static LIST_OVERSCAN=3;static LIST_BYPASS_THRESHOLD=50;getListItemHeight(){if(this.panelElement){const e=getComputedStyle(this.panelElement).getPropertyValue("--tbw-filter-item-height");if(e&&e.trim()){const t=parseFloat(e);if(!isNaN(t)&&t>0)return t}}return Kt.DEFAULT_LIST_ITEM_HEIGHT}computeSelected(){const e=[];for(const[n,r]of this.filters){if("set"!==r.type||"notIn"!==r.operator)continue;const t=this.grid.effectiveConfig?.columns?.find(e=>e.field===n);e.push({field:n,filterValue:t?.filterValue})}if(0===e.length)return{};const t=Vt(this.sourceRows,e),i={};for(const{field:n}of e){const e=this.excludedValues.get(n),r=t.get(n)??[];i[n]=e?r.filter(t=>!e.has(t)):r}return i}syncExcludedValues(e,t){t?"set"===t.type&&"notIn"===t.operator&&Array.isArray(t.value)?this.excludedValues.set(e,new Set(t.value)):"set"===t.type&&this.excludedValues.delete(e):this.excludedValues.delete(e)}attach(e){super.attach(e),this.injectGlobalStyles()}detach(){this.filters.clear(),this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,this.openPanelField=null,this.panelElement&&(this.panelElement.remove(),this.panelElement=null),this.searchText.clear(),this.excludedValues.clear(),this.panelAbortController?.abort(),this.panelAbortController=null}handleQuery(e){if("getContextMenuItems"===e.type){const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field)return;if(!this.isFilteringEnabled())return;if(!this.isColumnFilterable(i))return;const n=[],r=this.isFieldFiltered(i.field),o=this.filters.size>0;return r&&n.push({id:"filtering/clear-column-filter",label:"Clear Filter",icon:"✕",order:20,action:()=>this.clearFieldFilter(i.field)}),o&&n.push({id:"filtering/clear-all-filters",label:"Clear All Filters",icon:"✕",order:21,disabled:!o,action:()=>this.clearAllFilters()}),n.length>0?n:void 0}}processRows(e){const t=[...this.filters.values()];if(!t.length)return[...e];if(this.config.filterHandler)return this.cachedResult?this.cachedResult:[...e];const i=(n=t,JSON.stringify(n.map(e=>({field:e.field,operator:e.operator,value:e.value,valueTo:e.valueTo}))));var n;const r={len:e.length,first:e[0],mid:e[Math.floor(e.length/2)],last:e[e.length-1]},o=null!=this.cachedInputSpot&&r.len===this.cachedInputSpot.len&&r.first===this.cachedInputSpot.first&&r.mid===this.cachedInputSpot.mid&&r.last===this.cachedInputSpot.last;if(this.cacheKey===i&&this.cachedResult&&o)return this.cachedResult;const s=Nt([...e],t,this.config.caseSensitive,this.getFilterValues());return this.cachedResult=s,this.cacheKey=i,this.cachedInputSpot=r,s}afterRender(){const e=this.gridElement;if(!e)return;e.querySelectorAll('[part~="header-cell"]').forEach(e=>{const t=e.getAttribute("data-col");if(null===t)return;const i=this.visibleColumns[parseInt(t,10)];if(!i||!this.isColumnFilterable(i))return;if(Wt(i))return;const n=i.field;if(!n)return;const r=this.filters.has(n);let o=e.querySelector(".tbw-filter-btn");if(o){const t=o.classList.contains("active");if(o.classList.toggle("active",r),e.classList.toggle("filtered",r),t!==r){const e=r?"filterActive":"filter";this.setIcon(o,this.resolveIcon(e))}return}o=document.createElement("button"),o.className="tbw-filter-btn",o.setAttribute("aria-label",`Filter ${i.header??n}`);const s=r?"filterActive":"filter";this.setIcon(o,this.resolveIcon(s)),r&&(o.classList.add("active"),e.classList.add("filtered")),o.addEventListener("click",e=>{e.stopPropagation(),this.toggleFilterPanel(n,i,o)});const l=e.querySelector(".resize-handle");l?e.insertBefore(o,l):e.appendChild(o)})}setFilter(e,t){if(null===t)this.filters.delete(e),this.syncExcludedValues(e,null);else{const i={...t,field:e};this.filters.set(e,i),this.syncExcludedValues(e,i)}this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:[...this.filters.values()]}),this.requestRender()}getFilter(e){return this.filters.get(e)}getFilters(){return[...this.filters.values()]}getFilterModel(){return this.getFilters()}setFilterModel(e){this.filters.clear(),this.excludedValues.clear();for(const t of e)this.filters.set(t.field,t),this.syncExcludedValues(t.field,t);this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:[...this.filters.values()]}),this.requestRender()}clearAllFilters(){this.filters.clear(),this.excludedValues.clear(),this.searchText.clear(),this.applyFiltersInternal()}clearFieldFilter(e){this.filters.delete(e),this.excludedValues.delete(e),this.searchText.delete(e),this.applyFiltersInternal()}isFieldFiltered(e){return this.filters.has(e)}getFilteredRowCount(){return this.cachedResult?.length??this.rows.length}getActiveFilters(){return this.getFilters()}getUniqueValues(e){const t=this.grid.effectiveConfig?.columns?.find(t=>t.field===e),i=t?.filterValue;return Gt(this.sourceRows,e,i)}copyGridThemeContext(e){const t=this.gridElement;if(!t)return;for(const n of t.classList)n.startsWith("tbw-")||"selecting"===n||e.classList.add(n);const i=t.dataset.theme;i&&(e.dataset.theme=i)}injectGlobalStyles(){if(this.globalStylesInjected)return;if(document.getElementById("tbw-filter-panel-styles"))return void(this.globalStylesInjected=!0);const e=document.createElement("style");e.id="tbw-filter-panel-styles",e.textContent="@layer tbw-plugins{.tbw-filter-panel{position:fixed;background:var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));color:var(--tbw-filter-panel-fg, var(--tbw-color-fg, light-dark(#222222, #eeeeee)));border:1px solid var(--tbw-filter-panel-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-panel-radius, var(--tbw-border-radius, .25rem));box-shadow:0 4px 16px var(--tbw-filter-panel-shadow, var(--tbw-color-shadow, light-dark(rgba(0, 0, 0, .1), rgba(0, 0, 0, .3))));padding:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));z-index:10000;min-width:200px;max-width:280px;max-height:350px;display:flex;flex-direction:column;font-family:var(--tbw-font-family, system-ui, sans-serif);font-size:var(--tbw-font-size, .8125rem);transform-origin:top center}.tbw-filter-panel.tbw-filter-panel-above{transform-origin:bottom center}.tbw-filter-panel.tbw-filter-panel-animated{animation:tbw-filter-panel-enter var(--tbw-animation-duration, .15s) var(--tbw-animation-easing, ease-out)}.tbw-filter-panel.tbw-filter-panel-above.tbw-filter-panel-animated{animation:tbw-filter-panel-enter-above var(--tbw-animation-duration, .15s) var(--tbw-animation-easing, ease-out)}@keyframes tbw-filter-panel-enter{0%{opacity:0;transform:scaleY(.3) translateY(-10px)}to{opacity:1;transform:scaleY(1) translateY(0)}}@keyframes tbw-filter-panel-enter-above{0%{opacity:0;transform:scaleY(.3) translateY(10px)}to{opacity:1;transform:scaleY(1) translateY(0)}}@supports (anchor-name: --test){.tbw-filter-panel{position-anchor:--tbw-filter-anchor;top:anchor(bottom);left:anchor(left);margin-top:4px;position-try-fallbacks:flip-inline,flip-block,flip-block flip-inline}}.tbw-filter-search{margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));min-height:var(--tbw-filter-item-height, 28px)}.tbw-filter-search-input{height:var(--tbw-filter-item-height, 28px);width:100%;padding:var(--tbw-filter-search-padding, var(--tbw-spacing-sm, .375rem) var(--tbw-spacing-md, .5rem));background:var(--tbw-filter-input-bg, var(--tbw-color-bg, transparent));color:inherit;border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-input-radius, var(--tbw-border-radius, .25rem));font-size:inherit;box-sizing:border-box}.tbw-filter-search-input:focus{outline:none;border-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));box-shadow:0 0 0 2px rgba(from var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6)) r g b / 15%)}.tbw-filter-actions{display:flex;padding:var(--tbw-button-padding-sm, .25rem .125rem);margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border-bottom:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));min-height:var(--tbw-filter-item-height, 28px)}.tbw-filter-actions .tbw-filter-value-item{flex:1}.tbw-filter-values{flex:1;overflow-y:auto;margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));max-height:180px;position:relative}.tbw-filter-values-spacer{width:1px}.tbw-filter-values-content{position:absolute;top:0;left:0;right:0}.tbw-filter-value-item{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding-sm, .25rem .125rem);cursor:pointer;border-radius:3px;height:var(--tbw-filter-item-height, 28px)}.tbw-filter-value-item:hover{background:var(--tbw-filter-hover, var(--tbw-color-row-hover, light-dark(#f0f6ff, #1c1c1c)))}.tbw-filter-checkbox{margin:0;cursor:pointer;accent-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6))}.tbw-filter-no-match{color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem)) 0;text-align:center;font-style:italic}.tbw-filter-buttons{display:flex;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding-top:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border-top:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)))}.tbw-filter-apply-btn{flex:1;padding:var(--tbw-filter-btn-padding, var(--tbw-button-padding, .375rem .75rem));background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));color:var(--tbw-filter-accent-fg, var(--tbw-color-accent-fg, light-dark(#ffffff, #000000)));border:none;border-radius:var(--tbw-border-radius, .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);font-weight:var(--tbw-filter-btn-font-weight, 500);min-height:var(--tbw-filter-btn-min-height, auto)}.tbw-filter-apply-btn:hover{filter:brightness(.9)}.tbw-filter-clear-btn{flex:1;padding:var(--tbw-filter-btn-padding, var(--tbw-button-padding, .375rem .75rem));background:transparent;color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-border-radius, .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);font-weight:var(--tbw-filter-btn-font-weight, 500);min-height:var(--tbw-filter-btn-min-height, auto)}.tbw-filter-clear-btn:hover{background:var(--tbw-filter-hover, var(--tbw-color-row-hover, light-dark(#f0f6ff, #1c1c1c)))}.tbw-filter-range-inputs,.tbw-filter-date-range{display:flex;align-items:flex-end;gap:var(--tbw-spacing-sm, .375rem);margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-filter-range-group,.tbw-filter-date-group{display:flex;flex-direction:column;gap:var(--tbw-spacing-xs, .25rem);flex:1}.tbw-filter-range-label{font-size:var(--tbw-font-size-xs, .75rem);color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)))}.tbw-filter-range-input,.tbw-filter-date-input{width:100%;height:var(--tbw-filter-item-height, 28px);padding:var(--tbw-spacing-xs, .25rem) var(--tbw-spacing-sm, .375rem);background:var(--tbw-filter-input-bg, var(--tbw-color-bg, transparent));color:inherit;border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-input-radius, var(--tbw-border-radius, .25rem));font-size:inherit;box-sizing:border-box}.tbw-filter-range-input:focus,.tbw-filter-date-input:focus{outline:none;border-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));box-shadow:0 0 0 2px rgba(from var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6)) r g b / 15%)}.tbw-filter-range-separator{color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));padding-bottom:var(--tbw-spacing-xs, .25rem)}.tbw-filter-blank-option{display:flex;align-items:center;gap:var(--tbw-spacing-sm, .375rem);padding:var(--tbw-spacing-xs, .25rem) 0;margin-bottom:var(--tbw-spacing-xs, .25rem);font-size:var(--tbw-font-size-sm, .8125rem);cursor:pointer;-webkit-user-select:none;user-select:none}.tbw-filter-blank-checkbox{accent-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));margin:0;cursor:pointer}.tbw-filter-date-range.tbw-filter-disabled,.tbw-filter-range-inputs.tbw-filter-disabled,.tbw-filter-range-slider.tbw-filter-disabled{opacity:.4;pointer-events:none}.tbw-filter-range-slider{position:relative;height:24px;margin:var(--tbw-spacing-md, .5rem) 0 var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-filter-range-track{position:absolute;top:50%;left:0;right:0;height:4px;background:var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:2px;transform:translateY(-50%)}.tbw-filter-range-fill{position:absolute;top:50%;height:4px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border-radius:2px;transform:translateY(-50%)}.tbw-filter-range-thumb{position:absolute;top:0;width:100%;height:100%;background:none;pointer-events:none;-webkit-appearance:none;appearance:none}.tbw-filter-range-thumb::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:16px;height:16px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border:2px solid var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));border-radius:50%;cursor:pointer;pointer-events:all;box-shadow:0 1px 3px #0003}.tbw-filter-range-thumb::-moz-range-thumb{width:16px;height:16px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border:2px solid var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));border-radius:50%;cursor:pointer;pointer-events:all;box-shadow:0 1px 3px #0003}.tbw-filter-range-thumb::-webkit-slider-thumb:hover{transform:scale(1.1)}.tbw-filter-range-thumb::-moz-range-thumb:hover{transform:scale(1.1)}}",document.head.appendChild(e),this.globalStylesInjected=!0}toggleFilterPanel(e,t,i){if(this.openPanelField===e)return void this.closeFilterPanel();this.closeFilterPanel();const n=document.createElement("div");if(n.className="tbw-filter-panel",this.copyGridThemeContext(n),this.isAnimationEnabled&&n.classList.add("tbw-filter-panel-animated"),this.panelElement=n,this.openPanelField=e,this.config.valuesHandler)return n.innerHTML='<div class="tbw-filter-loading">Loading...</div>',document.body.appendChild(n),this.positionPanel(n,i),this.setupPanelCloseHandler(n,i),void this.config.valuesHandler(e,t).then(i=>{this.openPanelField===e&&this.panelElement&&(n.innerHTML="",this.renderPanelContent(e,t,n,i))});const r=Gt(this.sourceRows,e,t.filterValue);document.body.appendChild(n),this.positionPanel(n,i),this.renderPanelContent(e,t,n,r),this.setupPanelCloseHandler(n,i)}renderPanelContent(e,t,i,n){let r=this.excludedValues.get(e);r||(r=new Set,this.excludedValues.set(e,r));const o=this.searchText.get(e)??"",s={field:e,column:t,uniqueValues:n,excludedValues:r,searchText:o,currentFilter:this.filters.get(e),applySetFilter:(t,i)=>{this.applySetFilter(e,t,i),this.closeFilterPanel()},applyTextFilter:(t,i,n)=>{this.applyTextFilter(e,t,i,n),this.closeFilterPanel()},clearFilter:()=>{this.clearFieldFilter(e),this.closeFilterPanel()},closePanel:()=>this.closeFilterPanel()};let l=!1;if(this.config.filterPanelRenderer&&(this.config.filterPanelRenderer(i,s),l=i.children.length>0),!l&&t.type){const e=this.grid.effectiveConfig.typeDefaults?.[t.type];e?.filterPanelRenderer&&(e.filterPanelRenderer(i,s),l=i.children.length>0)}if(!l){const e=t.type;"number"===e?this.renderNumberFilterPanel(i,s,n):"date"===e?this.renderDateFilterPanel(i,s,n):this.renderDefaultFilterPanel(i,s,n,r)}}setupPanelCloseHandler(e,t){this.panelAbortController=new AbortController,setTimeout(()=>{document.addEventListener("click",i=>{e.contains(i.target)||i.target===t||this.closeFilterPanel()},{signal:this.panelAbortController?.signal})},0)}closeFilterPanel(){const e=this.panelElement;e&&(e.remove(),this.panelElement=null),this.panelAnchorElement&&(this.panelAnchorElement.style.anchorName="",this.panelAnchorElement=null),this.openPanelField=null,this.panelAbortController?.abort(),this.panelAbortController=null}static supportsAnchorPositioning=null;static checkAnchorPositioningSupport(){return null===Kt.supportsAnchorPositioning&&(Kt.supportsAnchorPositioning=CSS.supports("anchor-name","--test")),Kt.supportsAnchorPositioning}positionPanel(e,t){const i=t.closest(".cell")??t;if(i.style.anchorName="--tbw-filter-anchor",this.panelAnchorElement=i,Kt.checkAnchorPositioningSupport())return void requestAnimationFrame(()=>{const t=e.getBoundingClientRect(),n=i.getBoundingClientRect();t.top<n.top&&e.classList.add("tbw-filter-panel-above")});const n=i.getBoundingClientRect();e.style.position="fixed",e.style.top=`${n.bottom+4}px`,e.style.left=`${n.left}px`,requestAnimationFrame(()=>{const t=e.getBoundingClientRect();t.right>window.innerWidth-8&&(e.style.left=n.right-t.width+"px"),t.bottom>window.innerHeight-8&&(e.style.top=n.top-t.height-4+"px",e.classList.add("tbw-filter-panel-above"))})}renderDefaultFilterPanel(e,t,i,n){const{field:r,column:o}=t,s=this.getListItemHeight(),l=e=>{if(null==e)return"(Blank)";if(o.format&&!o.filterValue){const t=o.format(e,void 0);if(t)return t}return String(e)};i=i.slice().sort((e,t)=>l(e).localeCompare(l(t)));const a=document.createElement("div");a.className="tbw-filter-search";const d=document.createElement("input");d.type="text",d.placeholder="Search...",d.className="tbw-filter-search-input",d.value=this.searchText.get(r)??"",a.appendChild(d),e.appendChild(a);const c=document.createElement("div");c.className="tbw-filter-actions";const h=document.createElement("label");h.className="tbw-filter-value-item",h.style.padding="0",h.style.margin="0";const u=document.createElement("input");u.type="checkbox",u.className="tbw-filter-checkbox";const g=document.createElement("span");g.textContent="Select All",h.appendChild(u),h.appendChild(g),c.appendChild(h);const p=()=>{const e=[...b.values()],t=e.every(e=>e),i=e.every(e=>!e);u.checked=t,u.indeterminate=!t&&!i};u.addEventListener("change",()=>{const e=u.checked;for(const t of b.keys())b.set(t,e);p(),C()}),e.appendChild(c);const f=document.createElement("div");f.className="tbw-filter-values";const w=document.createElement("div");w.className="tbw-filter-values-spacer",f.appendChild(w);const m=document.createElement("div");m.className="tbw-filter-values-content",f.appendChild(m);const b=new Map;i.forEach(e=>{const t=null==e?"__null__":String(e);b.set(t,!n.has(e))}),p();let v=[];const y=(e,t)=>{const i=l(e),n=null==e?"__null__":String(e),r=document.createElement("label");r.className="tbw-filter-value-item",r.style.position="absolute",r.style.top=`calc(var(--tbw-filter-item-height, 28px) * ${t})`,r.style.left="0",r.style.right="0",r.style.boxSizing="border-box";const o=document.createElement("input");o.type="checkbox",o.className="tbw-filter-checkbox",o.checked=b.get(n)??!0,o.dataset.value=n,o.addEventListener("change",()=>{b.set(n,o.checked),p()});const s=document.createElement("span");return s.textContent=i,r.appendChild(o),r.appendChild(s),r},C=()=>{const e=v.length,t=f.clientHeight,i=f.scrollTop;if(w.style.height=e*s+"px",n=e,r=Kt.LIST_BYPASS_THRESHOLD/3,n<=r)return m.innerHTML="",m.style.transform="translateY(0px)",void v.forEach((e,t)=>{m.appendChild(y(e,t))});var n,r;const o=function(e){const{totalRows:t,viewportHeight:i,scrollTop:n,rowHeight:r,overscan:o}=e,s=Math.ceil(i/r);let l=Math.floor(n/r)-o;l<0&&(l=0);let a=l+s+2*o;return a>t&&(a=t),a===t&&l>0&&(l=Math.max(0,a-s-2*o)),{start:l,end:a,offsetY:l*r,totalHeight:t*r}}({totalRows:e,viewportHeight:t,scrollTop:i,rowHeight:s,overscan:Kt.LIST_OVERSCAN});m.style.transform=`translateY(${o.offsetY}px)`,m.innerHTML="";for(let s=o.start;s<o.end;s++)m.appendChild(y(v[s],s-o.start))},x=e=>{const t=this.config.caseSensitive??!1,n=t?e:e.toLowerCase();if(v=i.filter(i=>{const r=l(i),o=t?r:r.toLowerCase();return!e||o.includes(n)}),0===v.length){w.style.height="0px",m.innerHTML="";const e=document.createElement("div");return e.className="tbw-filter-no-match",e.textContent="No matching values",void m.appendChild(e)}C()};let E;f.addEventListener("scroll",()=>{v.length>0&&C()},{passive:!0}),x(d.value),e.appendChild(f),d.addEventListener("input",()=>{clearTimeout(E),E=setTimeout(()=>{this.searchText.set(r,d.value),x(d.value)},this.config.debounceMs??150)});const R=document.createElement("div");R.className="tbw-filter-buttons";const S=document.createElement("button");S.className="tbw-filter-apply-btn",S.textContent="Apply",S.addEventListener("click",()=>{const e=[];for(const[t,n]of b)if(!n)if("__null__"===t)e.push(null);else{const n=i.find(e=>String(e)===t);e.push(void 0!==n?n:t)}t.applySetFilter(e)}),R.appendChild(S);const _=document.createElement("button");_.className="tbw-filter-clear-btn",_.textContent="Clear Filter",_.addEventListener("click",()=>{t.clearFilter()}),R.appendChild(_),e.appendChild(R)}renderNumberFilterPanel(e,t,i){const{field:n,column:r}=t,o=r.filterParams,s=r.editorParams,l=(e,t)=>{if("number"==typeof e)return e;if("string"==typeof e){const i=parseFloat(e);return isNaN(i)?t:i}return t},a=i.filter(e=>"number"==typeof e&&!isNaN(e)),d=a.length>0?Math.min(...a):0,c=a.length>0?Math.max(...a):100,h=l(o?.min??s?.min,d),u=l(o?.max??s?.max,c),g=o?.step??s?.step??1,p=this.filters.get(n);let f=h,w=u;const m="blank"===p?.operator;"between"===p?.operator?(f=l(p.value,h),w=l(p.valueTo,u)):"greaterThanOrEqual"===p?.operator?f=l(p.value,h):"lessThanOrEqual"===p?.operator&&(w=l(p.value,u));const b=document.createElement("div");b.className="tbw-filter-range-inputs";const v=document.createElement("div");v.className="tbw-filter-range-group";const y=document.createElement("label");y.textContent="Min",y.className="tbw-filter-range-label";const C=document.createElement("input");C.type="number",C.className="tbw-filter-range-input",C.min=String(h),C.max=String(u),C.step=String(g),C.value=String(f),v.appendChild(y),v.appendChild(C),b.appendChild(v);const x=document.createElement("span");x.className="tbw-filter-range-separator",x.textContent="–",b.appendChild(x);const E=document.createElement("div");E.className="tbw-filter-range-group";const R=document.createElement("label");R.textContent="Max",R.className="tbw-filter-range-label";const S=document.createElement("input");S.type="number",S.className="tbw-filter-range-input",S.min=String(h),S.max=String(u),S.step=String(g),S.value=String(w),E.appendChild(R),E.appendChild(S),b.appendChild(E),e.appendChild(b);const _=document.createElement("div");_.className="tbw-filter-range-slider";const A=document.createElement("div");A.className="tbw-filter-range-track";const k=document.createElement("div");k.className="tbw-filter-range-fill";const T=document.createElement("input");T.type="range",T.className="tbw-filter-range-thumb tbw-filter-range-thumb-min",T.min=String(h),T.max=String(u),T.step=String(g),T.value=String(f);const L=document.createElement("input");L.type="range",L.className="tbw-filter-range-thumb tbw-filter-range-thumb-max",L.min=String(h),L.max=String(u),L.step=String(g),L.value=String(w),_.appendChild(A),_.appendChild(k),_.appendChild(T),_.appendChild(L),e.appendChild(_);const M=document.createElement("label");M.className="tbw-filter-blank-option";const P=document.createElement("input");P.type="checkbox",P.className="tbw-filter-blank-checkbox",P.checked=m;const H=document.createTextNode("Blank");M.appendChild(P),M.appendChild(H);const I=e=>{C.disabled=e,S.disabled=e,T.disabled=e,L.disabled=e,b.classList.toggle("tbw-filter-disabled",e),_.classList.toggle("tbw-filter-disabled",e)};I(m),P.addEventListener("change",()=>{I(P.checked)}),e.appendChild(M);const D=()=>{const e=parseFloat(T.value),t=parseFloat(L.value),i=u-h,n=(e-h)/i*100,r=(t-h)/i*100;k.style.left=`${n}%`,k.style.width=r-n+"%"};T.addEventListener("input",()=>{const e=Math.min(parseFloat(T.value),parseFloat(L.value));T.value=String(e),C.value=String(e),D()}),L.addEventListener("input",()=>{const e=Math.max(parseFloat(L.value),parseFloat(T.value));L.value=String(e),S.value=String(e),D()}),C.addEventListener("input",()=>{let e=parseFloat(C.value)||h;e=Math.max(h,Math.min(e,parseFloat(S.value))),T.value=String(e),D()}),S.addEventListener("input",()=>{let e=parseFloat(S.value)||u;e=Math.min(u,Math.max(e,parseFloat(C.value))),L.value=String(e),D()}),D();const z=document.createElement("div");z.className="tbw-filter-buttons";const O=document.createElement("button");O.className="tbw-filter-apply-btn",O.textContent="Apply",O.addEventListener("click",()=>{if(P.checked)return void t.applyTextFilter("blank","");const e=parseFloat(C.value),i=parseFloat(S.value);t.applyTextFilter("between",e,i)}),z.appendChild(O);const q=document.createElement("button");q.className="tbw-filter-clear-btn",q.textContent="Clear Filter",q.addEventListener("click",()=>{t.clearFilter()}),z.appendChild(q),e.appendChild(z)}renderDateFilterPanel(e,t,i){const{field:n,column:r}=t,o=r.filterParams,s=r.editorParams,l=i.filter(e=>e instanceof Date||"string"==typeof e&&!isNaN(Date.parse(e))).map(e=>e instanceof Date?e:new Date(e)).filter(e=>!isNaN(e.getTime())),a=l.length>0?new Date(Math.min(...l.map(e=>e.getTime()))):null,d=l.length>0?new Date(Math.max(...l.map(e=>e.getTime()))):null,c=e=>e?e.toISOString().split("T")[0]:"",h=e=>e?"string"==typeof e?e:"number"==typeof e?c(new Date(e)):"":"",u=h(o?.min)||h(s?.min)||c(a),g=h(o?.max)||h(s?.max)||c(d),p=this.filters.get(n);let f="",w="";const m="blank"===p?.operator;"between"===p?.operator?(f=h(p.value)||"",w=h(p.valueTo)||""):"greaterThanOrEqual"===p?.operator?f=h(p.value)||"":"lessThanOrEqual"===p?.operator&&(w=h(p.value)||"");const b=document.createElement("div");b.className="tbw-filter-date-range";const v=document.createElement("div");v.className="tbw-filter-date-group";const y=document.createElement("label");y.textContent="From",y.className="tbw-filter-range-label";const C=document.createElement("input");C.type="date",C.className="tbw-filter-date-input",u&&(C.min=u),g&&(C.max=g),C.value=f,v.appendChild(y),v.appendChild(C),b.appendChild(v);const x=document.createElement("span");x.className="tbw-filter-range-separator",x.textContent="–",b.appendChild(x);const E=document.createElement("div");E.className="tbw-filter-date-group";const R=document.createElement("label");R.textContent="To",R.className="tbw-filter-range-label";const S=document.createElement("input");S.type="date",S.className="tbw-filter-date-input",u&&(S.min=u),g&&(S.max=g),S.value=w,E.appendChild(R),E.appendChild(S),b.appendChild(E),e.appendChild(b);const _=document.createElement("label");_.className="tbw-filter-blank-option";const A=document.createElement("input");A.type="checkbox",A.className="tbw-filter-blank-checkbox",A.checked=m;const k=document.createTextNode("Show only blank");_.appendChild(A),_.appendChild(k);const T=e=>{C.disabled=e,S.disabled=e,b.classList.toggle("tbw-filter-disabled",e)};T(m),A.addEventListener("change",()=>{T(A.checked)}),e.appendChild(_);const L=document.createElement("div");L.className="tbw-filter-buttons";const M=document.createElement("button");M.className="tbw-filter-apply-btn",M.textContent="Apply",M.addEventListener("click",()=>{if(A.checked)return void t.applyTextFilter("blank","");const e=C.value,i=S.value;e&&i?t.applyTextFilter("between",e,i):e?t.applyTextFilter("greaterThanOrEqual",e):i?t.applyTextFilter("lessThanOrEqual",i):t.clearFilter()}),L.appendChild(M);const P=document.createElement("button");P.className="tbw-filter-clear-btn",P.textContent="Clear Filter",P.addEventListener("click",()=>{t.clearFilter()}),L.appendChild(P),e.appendChild(L)}applySetFilter(e,t,i){this.excludedValues.set(e,new Set(t)),0===t.length?this.filters.delete(e):this.filters.set(e,{field:e,type:"set",operator:"notIn",value:t,...void 0!==i&&{valueTo:i}}),this.applyFiltersInternal()}applyTextFilter(e,t,i,n){this.filters.set(e,{field:e,type:"text",operator:t,value:i,valueTo:n}),this.applyFiltersInternal()}applyFiltersInternal(){this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null;const e=[...this.filters.values()];if(this.config.filterHandler){const t=this.grid;t.setAttribute("aria-busy","true");const i=this.config.filterHandler(e,this.sourceRows),n=i=>{t.removeAttribute("aria-busy"),this.cachedResult=i,this.grid.rows=i,this.emit("filter-change",{filters:e,filteredRowCount:i.length,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:e}),this.requestRender()};return void(i&&"function"==typeof i.then?i.then(n):n(i))}this.emit("filter-change",{filters:e,filteredRowCount:0,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:e}),this.requestRender()}getColumnState(e){const t=this.filters.get(e);if(t)return{filter:{type:t.type,operator:t.operator,value:t.value,valueTo:t.valueTo}}}applyColumnState(e,t){if(!t.filter)return void this.filters.delete(e);const i={field:e,type:t.filter.type,operator:t.filter.operator,value:t.filter.value,valueTo:t.filter.valueTo};this.filters.set(e,i),this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null}}function Ut(e){if(!e.length)return[];const t=new Map,i=[],n=(e,t)=>{if(!t.length)return;const n=i[i.length-1];n&&n.implicit&&n.firstIndex+n.columns.length===e?n.columns.push(...t):i.push({id:"__implicit__"+e,label:void 0,columns:t,firstIndex:e,implicit:!0})};let r=[],o=0;return e.forEach((e,s)=>{const l=e.group;if(!l)return 0===r.length&&(o=s),void r.push(e);r.length&&(n(o,r.slice()),r=[]);const a="string"==typeof l?l:l.id;let d=t.get(a);d||(d={id:a,label:"string"==typeof l?void 0:l.label,columns:[],firstIndex:s},t.set(a,d),i.push(d)),d.columns.push(e)}),r.length&&n(o,r),1===i.length&&i[0].implicit&&i[0].columns.length===e.length?[]:i}const jt={sum:(e,t)=>e.reduce((e,i)=>e+(Number(i[t])||0),0),avg:(e,t)=>{const i=e.reduce((e,i)=>e+(Number(i[t])||0),0);return e.length?i/e.length:0},count:e=>e.length,min:(e,t)=>e.length?Math.min(...e.map(e=>Number(e[t])||1/0)):0,max:(e,t)=>e.length?Math.max(...e.map(e=>Number(e[t])||-1/0)):0,first:(e,t)=>e[0]?.[t],last:(e,t)=>e[e.length-1]?.[t]},Yt=new Map,Xt={register(e,t){Yt.set(e,t)},unregister(e){Yt.delete(e)},get(e){if(void 0!==e)return"function"==typeof e?e:Yt.get(e)??jt[e]},run(e,t,i,n){const r=this.get(e);return r?r(t,i,n):void 0},has:e=>Yt.has(e)||e in jt,list:()=>[...Object.keys(jt),...Yt.keys()]},Zt={sum:e=>e.reduce((e,t)=>e+t,0),avg:e=>e.length?e.reduce((e,t)=>e+t,0)/e.length:0,count:e=>e.length,min:e=>e.length?Math.min(...e):0,max:e=>e.length?Math.max(...e):0,first:e=>e[0]??0,last:e=>e[e.length-1]??0};Xt.register.bind(Xt),Xt.unregister.bind(Xt);const Qt=Xt.get.bind(Xt),Jt=Xt.run.bind(Xt);function ei({rows:e,config:t,expanded:i,initialExpanded:n}){const r=t.groupOn;if("function"!=typeof r)return[];const o={key:"__root__",value:null,depth:-1,rows:[],children:new Map};if(e.forEach(e=>{let t=r(e);null==t||!1===t?t=["__ungrouped__"]:Array.isArray(t)||(t=[t]);let i=o;t.forEach((e,t)=>{const n=null==e?"∅":String(e),r="__root__"===i.key?n:i.key+"||"+n;let o=i.children.get(n);o||(o={key:r,value:e,depth:t,rows:[],children:new Map,parent:i},i.children.set(n,o)),i=o}),i.rows.push(e)}),1===o.children.size&&o.children.has("__ungrouped__")){if(o.children.get("__ungrouped__").rows.length===e.length)return[]}const s=new Set([...i,...n??[]]),l=[],a=t=>{if(t===o)return void t.children.forEach(e=>a(e));const i=s.has(t.key);l.push({kind:"group",key:t.key,value:t.value,depth:t.depth,rows:t.rows,expanded:i}),i&&(t.children.size?t.children.forEach(e=>a(e)):t.rows.forEach(t=>l.push({kind:"data",row:t,rowIndex:e.indexOf(t)})))};return a(o),l}Xt.list.bind(Xt);function ti(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}function ii(e,t,i,n){const r=document.createElement("div");r.className="master-detail-row",r.setAttribute("data-detail-for",String(t)),r.setAttribute("role","row");const o=document.createElement("div");o.className="master-detail-cell",o.setAttribute("role","cell"),o.style.gridColumn=`1 / ${n+1}`;const s=i(e,t);return"string"==typeof s?o.innerHTML=s:s instanceof HTMLElement&&o.appendChild(s),r.appendChild(o),r}class ni extends rt{name="masterDetail";styles="@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-right:none!important;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1 / 3}tbw-grid .master-detail-expander{display:flex;align-items:center;justify-content:center;width:100%;height:100%}tbw-grid .master-detail-toggle{cursor:pointer;opacity:.7;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center}tbw-grid .master-detail-toggle:hover{opacity:1}tbw-grid .master-detail-row{grid-column:1 / -1;display:grid;background:var(--tbw-master-detail-bg, var(--tbw-color-row-alt));border-bottom:1px solid var(--tbw-master-detail-border, var(--tbw-color-border));overflow:hidden}tbw-grid .master-detail-cell{padding:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));overflow:auto}tbw-grid .master-detail-row.tbw-expanding{animation:tbw-detail-expand var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .master-detail-row.tbw-collapsing{animation:tbw-detail-collapse var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-detail-expand{0%{opacity:0;max-height:0;padding-top:0;padding-bottom:0}to{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem);padding-top:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));padding-bottom:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem))}}@keyframes tbw-detail-collapse{0%{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem)}to{opacity:0;max-height:0}}}";get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,animation:"slide"}}attach(e){super.attach(e),this.parseLightDomDetail()}parseLightDomDetail(){const e=this.grid;if(!e||"function"!=typeof e.querySelector)return;const t=e.querySelector("tbw-grid-detail");if(!t)return;const i=e;if(i.__frameworkAdapter?.parseDetailElement){const e=i.__frameworkAdapter.parseDetailElement(t);if(e)return void(this.config={...this.config,detailRenderer:e})}const n=t.getAttribute("animation"),r=t.getAttribute("show-expand-column"),o=t.getAttribute("expand-on-row-click"),s=t.getAttribute("collapse-on-click-outside"),l=t.getAttribute("height"),a={};null!==n&&(a.animation="false"!==n&&n),null!==r&&(a.showExpandColumn="false"!==r),null!==o&&(a.expandOnRowClick="true"===o),null!==s&&(a.collapseOnClickOutside="true"===s),null!==l&&(a.detailHeight="auto"===l?"auto":parseInt(l,10));const d=t.innerHTML.trim();d&&!this.config.detailRenderer&&(a.detailRenderer=(e,t)=>y(C(d,{value:e,row:e}))),Object.keys(a).length>0&&(this.config={...this.config,...a})}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}animateExpand(e,t,i){if(!this.isAnimationEnabled||!1===this.animationStyle)return!1;e.classList.add("tbw-expanding");let n=!1;const r=()=>{n||(n=!0,e.classList.remove("tbw-expanding"),void 0!==t&&void 0!==i&&this.#ht(e,t,i))};return e.addEventListener("animationend",r,{once:!0}),setTimeout(r,this.animationDuration+50),!0}animateCollapse(e,t){if(!this.isAnimationEnabled||!1===this.animationStyle)return void t();e.classList.add("tbw-collapsing");const i=()=>{e.classList.remove("tbw-collapsing"),t()};e.addEventListener("animationend",i,{once:!0}),setTimeout(i,this.animationDuration+50)}#ht(e,t,i){if(!e.isConnected)return;const n=e.offsetHeight;if(n>0){const e=this.measuredDetailHeights.get(t);this.measuredDetailHeights.set(t,n),e!==n&&this.grid.invalidateRowHeight(i)}}expandedRows=new Set;detailElements=new Map;measuredDetailHeights=new Map;rowsToAnimate=new Set;static DEFAULT_DETAIL_HEIGHT=150;getDetailHeight(e){const t=this.detailElements.get(e);if(t){if(!(t.classList.contains("tbw-expanding")||t.classList.contains("tbw-collapsing"))){const i=t.offsetHeight;if(i>0)return this.measuredDetailHeights.set(e,i),i}}const i=this.measuredDetailHeights.get(e);return i&&i>0?i:"number"==typeof this.config?.detailHeight?this.config.detailHeight:ni.DEFAULT_DETAIL_HEIGHT}toggleAndEmit(e,t){this.expandedRows=ti(this.expandedRows,e);const i=this.expandedRows.has(e);i&&this.rowsToAnimate.add(e),this.emit("detail-expand",{rowIndex:t,row:e,expanded:i}),this.requestRender()}detach(){this.expandedRows.clear(),this.detailElements.clear(),this.measuredDetailHeights.clear(),this.rowsToAnimate.clear()}processColumns(e){if(!(!0===this.config.showExpandColumn||!1!==this.config.showExpandColumn&&!!this.config.detailRenderer))return[...e];const t=[...e],i=function(e){return e.find(Bt)}(t);if(i)return t;const n=(r=this.name,{field:$t,header:"",width:32,resizable:!1,sortable:!1,filterable:!1,meta:{lockPosition:!0,suppressMovable:!0,expanderColumn:!0,expanderPlugin:r,utility:!0}});var r;return n.viewRenderer=e=>{const{row:t}=e,i=this.expandedRows.has(t),n=document.createElement("span");n.className="master-detail-expander expander-cell";const r=document.createElement("span");return r.className="master-detail-toggle"+(i?" expanded":""),this.setIcon(r,this.resolveIcon(i?"collapse":"expand")),r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.setAttribute("aria-expanded",String(i)),r.setAttribute("aria-label",i?"Collapse details":"Expand details"),n.appendChild(r),n},[n,...t]}onRowClick(e){if(this.config.expandOnRowClick&&this.config.detailRenderer)return this.toggleAndEmit(e.row,e.rowIndex),!1}onCellClick(e){const t=e.originalEvent?.target;if(t?.classList.contains("master-detail-toggle"))return this.toggleAndEmit(e.row,e.rowIndex),!0;this.expandedRows.size>0&&queueMicrotask(()=>this.#ut())}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusCol,i=this.grid._focusRow,n=this.visibleColumns[t];if(!n||!Bt(n))return;const r=this.rows[i];return r?(e.preventDefault(),this.toggleAndEmit(r,i),this.requestRenderWithFocus(),!0):void 0}afterRender(){this.#ut()}onScrollRender(){this.config.detailRenderer&&0!==this.expandedRows.size&&this.#ut()}#ut(){if(!this.config.detailRenderer)return;const e=this.gridElement?.querySelector(".rows");if(!e)return;const t=this.grid,i=t._rowPool,n=t._virtualization?.start??0,r=t._virtualization?.end??0,o=this.columns.length,s=n,l=r,a=new Map;if(i){const t=Math.min(i.length,l-s);for(let n=0;n<t;n++){const t=i[n];t.parentNode===e&&a.set(s+n,t)}}else{const t=e.querySelectorAll(".data-grid-row");for(const e of t){const t=e.querySelector(".cell[data-row]"),i=t?parseInt(t.getAttribute("data-row")??"-1",10):-1;i>=0&&a.set(i,e)}}for(const[d,c]of this.detailElements){const e=this.rows.indexOf(d),t=this.expandedRows.has(d),i=e>=0&&a.has(e);if(!t||!i){const e=this.grid.__frameworkAdapter;if(e?.unmount){const t=c.querySelector(".master-detail-cell"),i=t?.firstElementChild;i&&e.unmount(i)}c.parentNode&&c.remove(),this.detailElements.delete(d)}}for(const[d,c]of a){const e=this.rows[d];if(!e||!this.expandedRows.has(e))continue;const t=this.detailElements.get(e);if(t){t.previousElementSibling!==c&&c.after(t);continue}const i=ii(e,d,this.config.detailRenderer,o);"number"==typeof this.config.detailHeight&&(i.style.height=`${this.config.detailHeight}px`),c.after(i),this.detailElements.set(e,i);const n=this.rowsToAnimate.has(e);n&&this.rowsToAnimate.delete(e);n&&this.animateExpand(i,e,d)||requestAnimationFrame(()=>{this.#ht(i,e,d)})}}getExtraHeight(){let e=0;for(const t of this.expandedRows)e+=this.getDetailHeight(t);return e}getExtraHeightBefore(e){let t=0;for(const i of this.expandedRows){const n=this.rows.indexOf(i);n>=0&&n<e&&(t+=this.getDetailHeight(i))}return t}getRowHeight(e,t){if(!this.expandedRows.has(e))return;return(this.grid.defaultRowHeight??28)+this.getDetailHeight(e)}adjustVirtualStart(e,t,i){if(0===this.expandedRows.size)return e;const n=this.grid?._virtualization?.positionCache;let r=e;if(n&&n.length>0)for(const o of this.expandedRows){const i=this.rows.indexOf(o);if(i<0||i>=e)continue;n[i].offset+n[i].height>t&&i<r&&(r=i)}else{const n=[];for(const e of this.expandedRows){const t=this.rows.indexOf(e);t>=0&&n.push({index:t,row:e})}n.sort((e,t)=>e.index-t.index);let o=0;for(const{index:s,row:l}of n){const n=s*i+o,a=this.getDetailHeight(l);o+=a,s>=e||n+i+a>t&&s<r&&(r=s)}}return r}expand(e){const t=this.rows[e];t&&(this.rowsToAnimate.add(t),this.expandedRows=function(e,t){const i=new Set(e);return i.add(t),i}(this.expandedRows,t),this.requestRender())}collapse(e){const t=this.rows[e];t&&(this.expandedRows=function(e,t){const i=new Set(e);return i.delete(t),i}(this.expandedRows,t),this.requestRender())}toggle(e){const t=this.rows[e];t&&(this.expandedRows=ti(this.expandedRows,t),this.expandedRows.has(t)&&this.rowsToAnimate.add(t),this.requestRender())}isExpanded(e){const t=this.rows[e];return!!t&&function(e,t){return e.has(t)}(this.expandedRows,t)}expandAll(){for(const e of this.rows)this.rowsToAnimate.add(e),this.expandedRows.add(e);this.requestRender()}collapseAll(){this.expandedRows.clear(),this.requestRender()}getExpandedRows(){const e=[];for(const t of this.expandedRows){const i=this.rows.indexOf(t);i>=0&&e.push(i)}return e}getDetailElement(e){const t=this.rows[e];return t?this.detailElements.get(t):void 0}refreshDetailRenderer(){const e=this.config.detailRenderer;if(this.config={...this.config,detailRenderer:void 0},this.parseLightDomDetail(),!this.config.detailRenderer&&e&&(this.config={...this.config,detailRenderer:e}),this.config.detailRenderer){const e=this.grid;"function"==typeof e.refreshColumns?e.refreshColumns():this.requestRender()}}}function ri(e,t){return null==e&&null==t?0:null==e?1:null==t?-1:"number"==typeof e&&"number"==typeof t?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():"boolean"==typeof e&&"boolean"==typeof t?e===t?0:e?-1:1:String(e).localeCompare(String(t))}function oi(e,t){const i=e.findIndex(e=>e.field===t);return i>=0?i+1:void 0}function si(e,t){return e.find(e=>e.field===t)?.direction}function li(e){return e.pinned??e.sticky??e.meta?.pinned??e.meta?.sticky}function ai(e,t){return function(e,t){return"left"===e||"right"===e?e:"rtl"===t?"start"===e?"right":"left":"start"===e?"left":"right"}(e,t)}function di(e,t){const i=li(e);return!!i&&"left"===ai(i,t)}function ci(e,t){const i=li(e);return!!i&&"right"===ai(i,t)}function hi(e){return e.some(e=>null!=li(e))}function ui(e,t){const i=Array.from(e.querySelectorAll(".header-row .cell"));if(!i.length)return;const n=M(e);let r=0;for(const s of t)if(di(s,n)){const t=i.find(e=>e.getAttribute("data-field")===s.field);t&&(t.classList.add("sticky-left"),t.style.position="sticky",t.style.left=r+"px",e.querySelectorAll(`.data-grid-row .cell[data-field="${s.field}"]`).forEach(e=>{e.classList.add("sticky-left"),e.style.position="sticky",e.style.left=r+"px"}),r+=t.offsetWidth)}let o=0;for(const s of[...t].reverse())if(ci(s,n)){const t=i.find(e=>e.getAttribute("data-field")===s.field);t&&(t.classList.add("sticky-right"),t.style.position="sticky",t.style.right=o+"px",e.querySelectorAll(`.data-grid-row .cell[data-field="${s.field}"]`).forEach(e=>{e.classList.add("sticky-right"),e.style.position="sticky",e.style.right=o+"px"}),o+=t.offsetWidth)}}function gi(e){e.querySelectorAll(".sticky-left, .sticky-right").forEach(e=>{e.classList.remove("sticky-left","sticky-right"),e.style.position="",e.style.left="",e.style.right=""})}const pi="canMoveColumn";function fi(e,t){const i=document.createElement("div");i.className="tbw-pinned-rows",i.setAttribute("role","presentation"),i.setAttribute("aria-live","polite");const n=document.createElement("div");n.className="tbw-pinned-rows-left";const r=document.createElement("div");r.className="tbw-pinned-rows-center";const o=document.createElement("div");if(o.className="tbw-pinned-rows-right",!1!==e.showRowCount){const e=document.createElement("span");e.className="tbw-status-panel tbw-status-panel-row-count",e.textContent=`Total: ${t.totalRows} rows`,n.appendChild(e)}if(e.showFilteredCount&&t.filteredRows!==t.totalRows){const e=document.createElement("span");e.className="tbw-status-panel tbw-status-panel-filtered-count",e.textContent=`Filtered: ${t.filteredRows}`,n.appendChild(e)}if(e.showSelectedCount&&t.selectedRows>0){const e=document.createElement("span");e.className="tbw-status-panel tbw-status-panel-selected-count",e.textContent=`Selected: ${t.selectedRows}`,o.appendChild(e)}if(e.customPanels)for(const s of e.customPanels){const e=Ci(s,t);switch(s.position){case"left":n.appendChild(e);break;case"center":r.appendChild(e);break;case"right":o.appendChild(e)}}return i.appendChild(n),i.appendChild(r),i.appendChild(o),i}function wi(e){const t=document.createElement("div");return t.className=`tbw-aggregation-rows tbw-aggregation-rows-${e}`,t.setAttribute("role","presentation"),t}function mi(e,t,i,n,r=!1){e.innerHTML="";for(const o of t){const t=document.createElement("div");t.className="tbw-aggregation-row",t.setAttribute("role","presentation"),o.id&&t.setAttribute("data-aggregation-id",o.id);o.fullWidth??r?bi(t,o,i,n):vi(t,o,i,n),e.appendChild(t)}}function bi(e,t,i,n){const r=document.createElement("div");r.className="tbw-aggregation-cell tbw-aggregation-cell-full",r.style.gridColumn="1 / -1";const o="function"==typeof t.label?t.label(n,i):t.label;if(o){const e=document.createElement("span");e.className="tbw-aggregation-label",e.textContent=o,r.appendChild(e)}const s=function(e,t,i){const n=e.aggregators&&Object.keys(e.aggregators).length>0,r=e.cells&&Object.keys(e.cells).length>0;if(!n&&!r)return null;const o=document.createElement("span");o.className="tbw-aggregation-aggregates";for(const s of t){const{value:t,formatter:n}=yi(e,s,i);if(null!=t){const e=document.createElement("span");e.className="tbw-aggregation-aggregate",e.setAttribute("data-field",s.field);const i=s.header??s.field,r=n?n(t,s.field,s):String(t);e.textContent=`${i}: ${r}`,o.appendChild(e)}}return o.children.length>0?o:null}(t,i,n);s&&r.appendChild(s),e.appendChild(r)}function vi(e,t,i,n){for(const r of i){const i=document.createElement("div");i.className="tbw-aggregation-cell",i.setAttribute("data-field",r.field);const{value:o,formatter:s}=yi(t,r,n);i.textContent=null!=o?s?s(o,r.field,r):String(o):"",e.appendChild(i)}}function yi(e,t,i){let n,r;const o=e.aggregators?.[t.field];if(o)if("object"==typeof(s=o)&&null!==s&&"aggFunc"in s){const e=Qt(o.aggFunc);e&&(n=e(i,t.field,t)),r=o.formatter}else{const e=Qt(o);e&&(n=e(i,t.field,t))}else if(e.cells&&Object.prototype.hasOwnProperty.call(e.cells,t.field)){const r=e.cells[t.field];n="function"==typeof r?r(i,t.field,t):r}var s;return{value:n,formatter:r}}function Ci(e,t){const i=document.createElement("div");i.className="tbw-status-panel tbw-status-panel-custom",i.id=`status-panel-${e.id}`;const n=e.render(t);return"string"==typeof n?i.innerHTML=n:i.appendChild(n),i}function xi(e,t,i,n,r){return{totalRows:e.length,filteredRows:r?.cachedResult?.length??e.length,selectedRows:n?.selected?.size??0,columns:t,rows:e,grid:i}}const Ei=function(e){return Zt[e]??Zt.sum};function Ri(e,t){return[...e,t].join("|")}function Si(e,t){const i=t.rowGroupFields??[],n=t.columnGroupFields??[],r=t.valueFields??[],o=function(e,t){if(0===t.length)return["value"];const i=new Set;for(const n of e){const e=t.map(e=>String(n[e]??"")).join("|");i.add(e)}return[...i].sort()}(e,n),s=_i(e,i,n,o,r,0,""),l=function(e,t,i){const n={};function r(e){for(const o of e)if(o.isGroup&&o.children?.length)o.children&&r(o.children);else for(const e of t)for(const t of i){const i=Ri([e],t.field);n[i]=(n[i]??0)+(o.values[i]??0)}}return r(e),n}(s,o,r);return{rows:s,columnKeys:o,totals:l,grandTotal:Object.values(l).reduce((e,t)=>e+t,0)}}function _i(e,t,i,n,r,o,s){const l=[];if(0===t.length){const t=Ai(e,i,n,r),a=ki(t);return l.push({rowKey:s||"all",rowLabel:s||"All",depth:o,values:t,total:a,isGroup:!1,rowCount:e.length}),l}const a=t[0],d=t.slice(1),c=d.length>0,h=function(e,t){const i=new Map;for(const n of e){const e=String(n[t]??""),r=i.get(e);r?r.push(n):i.set(e,[n])}return i}(e,a);for(const[u,g]of h){const e=s?`${s}|${u}`:u,t=Ai(g,i,n,r),a=ki(t);let h;c&&(h=_i(g,d,i,n,r,o+1,e)),l.push({rowKey:e,rowLabel:u||"(blank)",depth:o,values:t,total:a,isGroup:c,children:h,rowCount:g.length})}return l}function Ai(e,t,i,n){const r={};for(const o of i)for(const i of n){const n=(t.length>0?e.filter(e=>t.map(t=>String(e[t]??"")).join("|")===o):e).map(e=>Number(e[i.field])||0),s=Ei(i.aggFunc),l=n.length>0?s(n):null;r[Ri([o],i.field)]=l}return r}function ki(e){let t=0;for(const i of Object.values(e))t+=i??0;return t}const Ti=["sum","avg","count","min","max","first","last"];function Li(e,t,i,n){const r=new AbortController,o={config:t,callbacks:n,signal:r.signal},s=document.createElement("div");return s.className="tbw-pivot-panel",s.appendChild(Mi("Options",()=>function(e,t){const{config:i,callbacks:n,signal:r}=t,o=document.createElement("div");return o.className="tbw-pivot-options",o.appendChild(Di("Enable Pivot View",e,e=>{n.onTogglePivot(e)},r)),o.appendChild(Di("Show Row Totals",i.showTotals??!0,e=>{n.onOptionChange("showTotals",e)},r)),o.appendChild(Di("Show Grand Total",i.showGrandTotal??!0,e=>{n.onOptionChange("showGrandTotal",e)},r)),o}(i,o))),s.appendChild(Mi("Row Groups",()=>Pi("rowGroups",o))),s.appendChild(Mi("Column Groups",()=>Pi("columnGroups",o))),s.appendChild(Mi("Values",()=>function(e){const{config:t,callbacks:i,signal:n}=e,r=document.createElement("div");r.className="tbw-pivot-drop-zone tbw-pivot-values-zone",r.setAttribute("data-zone","values");const o=t.valueFields??[];if(0===o.length){const e=document.createElement("div");e.className="tbw-pivot-placeholder",e.textContent="Drag numeric fields here for aggregation",r.appendChild(e)}else for(const s of o)r.appendChild(Ii(s,e));return r.addEventListener("dragover",e=>{e.preventDefault(),r.classList.add("drag-over")},{signal:n}),r.addEventListener("dragleave",()=>{r.classList.remove("drag-over")},{signal:n}),r.addEventListener("drop",e=>{e.preventDefault(),r.classList.remove("drag-over");const t=e.dataTransfer?.getData("text/plain");t&&i.onAddValueField(t,"sum")},{signal:n}),r}(o))),s.appendChild(Mi("Available Fields",()=>function(e){const{config:t,callbacks:i,signal:n}=e,r=document.createElement("div");r.className="tbw-pivot-available-fields";const o=i.getAvailableFields(),s=new Set([...t.rowGroupFields??[],...t.columnGroupFields??[],...t.valueFields?.map(e=>e.field)??[]]),l=o.filter(e=>!s.has(e.field));if(0===l.length){const e=document.createElement("div");e.className="tbw-pivot-placeholder",e.textContent="All fields are in use",r.appendChild(e)}else for(const a of l){const e=document.createElement("div");e.className="tbw-pivot-field-chip available",e.textContent=a.header,e.draggable=!0,e.title=`Drag to add "${a.field}" to a zone`,e.addEventListener("dragstart",t=>{t.dataTransfer?.setData("text/plain",a.field),e.classList.add("dragging")},{signal:n}),e.addEventListener("dragend",()=>{e.classList.remove("dragging")},{signal:n}),r.appendChild(e)}return r}(o))),e.appendChild(s),()=>{r.abort(),s.remove()}}function Mi(e,t){const i=document.createElement("div");i.className="tbw-pivot-section";const n=document.createElement("div");n.className="tbw-pivot-section-header",n.textContent=e;const r=document.createElement("div");return r.className="tbw-pivot-section-content",r.appendChild(t()),i.appendChild(n),i.appendChild(r),i}function Pi(e,t){const{config:i,callbacks:n,signal:r}=t,o=document.createElement("div");o.className="tbw-pivot-drop-zone",o.setAttribute("data-zone",e);const s="rowGroups"===e?i.rowGroupFields??[]:i.columnGroupFields??[];if(0===s.length){const e=document.createElement("div");e.className="tbw-pivot-placeholder",e.textContent="Drag fields here or click to add",o.appendChild(e)}else for(const l of s)o.appendChild(Hi(l,e,t));return o.addEventListener("dragover",e=>{e.preventDefault(),o.classList.add("drag-over")},{signal:r}),o.addEventListener("dragleave",()=>{o.classList.remove("drag-over")},{signal:r}),o.addEventListener("drop",t=>{t.preventDefault(),o.classList.remove("drag-over");const i=t.dataTransfer?.getData("text/plain");i&&n.onAddFieldToZone(i,e)},{signal:r}),o}function Hi(e,t,i){const{callbacks:n,signal:r}=i,o=document.createElement("div");o.className="tbw-pivot-field-chip",o.draggable=!0;const s=n.getAvailableFields().find(t=>t.field===e),l=document.createElement("span");l.className="tbw-pivot-chip-label",l.textContent=s?.header??e;const a=document.createElement("button");return a.className="tbw-pivot-chip-remove",a.innerHTML="×",a.title="Remove field",a.addEventListener("click",i=>{i.stopPropagation(),n.onRemoveFieldFromZone(e,t)},{signal:r}),o.appendChild(l),o.appendChild(a),o.addEventListener("dragstart",i=>{i.dataTransfer?.setData("text/plain",e),i.dataTransfer?.setData("source-zone",t),o.classList.add("dragging")},{signal:r}),o.addEventListener("dragend",()=>{o.classList.remove("dragging")},{signal:r}),o}function Ii(e,t){const{callbacks:i,signal:n}=t,r=document.createElement("div");r.className="tbw-pivot-field-chip tbw-pivot-value-chip";const o=i.getAvailableFields().find(t=>t.field===e.field),s=document.createElement("div");s.className="tbw-pivot-value-label-wrapper";const l=document.createElement("span");l.className="tbw-pivot-chip-label",l.textContent=o?.header??e.field;const a=document.createElement("select");a.className="tbw-pivot-agg-select",a.title="Aggregation function";for(const c of Ti){const t=document.createElement("option");t.value=c,t.textContent=c.toUpperCase(),t.selected=c===e.aggFunc,a.appendChild(t)}a.addEventListener("change",()=>{i.onUpdateValueAggFunc(e.field,a.value)},{signal:n});const d=document.createElement("button");return d.className="tbw-pivot-chip-remove",d.innerHTML="×",d.title="Remove value field",d.addEventListener("click",t=>{t.stopPropagation(),i.onRemoveValueField(e.field)},{signal:n}),s.appendChild(l),s.appendChild(a),r.appendChild(s),r.appendChild(d),r}function Di(e,t,i,n){const r=document.createElement("label");r.className="tbw-pivot-checkbox";const o=document.createElement("input");o.type="checkbox",o.checked=t,o.addEventListener("change",()=>i(o.checked),{signal:n});const s=document.createElement("span");return s.textContent=e,r.appendChild(o),r.appendChild(s),r}class zi extends rt{name="pivot";styles='@layer tbw-plugins{.pivot-group-row{display:grid;grid-template-columns:var(--tbw-column-template);font-weight:600;background:var(--tbw-pivot-group-bg, var(--tbw-color-row-alt));min-height:var(--tbw-row-height);border-bottom:var(--tbw-row-divider)}.pivot-group-row:hover{background:var(--tbw-pivot-group-hover, var(--tbw-color-row-hover))}.pivot-leaf-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-pivot-leaf-bg, var(--tbw-color-bg));min-height:var(--tbw-row-height);border-bottom:var(--tbw-row-divider)}.pivot-grand-total-row{display:grid;grid-template-columns:var(--tbw-column-template);font-weight:700;background:var(--tbw-pivot-grand-total-bg, var(--tbw-color-header-bg));min-height:var(--tbw-row-height);border-top:2px solid var(--tbw-color-border-strong)}.pivot-grand-total-row>.cell{display:flex;align-items:center;padding:var(--tbw-cell-padding);border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;min-width:0}.pivot-grand-total-row>.cell:last-child{border-right:0}.pivot-grand-total-footer{position:sticky;bottom:0;z-index:var(--tbw-z-layer-pinned-rows, 20);background:var(--tbw-pivot-grand-total-bg, var(--tbw-color-header-bg));min-width:fit-content}.pivot-group-row>.cell,.pivot-leaf-row>.cell{display:flex;align-items:center;padding:var(--tbw-cell-padding);border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;min-width:0}.pivot-group-row>.cell:last-child,.pivot-leaf-row>.cell:last-child{border-right:0}.pivot-toggle{display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-pivot-toggle-size, var(--tbw-toggle-size, 1.25em));height:var(--tbw-pivot-toggle-size, var(--tbw-toggle-size, 1.25em));margin-right:var(--tbw-spacing-sm, .375em);border:none;background:transparent;cursor:pointer;color:var(--tbw-pivot-toggle-color, var(--tbw-color-fg-muted));border-radius:var(--tbw-border-radius);transition:background var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease),color var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease)}.pivot-toggle:hover{background:var(--tbw-pivot-toggle-hover-bg, var(--tbw-color-row-hover));color:var(--tbw-pivot-toggle-hover-color, var(--tbw-color-fg))}.pivot-toggle:focus{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}.pivot-label{font-weight:inherit}.pivot-count{color:var(--tbw-pivot-count-color, var(--tbw-color-fg-muted));font-size:.9em;font-weight:400}.pivot-total-row{font-weight:700;border-top:2px solid var(--tbw-pivot-border, var(--tbw-color-border-strong))}[data-pivot-depth="1"]{--tbw-pivot-depth: 1}[data-pivot-depth="2"]{--tbw-pivot-depth: 2}[data-pivot-depth="3"]{--tbw-pivot-depth: 3}[data-pivot-depth="4"]{--tbw-pivot-depth: 4}.tbw-pivot-panel{display:flex;flex-direction:column;gap:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));padding:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));height:100%;overflow-y:auto;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-pivot-section{border:1px solid var(--tbw-pivot-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius);background:var(--tbw-pivot-section-bg, var(--tbw-color-bg))}.tbw-pivot-section-header{padding:var(--tbw-button-padding, var(--tbw-spacing-md, .5rem) var(--tbw-spacing-lg, .75rem));font-weight:600;background:var(--tbw-pivot-header-bg, var(--tbw-color-header-bg));border-bottom:1px solid var(--tbw-pivot-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius) var(--tbw-border-radius) 0 0}.tbw-pivot-section-content{padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-pivot-toggle-wrapper{display:flex;align-items:center}.tbw-pivot-toggle-label{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));cursor:pointer}.tbw-pivot-toggle-label input{width:var(--tbw-icon-size, 1rem);height:var(--tbw-icon-size, 1rem);cursor:pointer}.tbw-pivot-drop-zone{min-height:60px;padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border:2px dashed var(--tbw-pivot-drop-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius);background:var(--tbw-pivot-drop-bg, var(--tbw-color-row-alt));display:flex;flex-wrap:wrap;gap:var(--tbw-spacing-sm, .375rem);align-content:flex-start;transition:all .15s ease}.tbw-pivot-drop-zone.drag-over{border-color:var(--tbw-color-accent);background:var(--tbw-pivot-drop-active, var(--tbw-focus-background))}.tbw-pivot-placeholder{color:var(--tbw-color-fg-muted);font-style:italic;padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));text-align:center;width:100%}.tbw-pivot-field-chip{display:inline-flex;align-items:center;gap:var(--tbw-spacing-sm, .375rem);padding:var(--tbw-button-padding-sm, var(--tbw-spacing-xs, .25rem) var(--tbw-spacing-md, .5rem));background:var(--tbw-pivot-chip-bg, var(--tbw-color-header-bg));border:1px solid var(--tbw-pivot-chip-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius);cursor:grab;font-size:var(--tbw-font-size-xs, .75rem);transition:all .15s ease}.tbw-pivot-field-chip:hover{background:var(--tbw-pivot-chip-hover, var(--tbw-color-row-hover));border-color:var(--tbw-color-accent)}.tbw-pivot-field-chip.available{background:var(--tbw-color-bg)}.tbw-pivot-field-chip.dragging{opacity:.5;cursor:grabbing}.tbw-pivot-chip-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:120px}.tbw-pivot-chip-remove{display:flex;align-items:center;justify-content:center;width:var(--tbw-icon-size, 1rem);height:var(--tbw-icon-size, 1rem);padding:0;border:none;background:transparent;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-sm, .875rem);font-weight:700;cursor:pointer;border-radius:50%;transition:all .15s ease}.tbw-pivot-chip-remove:hover{background:var(--tbw-pivot-chip-remove-hover-bg, var(--tbw-color-accent));color:var(--tbw-pivot-chip-remove-hover-fg, var(--tbw-color-accent-fg))}.tbw-pivot-value-chip{padding:var(--tbw-button-padding-sm, var(--tbw-spacing-xs, .25rem) var(--tbw-spacing-md, .5rem))}.tbw-pivot-value-label-wrapper{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));flex:1;min-width:0}.tbw-pivot-agg-select{padding:var(--tbw-spacing-xs, .125rem) var(--tbw-spacing-xs, .25rem);font-size:var(--tbw-font-size-xs, .6875rem);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);background:var(--tbw-color-bg);cursor:pointer}.tbw-pivot-available-fields{display:flex;flex-wrap:wrap;gap:var(--tbw-spacing-sm, .375rem);min-height:40px}.tbw-pivot-options{display:flex;flex-direction:column;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-pivot-checkbox{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));cursor:pointer}.tbw-pivot-checkbox input{width:var(--tbw-icon-size-sm, .875rem);height:var(--tbw-icon-size-sm, .875rem);cursor:pointer}.pivot-group-row.tbw-pivot-slide-in,.pivot-leaf-row.tbw-pivot-slide-in{animation:tbw-pivot-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-pivot-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.pivot-group-row.tbw-pivot-fade-in,.pivot-leaf-row.tbw-pivot-fade-in{animation:tbw-pivot-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-pivot-fade-in{0%{opacity:0}to{opacity:1}}}';static PANEL_ID="pivot";get defaultConfig(){return{active:!0,showTotals:!0,showGrandTotal:!0,showToolPanel:!0,animation:"slide"}}isActive=!1;hasInitialized=!1;pivotResult=null;fieldHeaderMap=new Map;expandedKeys=new Set;defaultExpanded=!0;userHasToggledExpand=!1;originalColumns=[];panelContainer=null;grandTotalFooter=null;previousVisibleKeys=new Set;keysToAnimate=new Set;hasValidPivotConfig(){return(this.config.valueFields?.length??0)>0}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detach(){this.isActive=!1,this.hasInitialized=!1,this.pivotResult=null,this.fieldHeaderMap.clear(),this.originalColumns=[],this.panelContainer=null,this.cleanupGrandTotalFooter(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.userHasToggledExpand=!1}getToolPanel(){if(!1!==(this.config?.showToolPanel??this.userConfig?.showToolPanel??!0))return{id:zi.PANEL_ID,title:"Pivot",icon:"⊞",tooltip:"Configure pivot table",order:90,render:e=>this.renderPanel(e)}}processRows(e){if(!this.hasInitialized&&!1!==this.config.active&&this.hasValidPivotConfig()&&(this.hasInitialized=!0,this.isActive=!0),!this.isActive)return[...e];const t=function(e){const t=[];return e.rowGroupFields?.length||e.columnGroupFields?.length||t.push("At least one row or column group field is required"),e.valueFields?.length||t.push("At least one value field is required"),t}(this.config);if(t.length>0)return this.warn(`Config errors: ${t.join(", ")}`),[...e];this.buildFieldHeaderMap(),this.defaultExpanded=this.config.defaultExpanded??!0,this.pivotResult=Si(e,this.config),0===this.expandedKeys.size&&this.defaultExpanded&&!this.userHasToggledExpand&&this.expandAllKeys();const i=this.config.indentWidth??20,n=function(e,t,i=!0){const n=[];function r(e){n.push(e);const o=t?t.has(e.rowKey):i;if(e.children&&o)for(const t of e.children)r(t)}for(const o of e)r(o);return n}(this.pivotResult.rows,this.expandedKeys,this.defaultExpanded).map(e=>({__pivotRowKey:e.rowKey,__pivotLabel:e.rowLabel,__pivotDepth:e.depth,__pivotIsGroup:e.isGroup,__pivotHasChildren:Boolean(e.children?.length),__pivotExpanded:this.expandedKeys.has(e.rowKey),__pivotRowCount:e.rowCount??0,__pivotIndent:e.depth*i,__pivotTotal:e.total,...e.values}));this.keysToAnimate.clear();const r=new Set;for(const o of n){const e=o.__pivotRowKey;r.add(e),!this.previousVisibleKeys.has(e)&&o.__pivotDepth>0&&this.keysToAnimate.add(e)}return this.previousVisibleKeys=r,n}processColumns(e){if(!this.isActive||!this.pivotResult)return[...e];const t=[],i=(this.config.rowGroupFields??[]).map(e=>this.fieldHeaderMap.get(e)??e).join(" / ");t.push({field:"__pivotLabel",header:i||"Group",width:200});for(const n of this.pivotResult.columnKeys)for(const e of this.config.valueFields??[]){const i=Ri([n],e.field),r=e.header||this.fieldHeaderMap.get(e.field)||e.field;t.push({field:i,header:`${n} - ${r} (${e.aggFunc})`,width:120,type:"number"})}return this.config.showTotals&&t.push({field:"__pivotTotal",header:"Total",width:100,type:"number"}),t}renderRow(e,t,i){const n=e;return n.__pivotRowKey&&n.__pivotHasChildren?function(e,t,i){return t.className="data-grid-row pivot-group-row",t.setAttribute("data-pivot-depth",String(e.__pivotDepth??0)),t.setAttribute("data-pivot-key",String(e.__pivotRowKey??"")),t.setAttribute("role","row"),t.innerHTML="",i.columns.forEach((n,r)=>{const o=document.createElement("div");if(o.className="cell",o.setAttribute("data-col",String(r)),o.setAttribute("data-row",String(i.rowIndex)),o.setAttribute("role","gridcell"),0===r){const t=Number(e.__pivotIndent)||0;o.style.paddingLeft=`${t}px`;const n=String(e.__pivotRowKey),r=document.createElement("button");r.type="button",r.className="pivot-toggle",r.setAttribute("aria-label",e.__pivotExpanded?"Collapse group":"Expand group"),i.setIcon(r,i.resolveIcon(e.__pivotExpanded?"collapse":"expand")),r.addEventListener("click",e=>{e.stopPropagation(),i.onToggle(n)}),o.appendChild(r);const s=document.createElement("span");s.className="pivot-label",s.textContent=String(e.__pivotLabel??""),o.appendChild(s);const l=document.createElement("span");l.className="pivot-count",l.textContent=` (${Number(e.__pivotRowCount)||0})`,o.appendChild(l)}else{const t=e[n.field];o.textContent=null!=t?String(t):""}t.appendChild(o)}),!0}(n,t,{columns:this.gridColumns,rowIndex:i,onToggle:e=>this.toggle(e),resolveIcon:e=>this.resolveIcon(e),setIcon:(e,t)=>this.setIcon(e,t)}):void 0!==n.__pivotRowKey&&this.isActive?function(e,t,i,n){return t.className="data-grid-row pivot-leaf-row",t.setAttribute("data-pivot-depth",String(e.__pivotDepth??0)),t.setAttribute("data-pivot-key",String(e.__pivotRowKey??"")),t.innerHTML="",i.forEach((i,r)=>{const o=document.createElement("div");if(o.className="cell",o.setAttribute("data-col",String(r)),o.setAttribute("data-row",String(n)),o.setAttribute("role","gridcell"),0===r){const t=Number(e.__pivotIndent)||0;o.style.paddingLeft=`${t+20}px`;const i=document.createElement("span");i.className="pivot-label",i.textContent=String(e.__pivotLabel??""),o.appendChild(i)}else{const t=e[i.field];o.textContent=null!=t?String(t):""}t.appendChild(o)}),!0}(n,t,this.gridColumns,i):(this.cleanupPivotStyling(t),!1)}cleanupPivotStyling(e){(e.classList.contains("pivot-group-row")||e.classList.contains("pivot-leaf-row")||e.classList.contains("pivot-grand-total-row"))&&(e.classList.remove("pivot-group-row","pivot-leaf-row","pivot-grand-total-row"),e.classList.add("data-grid-row"),e.removeAttribute("data-pivot-depth"),e.innerHTML="")}onKeyDown(e){if(" "!==e.key)return;if(!this.isActive)return;const t=this.grid._focusRow,i=this.rows[t];return i?.__pivotIsGroup&&i.__pivotHasChildren?(e.preventDefault(),this.toggle(i.__pivotRowKey),this.requestRenderWithFocus(),!0):void 0}afterRender(){this.isActive&&this.config.showGrandTotal&&this.pivotResult?this.renderGrandTotalFooter():this.cleanupGrandTotalFooter();const e=this.animationStyle;if(!1===e||0===this.keysToAnimate.size)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const i="fade"===e?"tbw-pivot-fade-in":"tbw-pivot-slide-in";for(const n of t.querySelectorAll(".pivot-group-row, .pivot-leaf-row")){const e=n.dataset.pivotKey;e&&this.keysToAnimate.has(e)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}renderGrandTotalFooter(){if(!this.pivotResult)return;const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-scroll-area")??e.querySelector(".tbw-grid-content")??e.children[0];if(!t)return;this.grandTotalFooter||(this.grandTotalFooter=document.createElement("div"),this.grandTotalFooter.className="pivot-grand-total-footer",t.appendChild(this.grandTotalFooter));const i={__pivotRowKey:"__grandTotal",__pivotLabel:"Grand Total",__pivotIsGrandTotal:!0,__pivotTotal:this.pivotResult.grandTotal,...this.pivotResult.totals};var n,r,o;n=i,r=this.grandTotalFooter,o=this.gridColumns,r.className="pivot-grand-total-row",r.setAttribute("role","presentation"),r.innerHTML="",o.forEach((e,t)=>{const i=document.createElement("div");if(i.className="cell",i.setAttribute("data-col",String(t)),0===t){const e=document.createElement("span");e.className="pivot-label",e.textContent="Grand Total",i.appendChild(e)}else{const t=n[e.field];i.textContent=null!=t?String(t):""}r.appendChild(i)})}cleanupGrandTotalFooter(){this.grandTotalFooter&&(this.grandTotalFooter.remove(),this.grandTotalFooter=null)}toggle(e){this.userHasToggledExpand=!0,this.expandedKeys.has(e)?this.expandedKeys.delete(e):this.expandedKeys.add(e),this.requestRender()}expand(e){this.userHasToggledExpand=!0,this.expandedKeys.add(e),this.requestRender()}collapse(e){this.userHasToggledExpand=!0,this.expandedKeys.delete(e),this.requestRender()}expandAll(){this.userHasToggledExpand=!0,this.expandAllKeys(),this.requestRender()}collapseAll(){this.userHasToggledExpand=!0,this.expandedKeys.clear(),this.requestRender()}expandAllKeys(){if(!this.pivotResult)return;const e=function(e){const t=[];function i(e){if(e.isGroup&&t.push(e.rowKey),e.children)for(const t of e.children)i(t)}for(const n of e)i(n);return t}(this.pivotResult.rows);for(const t of e)this.expandedKeys.add(t)}isExpanded(e){return this.expandedKeys.has(e)}enablePivot(){0===this.originalColumns.length&&this.captureOriginalColumns(),this.isActive=!0,this.requestRender()}disablePivot(){this.isActive=!1,this.pivotResult=null,this.requestRender()}isPivotActive(){return this.isActive}getPivotResult(){return this.pivotResult}setRowGroupFields(e){this.config.rowGroupFields=e,this.requestRender()}setColumnGroupFields(e){this.config.columnGroupFields=e,this.requestRender()}setValueFields(e){this.config.valueFields=e,this.requestRender()}refresh(){this.pivotResult=null,this.requestRender()}showPanel(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(zi.PANEL_ID)||this.grid.toggleToolPanelSection(zi.PANEL_ID)}hidePanel(){this.grid.closeToolPanel()}togglePanel(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(zi.PANEL_ID)}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(zi.PANEL_ID)}get gridColumns(){return this.grid.columns??[]}refreshIfActive(){this.isActive&&this.refresh(),this.refreshPanel()}buildFieldHeaderMap(){const e=this.getAvailableFields();this.fieldHeaderMap.clear();for(const t of e)this.fieldHeaderMap.set(t.field,t.header)}getAvailableFields(){return this.originalColumns.length>0?this.originalColumns:this.captureOriginalColumns()}captureOriginalColumns(){try{const e=this.grid.getAllColumns?.()??this.grid.columns??[];return this.originalColumns=e.filter(e=>!e.field.startsWith("__pivot")).map(e=>({field:e.field,header:e.header??e.field})),this.originalColumns}catch{return[]}}renderPanel(e){this.panelContainer=e,0===this.originalColumns.length&&this.captureOriginalColumns();const t={onTogglePivot:e=>{e?this.enablePivot():this.disablePivot(),this.refreshPanel()},onAddFieldToZone:(e,t)=>this.addFieldToZone(e,t),onRemoveFieldFromZone:(e,t)=>this.removeFieldFromZone(e,t),onAddValueField:(e,t)=>this.addValueField(e,t),onRemoveValueField:e=>this.removeValueField(e),onUpdateValueAggFunc:(e,t)=>this.updateValueAggFunc(e,t),onOptionChange:(e,t)=>{this.config[e]=t,this.isActive&&this.refresh()},getAvailableFields:()=>this.getAvailableFields()};return Li(e,this.config,this.isActive,t)}refreshPanel(){this.panelContainer&&(this.panelContainer.innerHTML="",this.renderPanel(this.panelContainer))}addFieldToZone(e,t){if("rowGroups"===t){const t=this.config.rowGroupFields??[];t.includes(e)||(this.config.rowGroupFields=[...t,e])}else{const t=this.config.columnGroupFields??[];t.includes(e)||(this.config.columnGroupFields=[...t,e])}this.removeFromOtherZones(e,t),this.refreshIfActive()}removeFieldFromZone(e,t){"rowGroups"===t?this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(t=>t!==e):this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(t=>t!==e),this.refreshIfActive()}removeFromOtherZones(e,t){"rowGroups"!==t&&(this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(t=>t!==e)),"columnGroups"!==t&&(this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(t=>t!==e)),"values"!==t&&(this.config.valueFields=(this.config.valueFields??[]).filter(t=>t.field!==e))}addValueField(e,t){const i=this.config.valueFields??[];i.some(t=>t.field===e)||(this.config.valueFields=[...i,{field:e,aggFunc:t}]),this.removeFromOtherZones(e,"values"),this.refreshIfActive()}removeValueField(e){this.config.valueFields=(this.config.valueFields??[]).filter(t=>t.field!==e),this.refreshIfActive()}updateValueAggFunc(e,t){const i=this.config.valueFields??[],n=i.findIndex(t=>t.field===e);n>=0&&(i[n]={...i[n],aggFunc:t},this.config.valueFields=[...i]),this.isActive&&this.refresh()}}const Oi="tbw-print-isolation-style";async function qi(e,t={}){const{orientation:i="landscape"}=t,n=e.id;document.querySelectorAll(`#${CSS.escape(n)}`).length>1&&console.warn(`[tbw-grid:print] Multiple elements found with id="${n}". Print isolation may not work correctly. Ensure each grid has a unique ID.`),document.getElementById(Oi)?.remove();const r=function(e,t){const i=document.createElement("style");return i.id=Oi,i.textContent=`\n /* Print isolation: hide everything except the target grid */\n @media print {\n /* Hide all body children by default */\n body > *:not(#${e}) {\n display: none !important;\n }\n\n /* But show the grid and ensure it's not hidden by ancestor rules */\n #${e} {\n display: block !important;\n position: static !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n width: 100% !important;\n max-height: none !important;\n margin: 0 !important;\n padding: 0 !important;\n transform: none !important;\n }\n\n /* If grid is nested, we need to show its ancestors too */\n #${e},\n #${e} * {\n visibility: visible !important;\n }\n\n /* Walk up the DOM and show all ancestors of the grid */\n body *:has(> #${e}),\n body *:has(#${e}) {\n display: block !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n position: static !important;\n transform: none !important;\n background: transparent !important;\n border: none !important;\n padding: 0 !important;\n margin: 0 !important;\n }\n\n /* Hide siblings of ancestors (everything that's not in the path to the grid) */\n body *:has(#${e}) > *:not(:has(#${e})):not(#${e}) {\n display: none !important;\n }\n\n /* Page settings */\n @page {\n size: ${t};\n margin: 1cm;\n }\n\n /* Ensure proper print styling */\n body {\n margin: 0 !important;\n padding: 0 !important;\n background: white !important;\n color-scheme: light !important;\n }\n }\n\n /* Screen: also apply isolation for print preview */\n @media screen {\n /* When this stylesheet is active, we're about to print */\n /* No screen-specific rules needed - isolation only applies to print */\n }\n `,i}(n,i);return document.head.appendChild(r),new Promise(e=>{const t=()=>{window.removeEventListener("afterprint",t),document.getElementById(Oi)?.remove(),e()};window.addEventListener("afterprint",t),window.print(),setTimeout(()=>{window.removeEventListener("afterprint",t),document.getElementById(Oi)?.remove(),e()},5e3)})}const Fi={button:!1,orientation:"landscape",warnThreshold:500,maxRows:0,includeTitle:!0,includeTimestamp:!0,title:"",isolate:!1};function Ni(e,t,i){if(t===i)return e;if(t<0||t>=e.length)return e;if(i<0||i>e.length)return e;const n=[...e],[r]=n.splice(t,1);return n.splice(i,0,r),n}const Gi="__tbw_row_drag";function Vi(e){return{startRow:Math.min(e.startRow,e.endRow),startCol:Math.min(e.startCol,e.endCol),endRow:Math.max(e.startRow,e.endRow),endCol:Math.max(e.startCol,e.endCol)}}function $i(e){const t=Vi(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function Bi(e){return e.map($i)}function Wi(e,t,i){return i.some(i=>function(e,t,i){const n=Vi(i);return e>=n.startRow&&e<=n.endRow&&t>=n.startCol&&t<=n.endCol}(e,t,i))}function Ki(e){const t=[],i=Vi(e);for(let n=i.startRow;n<=i.endRow;n++)for(let e=i.startCol;e<=i.endCol;e++)t.push({row:n,col:e});return t}function Ui(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function ji(e,t){const i=Vi(e),n=Vi(t);return i.startRow===n.startRow&&i.startCol===n.startCol&&i.endRow===n.endRow&&i.endCol===n.endCol}const Yi="__tbw_checkbox";function Xi(e,t){return Math.floor(e/t)}async function Zi(e,t,i,n){const r=function(e,t){return{start:e*t,end:(e+1)*t}}(t,i);return e.getRows({startRow:r.start,endRow:r.end,sortModel:n.sortModel,filterModel:n.filterModel})}function Qi(e,t,i){const n=Xi(e,t),r=i.get(n);if(!r)return;return r[e%t]}function Ji(e,t,i){return void 0!==e.id?String(e.id):i?`${i}-${t}`:String(t)}function en(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}function tn(e,t,i=null,n=0){const r=t.childrenField??"children",o=new Set;for(let s=0;s<e.length;s++){const l=e[s],a=Ji(l,s,i),d=l[r];if(Array.isArray(d)&&d.length>0){o.add(a);const e=tn(d,t,a,n+1);for(const t of e)o.add(t)}}return o}function nn(e,t,i,n=null,r=0){const o=i.childrenField??"children";for(let s=0;s<e.length;s++){const l=e[s],a=Ji(l,s,n);if(a===t)return[a];const d=l[o];if(Array.isArray(d)&&d.length>0){const e=nn(d,t,i,a,r+1);if(e)return[a,...e]}}return null}function rn(e,t,i,n){const r=nn(e,t,i);if(!r)return n;const o=new Set(n);for(let s=0;s<r.length-1;s++)o.add(r[s]);return o}function on(e,t="children"){if(!Array.isArray(e)||0===e.length)return!1;for(const i of e){if(!i)continue;const e=i[t];if(Array.isArray(e)&&e.length>0)return!0}return!1}function sn(e){if(0===e.undoStack.length)return{newState:e,action:null};const t=[...e.undoStack],i=t.pop();return i?{newState:{undoStack:t,redoStack:[...e.redoStack,i]},action:i}:{newState:e,action:null}}function ln(e){if(0===e.redoStack.length)return{newState:e,action:null};const t=[...e.redoStack],i=t.pop();return i?{newState:{undoStack:[...e.undoStack,i],redoStack:t},action:i}:{newState:e,action:null}}function an(e){const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}class dn extends rt{static dependencies=[{name:"reorder",required:!1,reason:"Enables drag-to-reorder columns in visibility panel"}];static manifest={queries:[{type:"getContextMenuItems",description:'Contributes "Hide column" item to the header context menu'}]};name="visibility";static PANEL_ID="columns";styles='@layer tbw-plugins{.tbw-visibility-content{display:flex;flex-direction:column;height:100%}.tbw-visibility-list{flex:1;overflow-y:auto;padding:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem))}.tbw-visibility-row{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-menu-item-padding, .375rem .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);border-radius:var(--tbw-border-radius, .25rem);position:relative}.tbw-visibility-row:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-row input[type=checkbox]{cursor:pointer}.tbw-visibility-row.locked span{color:var(--tbw-color-fg-muted)}.tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-row.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-label{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));flex:1;cursor:pointer}.tbw-visibility-row.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-row.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-show-all{margin:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding, .5rem .75rem);border:1px solid var(--tbw-visibility-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius, .25rem);background:var(--tbw-visibility-btn-bg, var(--tbw-color-header-bg));color:var(--tbw-color-fg);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-visibility-show-all:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header{display:flex;align-items:center;padding:var(--tbw-menu-item-padding, .375rem .25rem);font-size:var(--tbw-font-size-sm, .8125rem);font-weight:600;color:var(--tbw-color-fg);border-bottom:1px solid var(--tbw-color-border);margin-top:var(--tbw-spacing-sm, .25rem);position:relative}.tbw-visibility-group-header:first-child{margin-top:0}.tbw-visibility-group-header .tbw-visibility-label{gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-visibility-group-header.reorderable{cursor:grab}.tbw-visibility-group-header.reorderable:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header .tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-group-header.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-group-header.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-group-header.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-group-header.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row--grouped{padding-left:calc(var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem)) + .75rem)}}';get defaultConfig(){return{allowHideAll:!1}}columnListElement=null;isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;draggedGroupId=null;draggedGroupFields=[];clearDragClasses(e){e.querySelectorAll(".tbw-visibility-row, .tbw-visibility-group-header").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-move",()=>{this.columnListElement&&requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})},{signal:this.disconnectSignal})}detach(){this.columnListElement=null,this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}handleQuery(e){if("getContextMenuItems"===e.type){const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field)return;if(i.meta?.lockVisibility)return;return[{id:"visibility/hide-column",label:"Hide Column",icon:"👁",order:30,action:()=>this.hideColumn(i.field)}]}}getToolPanel(){return{id:dn.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(dn.PANEL_ID)||this.grid.toggleToolPanelSection(dn.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(dn.PANEL_ID)}isColumnVisible(e){return this.grid.isColumnVisible(e)}setColumnVisible(e,t){this.grid.setColumnVisible(e,t)}getVisibleColumns(){return this.grid.getAllColumns().filter(e=>e.visible).map(e=>e.field)}getHiddenColumns(){return this.grid.getAllColumns().filter(e=>!e.visible).map(e=>e.field)}showAll(){this.grid.showAllColumns()}toggleColumn(e){this.grid.toggleColumnVisibility(e)}showColumn(e){this.setColumnVisible(e,!0)}hideColumn(e){this.setColumnVisible(e,!1)}getAllColumns(){return this.grid.getAllColumns()}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(dn.PANEL_ID)}renderPanelContent(e){const t=document.createElement("div");t.className="tbw-visibility-content";const i=document.createElement("div");i.className="tbw-visibility-list",t.appendChild(i);const n=document.createElement("button");return n.className="tbw-visibility-show-all",n.textContent="Show All",n.addEventListener("click",()=>{this.grid.showAllColumns(),this.rebuildToggles(i)}),t.appendChild(n),this.columnListElement=i,this.rebuildToggles(i),e.appendChild(t),()=>{this.columnListElement=null,t.remove()}}hasReorderPlugin(){const e=this.grid?.getPluginByName?.("reorder");return!(!e||"function"!=typeof e.moveColumn)}rebuildToggles(e){const t=this.hasReorderPlugin();e.innerHTML="";const i=this.grid.getAllColumns().filter(e=>!e.utility),n=this.grid.query("getColumnGrouping"),r=n?.flat().filter(e=>e&&e.fields.length>0)??[];if(0===r.length)return void this.renderFlatColumnList(i,t,e);const o=new Map;for(const l of r)for(const e of l.fields)o.set(e,l);const s=new Set;for(const l of i){const n=o.get(l.field);if(n){if(!s.has(n.id)){s.add(n.id);const r=new Set(n.fields),o=i.filter(e=>r.has(e.field));o.length>0&&this.renderGroupSection(n,o,t,e)}}else{const n=i.indexOf(l);e.appendChild(this.createColumnRow(l,n,t,e))}}}renderGroupSection(e,t,i,n){const r=document.createElement("div");r.className="tbw-visibility-group-header",r.setAttribute("data-group-id",e.id),i&&(r.draggable=!0,r.classList.add("reorderable"),this.setupGroupDragListeners(r,e,n));const o=document.createElement("label");o.className="tbw-visibility-label";const s=document.createElement("input");s.type="checkbox";const l=t.filter(e=>e.visible).length,a=t.every(e=>e.lockVisible);l===t.length?(s.checked=!0,s.indeterminate=!1):0===l?(s.checked=!1,s.indeterminate=!1):(s.checked=!1,s.indeterminate=!0),s.disabled=a,s.addEventListener("change",()=>{const e=s.checked;for(const i of t)i.lockVisible||this.grid.setColumnVisible(i.field,e);setTimeout(()=>this.rebuildToggles(n),0)});const d=document.createElement("span");if(d.textContent=e.label,o.appendChild(s),o.appendChild(d),r.appendChild(o),i){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,this.resolveIcon("dragHandle")),e.title="Drag to reorder group",r.insertBefore(e,o)}n.appendChild(r);const c=this.grid.getAllColumns().filter(e=>!e.utility);for(const h of t){const e=c.findIndex(e=>e.field===h.field),t=this.createColumnRow(h,e,i,n);t.classList.add("tbw-visibility-row--grouped"),n.appendChild(t)}}renderFlatColumnList(e,t,i){const n=this.grid.getAllColumns().filter(e=>!e.utility);for(const r of e){const e=n.findIndex(e=>e.field===r.field);i.appendChild(this.createColumnRow(r,e,t,i))}}createColumnRow(e,t,i,n){const r=e.header||e.field,o=document.createElement("div");o.className=e.lockVisible?"tbw-visibility-row locked":"tbw-visibility-row",o.setAttribute("data-field",e.field),o.setAttribute("data-index",String(t)),i&&an(e)&&(o.draggable=!0,o.classList.add("reorderable"),this.setupDragListeners(o,e.field,t,n));const s=document.createElement("label");s.className="tbw-visibility-label";const l=document.createElement("input");l.type="checkbox",l.checked=e.visible,l.disabled=e.lockVisible??!1,l.addEventListener("change",()=>{this.grid.toggleColumnVisibility(e.field),setTimeout(()=>this.rebuildToggles(n),0)});const a=document.createElement("span");if(a.textContent=r,s.appendChild(l),s.appendChild(a),i&&an(e)){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,this.resolveIcon("dragHandle")),e.title="Drag to reorder",o.appendChild(e)}return o.appendChild(s),o}setupGroupDragListeners(e,t,i){e.addEventListener("dragstart",n=>{this.isDragging=!0,this.draggedGroupId=t.id,this.draggedGroupFields=[...t.fields],this.draggedField=null,this.draggedIndex=null,n.dataTransfer&&(n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",`group:${t.id}`)),e.classList.add("dragging"),i.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&e.classList.add("dragging")})}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedGroupId=null,this.draggedGroupFields=[],this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(i)}),e.addEventListener("dragover",n=>{if(n.preventDefault(),!this.isDragging)return;if(this.draggedGroupId===t.id)return;if(!this.draggedGroupId)return;const r=e.getBoundingClientRect(),o=r.top+r.height/2,s=n.clientY<o;this.clearDragClasses(i),e.classList.add("drop-target"),e.classList.toggle("drop-before",s),e.classList.toggle("drop-after",!s)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",n=>{if(n.preventDefault(),!this.isDragging||!this.draggedGroupId||this.draggedGroupId===t.id)return;const r=e.getBoundingClientRect(),o=n.clientY<r.top+r.height/2;this.executeGroupDrop(this.draggedGroupFields,t.fields,o,i)})}executeGroupDrop(e,t,i,n){const r=this.grid.getAllColumns().map(e=>e.field),o=r.filter(t=>!e.includes(t)),s=i?t[0]:t[t.length-1],l=o.indexOf(s);if(-1===l)return;const a=i?l:l+1,d=r.filter(t=>e.includes(t));o.splice(a,0,...d),this.grid.setColumnOrder(o),requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})}setupDragListeners(e,t,i,n){e.addEventListener("dragstart",n=>{this.isDragging=!0,this.draggedField=t,this.draggedIndex=i,this.draggedGroupId=null,this.draggedGroupFields=[],n.dataTransfer&&(n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",t)),e.classList.add("dragging")}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(n)}),e.addEventListener("dragover",r=>{if(r.preventDefault(),!this.isDragging)return;if(this.draggedGroupId){if(e.classList.contains("tbw-visibility-row--grouped"))return}else if(this.draggedField===t)return;const o=e.getBoundingClientRect(),s=o.top+o.height/2;this.dropIndex=r.clientY<s?i:i+1,this.clearDragClasses(n),this.draggedGroupId?(n.querySelector(`.tbw-visibility-group-header[data-group-id="${this.draggedGroupId}"]`)?.classList.add("dragging"),n.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&e.classList.add("dragging")})):this.draggedField&&n.querySelector(`.tbw-visibility-row[data-field="${this.draggedField}"]`)?.classList.add("dragging"),e.classList.add("drop-target"),e.classList.toggle("drop-before",r.clientY<s),e.classList.toggle("drop-after",r.clientY>=s)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",i=>{if(i.preventDefault(),!this.isDragging)return;if(this.draggedGroupId&&this.draggedGroupFields.length>0){if(e.classList.contains("tbw-visibility-row--grouped"))return;const r=e.getBoundingClientRect(),o=i.clientY<r.top+r.height/2;return void this.executeGroupDrop(this.draggedGroupFields,[t],o,n)}const r=this.draggedField,o=this.draggedIndex,s=this.dropIndex;if(null===r||null===o||null===s)return;const l=s>o?s-1:s;if(l!==o){const e=this.grid.getAllColumns(),t=e.filter(e=>!e.utility),i=t[l]?.field,n={field:r,fromIndex:o,toIndex:i?e.findIndex(e=>e.field===i):e.length};this.emit("column-reorder-request",n)}})}}e.BLANK_FILTER_VALUE=qt,e.BaseGridPlugin=rt,e.ClipboardPlugin=class extends rt{static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:"\t",newline:"\n",quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e);e.addEventListener("paste",e=>this.#gt(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#pt(e.target),!0)}#pt(e){const t=this.#ft();if(t&&0===t.ranges.length){const t=this.#wt(e);if(!t)return;const i=this.columns[t.col];if(!i)return;return void this.copy({rowIndices:[t.row],columns:[i.field]})}this.copy()}#gt(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const i=ht(t,this.config),n=this.#ft(),r=n?.ranges?.[0],o=r?.from.row??0,s=r?.from.col??0,l=r&&("range"===n?.mode||"row"===n?.mode)&&(r.from.row!==r.to.row||r.from.col!==r.to.col)?{endRow:r.to.row,endCol:r.to.col}:null,a=l?.endCol??this.visibleColumns.length-1,d=this.visibleColumns[s],c=d?{row:o,col:s,field:d.field,bounds:l}:null,h=[],u=i[0]?.length??0;for(let p=0;p<u&&s+p<=a;p++){const e=this.visibleColumns[s+p];e&&h.push(e.field)}const g={rows:i,text:t,target:c,fields:h};this.emit("paste",g),this.#mt(g)}#mt(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??ut)(e,this.grid)}#ft(){const e=this.grid?.query("getSelection");return e?.[0]}#bt(e){const t=this.#ft();let i,n;if(e?.columns)i=at(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],n=Math.min(e.from.col,e.to.col),r=Math.max(e.from.col,e.to.col);i=at(this.visibleColumns.slice(n,r+1))}else i=at(this.columns);if(e?.rowIndices)n=dt(this.rows,e.rowIndices);else if(t?.ranges.length){const e=t.ranges[t.ranges.length-1],i=Math.min(e.from.row,e.to.row),r=Math.max(e.from.row,e.to.row);n=[];for(let t=i;t<=r;t++){const e=this.rows[t];e&&n.push(e)}}else n=this.rows;return{columns:i,rows:n}}#vt(e,t,i){const n=i?.delimiter??this.config.delimiter??"\t",r=i?.newline??this.config.newline??"\n",o=i?.includeHeaders??this.config.includeHeaders??!1,s=i?.processCell??this.config.processCell,l=[];o&&l.push(e.map(e=>e.header||e.field).join(n));for(const a of t){const t=e.map(e=>{const t=a[e.field];return s?s(t,e.field,a):ct(t)});l.push(t.join(n))}return l.join(r)}#wt(e){const t=e.closest("[data-field-cache]");if(!t)return null;const i=t.dataset.fieldCache,n=t.dataset.row;if(!i||!n)return null;const r=parseInt(n,10);if(isNaN(r))return null;const o=this.columns.findIndex(e=>e.field===i);return-1===o?null:{row:r,col:o}}getSelectionAsText(e){const{columns:t,rows:i}=this.#bt(e);return 0===t.length||0===i.length?"":this.#vt(t,i,e)}async copy(e){const{columns:t,rows:i}=this.#bt(e);if(0===t.length||0===i.length)return"";const n=this.#vt(t,i,e);return await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){console.warn("[copyToClipboard] Clipboard API failed:",t);const i=document.createElement("textarea");i.value=e,i.style.position="fixed",i.style.opacity="0",i.style.pointerEvents="none",document.body.appendChild(i),i.select();const n=document.execCommand("copy");return document.body.removeChild(i),n}}(n),this.lastCopied={text:n,timestamp:Date.now()},this.emit("copy",{text:n,rowCount:i.length,columnCount:t.length}),n}async copyRows(e,t){return 0===e.length?"":this.copy({...t,rowIndices:e})}async paste(){const e=await async function(){try{return await navigator.clipboard.readText()}catch{return""}}();return e?ht(e,this.config):null}getLastCopied(){return this.lastCopied}},e.ColumnVirtualizationPlugin=class extends rt{name="columnVirtualization";get defaultConfig(){return{autoEnable:!0,threshold:30,overscan:3}}isVirtualized=!1;startCol=0;endCol=0;scrollLeft=0;totalWidth=0;columnWidths=[];columnOffsets=[];originalColumns=[];attach(e){super.attach(e);const t=this.columns;this.columnWidths=pt(t),this.columnOffsets=ft(t),this.totalWidth=wt(t),this.endCol=t.length-1}detach(){this.#yt(),this.columnWidths=[],this.columnOffsets=[],this.originalColumns=[],this.isVirtualized=!1,this.startCol=0,this.endCol=0,this.scrollLeft=0,this.totalWidth=0}#yt(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".header-row");t&&(t.style.paddingLeft="",t.style.minWidth="");e.querySelectorAll(".data-grid-row").forEach(e=>{e.style.paddingLeft=""});const i=e.querySelector(".rows-viewport .rows");i&&(i.style.width="");const n=e.querySelector(".rows-body");n&&(n.style.minWidth="")}processColumns(e){(0===this.originalColumns.length||e.length>=this.originalColumns.length)&&(this.originalColumns=e,this.columnWidths=pt(e),this.columnOffsets=ft(e),this.totalWidth=wt(e));const t=this.originalColumns,i=(n=t.length,r=this.config.threshold??30,!!(this.config.autoEnable??!0)&&n>r);var n,r;if(this.isVirtualized=i??!1,!i)return this.startCol=0,this.endCol=t.length-1,[...t];const o=this.grid.clientWidth||800,s=mt(this.scrollLeft,o,this.columnOffsets,this.columnWidths,this.config.overscan??3);return this.startCol=s.startCol,this.endCol=s.endCol,s.visibleColumns.map(e=>t[e])}afterRender(){if(!this.isVirtualized)return;const e=this.gridElement;if(!e)return;const t=this.columnOffsets[this.startCol]??0,i=e.querySelector(".header-row"),n=e.querySelectorAll(".data-grid-row");i&&(i.style.paddingLeft=`${t}px`,i.style.minWidth=`${this.totalWidth}px`),n.forEach(e=>{e.style.paddingLeft=`${t}px`});const r=e.querySelector(".rows-viewport .rows");r&&(r.style.width=`${this.totalWidth}px`);const o=e.querySelector(".rows-body");o&&(o.style.minWidth=`${this.totalWidth}px`)}onScroll(e){if(!this.isVirtualized)return;Math.abs(e.scrollLeft-this.scrollLeft)<1||(this.scrollLeft=e.scrollLeft,this.requestColumnsRender())}getIsVirtualized(){return this.isVirtualized}getVisibleColumnRange(){return{start:this.startCol,end:this.endCol}}scrollToColumn(e){const t=this.columnOffsets[e]??0;this.grid.scrollLeft=t}getColumnOffset(e){return this.columnOffsets[e]??0}getTotalWidth(){return this.totalWidth}},e.ContextMenuPlugin=Lt,e.DEFAULT_ANIMATION_CONFIG=i,e.DEFAULT_GRID_ICONS=r,e.DGEvents={CELL_CHANGE:"cell-change",CELL_COMMIT:"cell-commit",ROW_COMMIT:"row-commit",EDIT_OPEN:"edit-open",EDIT_CLOSE:"edit-close",CHANGED_ROWS_RESET:"changed-rows-reset",MOUNT_EXTERNAL_VIEW:"mount-external-view",MOUNT_EXTERNAL_EDITOR:"mount-external-editor",SORT_CHANGE:"sort-change",COLUMN_RESIZE:"column-resize",ACTIVATE_CELL:"activate-cell",CELL_ACTIVATE:"cell-activate",GROUP_TOGGLE:"group-toggle",COLUMN_STATE_CHANGE:"column-state-change"},e.DataGridElement=nt,e.EditingPlugin=class extends rt{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>!0===e},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'}],events:[{type:"cell-edit-committed",description:"Emitted when a cell edit is committed (for plugin-to-plugin coordination)"}],queries:[{type:"isEditing",description:"Returns whether any cell is currently being edited"}]};name="editing";styles="@layer tbw-plugins{tbw-grid{--tbw-editing-bg: var(--tbw-color-selection);--tbw-editing-row-bg: var(--tbw-editing-bg);--tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));--tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);--tbw-font-size-editor: inherit;--tbw-editing-row-outline-color: var(--tbw-color-accent);--tbw-editing-row-outline-width: 1px;--tbw-invalid-bg: light-dark(#fef2f2, #450a0a);--tbw-invalid-border-color: light-dark(#ef4444, #f87171)}tbw-grid:not(.tbw-grid-mode) .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:calc(var(--tbw-row-height) + 2px);align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}tbw-grid .data-grid-row>.cell[data-invalid=true]{background:var(--tbw-invalid-bg);outline:1px solid var(--tbw-invalid-border-color);outline-offset:-1px}}";get defaultConfig(){return{mode:"row",editOn:"click"}}get#Ct(){return"grid"===this.config.mode}#xt=-1;#Et;#Rt;#St=-1;#_t=new Map;#At=new Set;#kt=new Set;#Tt=new Map;#Lt=!1;#Mt=-1;#Pt=new Map;#Ht=!1;#It=!1;#Dt=!1;attach(e){super.attach(e);const t=this.disconnectSignal,i=e;i._activeEditRows=-1,i._rowEditSnapshots=new Map,Object.defineProperty(e,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(e,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),e.resetChangedRows=e=>this.resetChangedRows(e),e.beginBulkEdit=(e,t)=>{t&&this.beginCellEdit(e,t)},document.addEventListener("keydown",e=>{if(!this.#Ct&&"Escape"===e.key&&-1!==this.#xt){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}this.#zt(this.#xt,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",e=>{if(this.#Ct)return;if(-1===this.#xt)return;const t=i.findRenderedRowElement?.(this.#xt);if(!t)return;if(!(e.composedPath&&e.composedPath()||[]).includes(t)){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}queueMicrotask(()=>{-1!==this.#xt&&this.#zt(this.#xt,!1)})}},{signal:t}),this.gridElement.addEventListener("cell-change",e=>{const t=e.detail;if("user"===t.source)return;const i=`${t.rowIndex}:${t.field}`,n=this.#Tt.get(i);n&&n(t.newValue)},{signal:t}),this.#Ct&&(i._isGridEditMode=!0,this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",e=>{const t=e.target;if(t.matches(D)){if(this.#It)return t.blur(),void this.gridElement.focus();this.#Ht=!0}},{signal:t}),this.gridElement.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&this.gridElement.contains(t)&&t.matches(D)||(this.#Ht=!1)},{signal:t}),this.gridElement.addEventListener("keydown",e=>{if("Escape"===e.key&&this.#Ht){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}const t=document.activeElement;t&&this.gridElement.contains(t)&&(t.blur(),this.gridElement.focus()),this.#Ht=!1,this.#It=!0,e.preventDefault(),e.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",e=>{e.target.matches(D)&&(this.#It=!1)},{signal:t}))}detach(){this.gridElement._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#xt=-1,this.#Et=void 0,this.#Rt=void 0,this.#St=-1,this.#_t.clear(),this.#At.clear(),this.#kt.clear(),this.#Tt.clear(),this.#Ht=!1,this.#It=!1,this.#Dt=!1,super.detach()}handleQuery(e){if("isEditing"===e.type)return this.#Ct||-1!==this.#xt}onCellClick(e){if(this.#Ct)return!1;const t=this.grid,i=this.config.editOn??t.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;if("click"!==i&&"dblclick"!==i)return!1;const n="dblclick"===e.originalEvent.type;if("click"===i&&n)return!1;if("dblclick"===i&&!n)return!1;const{rowIndex:r}=e,o=t._columns?.some(e=>e.editable);return!!o&&(e.originalEvent.stopPropagation(),this.beginBulkEdit(r),!0)}onKeyDown(e){const t=this.grid;if("Escape"===e.key){if(this.#Ct&&this.#Ht){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}const t=document.activeElement;return t&&this.gridElement.contains(t)&&t.blur(),this.#Ht=!1,this.requestAfterRender(),!0}if(-1!==this.#xt&&!this.#Ct){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}return this.#zt(this.#xt,!0),!0}}if(this.#Ct&&!this.#Ht&&("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key))return!1;if(this.#Ct&&this.#Ht&&("ArrowUp"===e.key||"ArrowDown"===e.key))return!0;if(("ArrowUp"===e.key||"ArrowDown"===e.key)&&-1!==this.#xt&&!this.#Ct){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}const i=t._rows.length-1,n=this.#xt;return this.#zt(n,!1),"ArrowDown"===e.key?t._focusRow=Math.min(i,t._focusRow+1):t._focusRow=Math.max(0,t._focusRow-1),e.preventDefault(),K(t),this.requestAfterRender(),!0}if("Tab"===e.key&&(-1!==this.#xt||this.#Ct)){if(e.preventDefault(),this.#Dt)return this.#zt(this.#xt,!1),!0;const t=!e.shiftKey;return this.#Ot(t),!0}if(" "===e.key||"Spacebar"===e.key){if(-1!==this.#xt)return!1;const i=t._focusRow,n=t._focusCol;if(i>=0&&n>=0){const r=t._visibleColumns[n],o=t._rows[i];if(r?.editable&&"boolean"===r.type&&o){const t=r.field;if(Pt(t)){const n=!o[t];return this.#qt(i,r,n,o),e.preventDefault(),this.requestRender(),!0}}}return!1}if(!("Enter"!==e.key||e.shiftKey||e.ctrlKey||e.altKey||e.metaKey)){if(this.#Ct&&!this.#Ht)return this.#Ft(),!0;if(-1!==this.#xt){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}return!1}const i=this.config.editOn??t.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;const n=t._focusRow,r=t._focusCol;if(n>=0){const i=t._columns?.some(e=>e.editable);if(i){const i=t._visibleColumns[r],o=t._rows[n],s=i?.field??"",l=s&&o?o[s]:void 0,a=this.gridElement.querySelector(`[data-row="${n}"][data-col="${r}"]`),d=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:n,colIndex:r,field:s,value:l,row:o,cellEl:a,trigger:"keyboard",originalEvent:e}});this.gridElement.dispatchEvent(d);const c=new CustomEvent("activate-cell",{cancelable:!0,bubbles:!0,detail:{row:n,col:r}});return this.gridElement.dispatchEvent(c),d.defaultPrevented||c.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(n),!0)}}return!1}if("F2"===e.key){if(-1!==this.#xt||this.#Ct)return!1;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return!1;const i=t._focusRow,n=t._focusCol;if(i>=0&&n>=0){const r=t._visibleColumns[n];if(r?.editable&&r.field)return e.preventDefault(),this.beginCellEdit(i,r.field),!0}return!1}return!1}processColumns(e){const t=this.grid,i=t.effectiveConfig?.typeDefaults,n=t.__frameworkAdapter;return i||n?.getTypeDefault?e.map(e=>{if(!e.type)return e;let t;if(i?.[e.type]?.editorParams&&(t=i[e.type].editorParams),!t&&n?.getTypeDefault){const i=n.getTypeDefault(e.type);i?.editorParams&&(t=i.editorParams)}return t?{...e,editorParams:{...t,...e.editorParams}}:e}):e}afterRender(){const e=this.grid;if(this.#Lt&&(this.#Lt=!1,this.#Nt(e)),-1!==this.#Mt){const t=this.#Mt;this.#Mt=-1,e.animateRow?.(t,"change")}if(!this.#Ct&&0!==this.#kt.size)for(const t of this.#kt){const[i,n]=t.split(":"),r=parseInt(i,10),o=parseInt(n,10),s=e.findRenderedRowElement?.(r);if(!s)continue;const l=s.querySelector(`.cell[data-col="${o}"]`);if(!l||l.classList.contains("editing"))continue;const a=e._rows[r],d=e._visibleColumns[o];a&&d&&this.#Gt(a,r,d,o,l,!0)}}afterCellRender(e){if(!this.#Ct)return;const{row:t,rowIndex:i,column:n,colIndex:r,cellElement:o}=e;n.editable&&(o.classList.contains("editing")||this.#Gt(t,i,n,r,o,!0))}onScrollRender(){this.afterRender()}get changedRows(){const e=[];for(const t of this.#At){const i=this.grid.getRow(t);i&&e.push(i)}return e}get changedRowIds(){return Array.from(this.#At)}get activeEditRow(){return this.#xt}get activeEditCol(){return this.#St}isRowEditing(e){return this.#xt===e}isCellEditing(e,t){return this.#kt.has(`${e}:${t}`)}isRowChanged(e){const t=this.grid,i=t._rows[e];if(!i)return!1;try{const e=t.getRowId?.(i);return!!e&&this.#At.has(e)}catch{return!1}}isRowChangedById(e){return this.#At.has(e)}setInvalid(e,t,i=""){let n=this.#Pt.get(e);n||(n=new Map,this.#Pt.set(e,n)),n.set(t,i),this.#Vt(e,t,!0)}clearInvalid(e,t){const i=this.#Pt.get(e);i&&(i.delete(t),0===i.size&&this.#Pt.delete(e)),this.#Vt(e,t,!1)}clearRowInvalid(e){const t=this.#Pt.get(e);if(t){const i=Array.from(t.keys());this.#Pt.delete(e),i.forEach(t=>this.#Vt(e,t,!1))}}clearAllInvalid(){const e=Array.from(this.#Pt.entries());this.#Pt.clear(),e.forEach(([e,t])=>{t.forEach((t,i)=>this.#Vt(e,i,!1))})}isCellInvalid(e,t){return this.#Pt.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#Pt.get(e)?.get(t)}hasInvalidCells(e){const t=this.#Pt.get(e);return!!t&&t.size>0}getInvalidFields(e){return new Map(this.#Pt.get(e)??[])}#Vt(e,t,i){const n=this.grid,r=n._visibleColumns?.findIndex(e=>e.field===t);if(-1===r||void 0===r)return;const o=n._rows,s=o?.findIndex(t=>{try{return n.getRowId?.(t)===e}catch{return!1}});if(-1===s||void 0===s)return;const l=n.findRenderedRowElement?.(s),a=l?.querySelector(`.cell[data-col="${r}"]`);if(a)if(i){a.setAttribute("data-invalid","true");const i=this.#Pt.get(e)?.get(t);i&&a.setAttribute("title",i)}else a.removeAttribute("data-invalid"),a.removeAttribute("title")}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#At.clear(),this.#$t(),e||this.emit("changed-rows-reset",{rows:t,ids:i});const n=this.grid;n._rowPool?.forEach(e=>e.classList.remove("changed"))}beginCellEdit(e,t){const i=this.grid,n=i._visibleColumns.findIndex(e=>e.field===t);if(-1===n)return;const r=i._visibleColumns[n];if(!r?.editable)return;const o=i.findRenderedRowElement?.(e),s=o?.querySelector(`.cell[data-col="${n}"]`);s&&(this.#Dt=!0,this.#Bt(e,n,s))}beginBulkEdit(e){const t=this.grid;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return;const i=t._columns?.some(e=>e.editable);if(!i)return;const n=t.findRenderedRowElement?.(e);if(!n)return;this.#Dt=!1;const r=t._rows[e];this.#Wt(e,r),Array.from(n.children).forEach((i,n)=>{const o=t._visibleColumns[n];if(o?.editable){const t=i;t.classList.contains("editing")||this.#Gt(r,e,o,n,t,!0)}}),setTimeout(()=>{let e=n.querySelector(`.cell[data-col="${t._focusCol}"]`);if(e?.classList.contains("editing")||(e=n.querySelector(".cell.editing")),e?.classList.contains("editing")){const t=e.querySelector(D);try{t?.focus({preventScroll:!0})}catch{}}},0)}commitActiveRowEdit(){-1!==this.#xt&&this.#zt(this.#xt,!1)}cancelActiveRowEdit(){-1!==this.#xt&&this.#zt(this.#xt,!0)}#Bt(e,t,i){const n=this.grid,r=n._rows[e],o=n._visibleColumns[t];r&&o?.editable&&(i.classList.contains("editing")||(this.#xt!==e&&this.#Wt(e,r),this.#St=t,this.#Gt(r,e,o,t,i,!1)))}#Ft(){const e=this.grid,t=e._focusRow,i=e._focusCol;if(t<0||i<0)return;const n=e.findRenderedRowElement?.(t),r=n?.querySelector(`.cell[data-col="${i}"]`);if(r?.classList.contains("editing")){const e=r.querySelector(D);e&&(this.#It=!1,e.focus(),this.#Ht=!0,e instanceof HTMLInputElement&&("text"===e.type||"number"===e.type)&&e.select())}}#Ot(e){const t=this.grid,i=t._rows,n=this.#Ct?t._focusRow:this.#xt,r=t._visibleColumns.map((e,t)=>e.editable?t:-1).filter(e=>e>=0);if(0===r.length)return;const o=r.indexOf(t._focusCol)+(e?1:-1);if(o>=0&&o<r.length){t._focusCol=r[o];const e=t.findRenderedRowElement?.(n),i=e?.querySelector(`.cell[data-col="${r[o]}"]`);if(i?.classList.contains("editing")){const e=i.querySelector(D);e?.focus({preventScroll:!0})}return void K(t,{forceHorizontalScroll:!0})}const s=n+(e?1:-1);s>=0&&s<i.length&&(this.#Ct?(t._focusRow=s,t._focusCol=e?r[0]:r[r.length-1],K(t,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const e=t.findRenderedRowElement?.(s),i=e?.querySelector(`.cell[data-col="${t._focusCol}"]`);if(i?.classList.contains("editing")){const e=i.querySelector(D);e?.focus({preventScroll:!0})}},0)):(this.#zt(n,!1),t._focusRow=s,t._focusCol=e?r[0]:r[r.length-1],this.beginBulkEdit(s),K(t,{forceHorizontalScroll:!0})))}#$t(){const e=this.grid;e._activeEditRows=this.#xt,e._rowEditSnapshots=this.#_t}#Wt(e,t){if(this.#xt!==e){this.#_t.set(e,{...t}),this.#xt=e,this.#Rt=t;const i=this.grid;try{this.#Et=i.getRowId?.(t)??void 0}catch{this.#Et=void 0}this.#$t(),this.#Ct||this.emit("edit-open",{rowIndex:e,rowId:this.#Et??"",row:t})}}#zt(e,t){if(this.#xt!==e)return;const i=this.grid,n=this.#_t.get(e),r=i.findRenderedRowElement?.(e);let o=this.#Et;const s=o?i._getRowEntry(o):void 0,l=s?.row??this.#Rt??i._rows[e];if(!o&&l)try{o=i.getRowId?.(l)}catch{}if(!t&&r&&l){r.querySelectorAll(".cell.editing").forEach(t=>{const n=Number(t.getAttribute("data-col"));if(isNaN(n))return;const r=i._visibleColumns[n];if(!r)return;if(t.hasAttribute("data-editor-managed"))return;const o=t.querySelector("input,textarea,select");if(o){const t=r.field,i=l[t],n=Ht(o,r,i);i!==n&&this.#qt(e,r,n,l)}})}if(t||this.#Ct||!l||this.emit("before-edit-close",{rowIndex:e,rowId:o??"",row:l}),t&&n&&l)Object.keys(n).forEach(e=>{l[e]=n[e]}),o&&(this.#At.delete(o),this.clearRowInvalid(o));else if(!t&&l){const t=this.#Kt(n,l),i=o?this.#At.has(o):t,r=this.emitCancelable("row-commit",{rowIndex:e,rowId:o??"",row:l,oldValue:n,newValue:l,changed:i,changedRows:this.changedRows,changedRowIds:this.changedRowIds});r&&n?(Object.keys(n).forEach(e=>{l[e]=n[e]}),o&&(this.#At.delete(o),this.clearRowInvalid(o))):!r&&t&&this.isAnimationEnabled&&(this.#Mt=e)}this.#_t.delete(e),this.#xt=-1,this.#Et=void 0,this.#Rt=void 0,this.#St=-1,this.#Dt=!1,this.#$t();for(const a of this.#kt)a.startsWith(`${e}:`)&&this.#kt.delete(a);for(const a of this.#Tt.keys())a.startsWith(`${e}:`)&&this.#Tt.delete(a);this.#Lt=!0,r?(r.querySelectorAll(".cell.editing").forEach(e=>{e.classList.remove("editing"),function(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing")}(e.parentElement)}),i.refreshVirtualWindow(!0)):(this.#Nt(i),this.#Lt=!1),!this.#Ct&&l&&this.emit("edit-close",{rowIndex:e,rowId:o??"",row:l,reverted:t})}#qt(e,t,i,n){const r=t.field;if(!Pt(r))return;const o=n[r];if(o===i)return;const s=this.grid;let l;try{l=this.grid.getRowId(n)}catch{}const a=!l||!this.#At.has(l),d=l?e=>this.grid.updateRow(l,e,"cascade"):It;let c=!1;const h=l?e=>{c=!0,this.setInvalid(l,r,e??"")}:()=>{};if(this.emitCancelable("cell-commit",{row:n,rowId:l??"",field:r,oldValue:o,value:i,rowIndex:e,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:a,updateRow:d,setInvalid:h}))return;l&&!c&&this.isCellInvalid(l,r)&&this.clearInvalid(l,r),n[r]=i,l&&this.#At.add(l),this.#$t(),this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:r,oldValue:o,newValue:i});const u=s.findRenderedRowElement?.(e);u&&u.classList.add("changed")}#Gt(e,t,i,n,r,o){if(!i.editable)return;if(r.classList.contains("editing"))return;let s;try{s=this.grid.getRowId(e)}catch{}const l=s?e=>this.grid.updateRow(s,e,"cascade"):It,a=Pt(i.field)?e[i.field]:void 0;r.classList.add("editing"),this.#kt.add(`${t}:${n}`);const d=r.parentElement;d&&function(e){const t=(e.__editingCellCount??0)+1;e.__editingCellCount=t,e.setAttribute("data-has-editing","")}(d);let c=!1;const h=n=>{if(c||!this.#Ct&&-1===this.#xt)return;const r=this.grid,o=s?r._getRowEntry(s):void 0,l=o?.row??e,a=o?.index??t;this.#qt(a,i,n,l)},u=()=>{if(c=!0,Pt(i.field)){const t=this.grid,n=s?t._getRowEntry(s):void 0;(n?.row??e)[i.field]=a}},g=document.createElement("div");g.className="tbw-editor-host",r.innerHTML="",r.appendChild(g),g.addEventListener("keydown",e=>{if("Enter"===e.key){if(this.#Ct){e.stopPropagation(),e.preventDefault();const t=g.querySelector("input,textarea,select");return void(t&&h(Ht(t,i,a)))}if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}e.stopPropagation(),e.preventDefault(),c=!0,this.#zt(t,!1)}if("Escape"===e.key){if(this.#Ct)return e.stopPropagation(),void e.preventDefault();if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}e.stopPropagation(),e.preventDefault(),u(),this.#zt(t,!0)}});const p=i,f=p.__editorTemplate,w=function(e,t){if(t.editor)return t.editor;if(t.__editorTemplate)return"template";if(!t.type)return;const i=e.effectiveConfig?.typeDefaults;if(i?.[t.type]?.editor)return i[t.type].editor;const n=e.__frameworkAdapter;if(n?.getTypeDefault){const e=n.getTypeDefault(t.type);if(e?.editor)return e.editor}}(this.grid,p)??Mt(i),m=a,b=`${t}:${i.field}`,v=[];this.#Tt.set(b,e=>{for(const t of v)t(e)});const y=e=>{v.push(e)};if("template"===w&&f)this.#Ut(g,p,e,a,h,u,o,t),y(e=>{const t=g.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if("string"==typeof w){const e=document.createElement(w);e.value=m,e.addEventListener("change",()=>h(e.value)),y(t=>{e.value=t}),g.appendChild(e),o||queueMicrotask(()=>{const e=g.querySelector(D);e?.focus({preventScroll:!0})})}else if("function"==typeof w){const t=w({row:e,rowId:s??"",value:m,field:i.field,column:i,commit:h,cancel:u,updateRow:l,onValueChange:y});if("string"==typeof t)g.innerHTML=t,function(e,t,i,n){const r=e.querySelector("input,textarea,select");r&&(r.addEventListener("blur",()=>{i(Ht(r,t,n))}),r instanceof HTMLInputElement&&"checkbox"===r.type?r.addEventListener("change",()=>i(r.checked)):r instanceof HTMLSelectElement&&r.addEventListener("change",()=>i(Ht(r,t,n))))}(g,i,h,a),y(e=>{const t=g.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if(t instanceof Node){g.appendChild(t);t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?y(e=>{t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??"")}):r.setAttribute("data-editor-managed","")}o||queueMicrotask(()=>{const e=g.querySelector(D);e?.focus({preventScroll:!0})})}else if(w&&"object"==typeof w){const t=document.createElement("div");t.setAttribute("data-external-editor",""),t.setAttribute("data-field",i.field),g.appendChild(t),r.setAttribute("data-editor-managed","");const n={row:e,rowId:s??"",value:m,field:i.field,column:i,commit:h,cancel:u,updateRow:l,onValueChange:y};if(w.mount)try{w.mount({placeholder:t,context:n,spec:w})}catch(C){console.warn(`[tbw-grid] External editor mount error for column '${i.field}':`,C)}else this.grid.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:t,spec:w,context:n}}))}}#Ut(e,t,i,n,r,o,s,l){const a=t.__editorTemplate;if(!a)return;const d=a.cloneNode(!0),c=t.__compiledEditor;c?d.innerHTML=c({row:i,value:n,field:t.field,column:t,commit:r,cancel:o}):d.querySelectorAll("*").forEach(e=>{1===e.childNodes.length&&e.firstChild?.nodeType===Node.TEXT_NODE&&(e.textContent=e.textContent?.replace(/{{\s*value\s*}}/g,null==n?"":String(n)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(e,t)=>{if(!Pt(t))return"";const n=i[t];return null==n?"":String(n)})||"")});const h=d.querySelector("input,textarea,select");if(h){h instanceof HTMLInputElement&&"checkbox"===h.type?h.checked=!!n:h.value=String(n??"");let e=!1;h.addEventListener("blur",()=>{e||r(Ht(h,t,n))}),h.addEventListener("keydown",i=>{const s=i;if("Enter"===s.key){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(s))return}s.stopPropagation(),s.preventDefault(),e=!0,r(Ht(h,t,n)),this.#zt(l,!1)}if("Escape"===s.key){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(s))return}s.stopPropagation(),s.preventDefault(),o(),this.#zt(l,!0)}}),h instanceof HTMLInputElement&&"checkbox"===h.type&&h.addEventListener("change",()=>r(h.checked)),s||setTimeout(()=>h.focus({preventScroll:!0}),0)}e.appendChild(d)}#Kt(e,t){if(!e)return!1;const i=e,n=t,r=new Set([...Object.keys(i),...Object.keys(n)]);for(const o of r)if(i[o]!==n[o])return!0;return!1}#Nt(e){queueMicrotask(()=>{try{const t=e._focusRow,i=e._focusCol,n=e.findRenderedRowElement?.(t);if(n){Array.from(e._bodyEl.querySelectorAll(".cell-focus")).forEach(e=>e.classList.remove("cell-focus"));const r=n.querySelector(`.cell[data-row="${t}"][data-col="${i}"]`);r&&(r.classList.add("cell-focus"),r.setAttribute("aria-selected","true"),r.hasAttribute("tabindex")||r.setAttribute("tabindex","-1"),r.focus({preventScroll:!0}))}}catch{}})}},e.ExportPlugin=class extends rt{name="export";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;performExport(e,t){const i=this.config,n={format:e,fileName:t?.fileName??i.fileName??"export",includeHeaders:t?.includeHeaders??i.includeHeaders,processCell:t?.processCell,processHeader:t?.processHeader,columns:t?.columns,rowIndices:t?.rowIndices},r=at(this.columns,t?.columns,i.onlyVisible);let o;if(t?.rowIndices)o=dt(this.rows,t.rowIndices);else if(i.onlySelected){const e=this.getSelectionState();o=e?.selected?.size?dt(this.rows,[...e.selected]):[...this.rows]}else o=[...this.rows];this.isExportingFlag=!0;let s=n.fileName;try{switch(e){case"csv":{const e=function(e,t,i,n={}){const r=n.delimiter??",",o=n.newline??"\n",s=[],l=n.bom?"\ufeff":"";if(!1!==i.includeHeaders){const e=t.map(e=>{const t=e.header||e.field;return Dt(i.processHeader?i.processHeader(t,e.field):t)});s.push(e.join(r))}for(const a of e){const e=t.map(e=>{let t=a[e.field];return i.processCell&&(t=i.processCell(t,e.field,a)),Dt(t)});s.push(e.join(r))}return l+s.join(o)}(o,r,n,{bom:!0});s=s.endsWith(".csv")?s:`${s}.csv`,function(e,t){zt(new Blob([e],{type:"text/csv;charset=utf-8;"}),t)}(e,s);break}case"excel":{const e=function(e,t,i){let n='<?xml version="1.0" encoding="UTF-8"?>\n<?mso-application progid="Excel.Sheet"?>\n<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"\n xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">\n<Worksheet ss:Name="Sheet1">\n<Table>';if(!1!==i.includeHeaders){n+="\n<Row>";for(const e of t){const t=e.header||e.field;n+=`<Cell><Data ss:Type="String">${Ot(i.processHeader?i.processHeader(t,e.field):t)}</Data></Cell>`}n+="</Row>"}for(const r of e){n+="\n<Row>";for(const e of t){let t=r[e.field];i.processCell&&(t=i.processCell(t,e.field,r));let o="String",s="";null==t?s="":"number"!=typeof t||isNaN(t)?t instanceof Date?(o="DateTime",s=t.toISOString()):s=Ot(String(t)):(o="Number",s=String(t)),n+=`<Cell><Data ss:Type="${o}">${s}</Data></Cell>`}n+="</Row>"}return n+="\n</Table>\n</Worksheet>\n</Workbook>",n}(o,r,n);s=s.endsWith(".xls")?s:`${s}.xls`,function(e,t){const i=t.endsWith(".xls")?t:`${t}.xls`;zt(new Blob([e],{type:"application/vnd.ms-excel;charset=utf-8;"}),i)}(e,s);break}case"json":{const e=o.map(e=>{const t={};for(const i of r){let r=e[i.field];n.processCell&&(r=n.processCell(r,i.field,e)),t[i.field]=r}return t}),t=JSON.stringify(e,null,2);s=s.endsWith(".json")?s:`${s}.json`;zt(new Blob([t],{type:"application/json"}),s);break}}this.lastExportInfo={format:e,timestamp:new Date},this.emit("export-complete",{format:e,fileName:s,rowCount:o.length,columnCount:r.length})}finally{this.isExportingFlag=!1}}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}exportCsv(e){this.performExport("csv",e)}exportExcel(e){this.performExport("excel",e)}exportJson(e){this.performExport("json",e)}isExporting(){return this.isExportingFlag}getLastExport(){return this.lastExportInfo}},e.FilteringPlugin=Kt,e.FitModeEnum=t,e.GridCSSVars={COLOR_BG:"--tbw-color-bg",COLOR_FG:"--tbw-color-fg",COLOR_FG_MUTED:"--tbw-color-fg-muted",COLOR_BORDER:"--tbw-color-border",COLOR_ACCENT:"--tbw-color-accent",COLOR_HEADER_BG:"--tbw-color-header-bg",COLOR_HEADER_FG:"--tbw-color-header-fg",COLOR_SELECTION:"--tbw-color-selection",COLOR_ROW_HOVER:"--tbw-color-row-hover",COLOR_ROW_ALT:"--tbw-color-row-alt",ROW_HEIGHT:"--tbw-row-height",HEADER_HEIGHT:"--tbw-header-height",CELL_PADDING:"--tbw-cell-padding",FONT_FAMILY:"--tbw-font-family",FONT_SIZE:"--tbw-font-size",BORDER_RADIUS:"--tbw-border-radius",FOCUS_OUTLINE:"--tbw-focus-outline"},e.GridClasses=ot,e.GridDataAttrs=st,e.GridElement=nt,e.GridSelectors=lt,e.GroupingColumnsPlugin=class extends rt{static manifest={ownedProperties:[{property:"group",level:"column",description:'the "group" column property'},{property:"columnGroups",level:"config",description:'the "columnGroups" config property',isUsed:e=>Array.isArray(e)&&e.length>0}],queries:[{type:"getColumnGrouping",description:"Returns column group metadata for the visibility panel"}]};name="groupingColumns";styles="@layer tbw-plugins{.header-group-row{display:grid;grid-auto-flow:column;background:var(--tbw-grouping-columns-header-bg, var(--tbw-color-header-bg));border-bottom:1px solid var(--tbw-grouping-columns-border, var(--tbw-color-border))}.header-group-cell{display:flex;align-items:center;justify-content:center;padding:var(--tbw-button-padding-sm, .25rem .5rem);font-weight:600;font-size:var(--tbw-font-size-sm, .9em);text-transform:uppercase;letter-spacing:.5px;border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.header-group-cell:last-child{border-right:none}.header-row .cell.grouped{border-top:none}.header-row .cell.group-end{border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.header-row .cell.group-end:last-child{border-right:none}.rows .cell.group-end{border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.rows .cell.group-end:last-child{border-right:none}.header-group-row.no-borders{border-bottom:none}.header-group-row.no-borders .header-group-cell{border-right:none}.header-row.no-group-borders .cell.group-end{border-right:1px solid var(--tbw-color-border)}}";get defaultConfig(){return{showGroupBorders:!0,lockGroupOrder:!1}}groups=[];isActive=!1;#jt=new Set;attach(e){super.attach(e),e.addEventListener("column-move",this.#Yt,{signal:this.disconnectSignal})}detach(){this.groups=[],this.isActive=!1,this.#jt.clear()}#Yt=e=>{if(!this.isActive)return;const t=e,{field:i,columnOrder:n}=t.detail;if(this.config.lockGroupOrder)for(const r of this.groups)if(!r.id.startsWith("__implicit__")&&!this.#Xt(r,n))return t.preventDefault(),void this.#Zt(i);this.#Qt(n)};#Qt(e){this.#jt.clear();const t=this.#Jt(e);for(const i of this.groups){const n=new Set(i.columns.map(e=>e.field));for(let i=e.length-1;i>=0;i--)if(n.has(e[i])){const n=e[i];n!==t&&this.#jt.add(n);break}}}#Jt(e){if(0===this.groups.length)return null;for(let t=e.length-1;t>=0;t--){const i=e[t];for(const t of this.groups)if(t.columns.some(e=>e.field===i)){const i=new Set(t.columns.map(e=>e.field));for(let t=e.length-1;t>=0;t--)if(i.has(e[t]))return e[t]}}return null}#Xt(e,t){const i=e.columns.map(e=>t.indexOf(e.field)).filter(e=>-1!==e).sort((e,t)=>e-t);return i.length<=1||i.length===i[i.length-1]-i[0]+1}#Zt(e){const t=this.gridElement?.querySelector(`.header-row [part~="header-cell"][data-field="${e}"]`);t&&(t.style.setProperty("--_flash-color","var(--tbw-color-error)"),t.animate([{backgroundColor:"rgba(from var(--_flash-color) r g b / 30%)"},{backgroundColor:"transparent"}],{duration:400,easing:"ease-out"}))}handleQuery(e){if("getColumnGrouping"===e.type)return this.#ei()}#ei(){let e;const t=this.grid?.gridConfig?.columnGroups;if(t&&Array.isArray(t)&&t.length>0)e=t.filter(e=>e.children.length>0).map(e=>({id:e.id,label:e.header,fields:[...e.children]}));else if(this.isActive&&this.groups.length>0){e=this.groups.filter(e=>!e.id.startsWith("__implicit__")).map(e=>({id:e.id,label:e.label??e.id,fields:e.columns.map(e=>e.field)}));const t=this.columns;for(const i of t)if(i.hidden&&i.group){const t="string"==typeof i.group?i.group:i.group.id,n="string"==typeof i.group?i.group:i.group.label??i.group.id,r=e.find(e=>e.id===t);r?r.fields.includes(i.field)||r.fields.push(i.field):e.push({id:t,label:n,fields:[i.field]})}}else{const t=this.columns,i=new Map;for(const e of t){if(!e.group)continue;const t="string"==typeof e.group?e.group:e.group.id,n="string"==typeof e.group?e.group:e.group.label??e.group.id,r=i.get(t);r?r.fields.includes(e.field)||r.fields.push(e.field):i.set(t,{id:t,label:n,fields:[e.field]})}e=Array.from(i.values())}const i=this.grid?.getColumnOrder();if(i&&i.length>0){const t=new Map(i.map((e,t)=>[e,t]));for(const i of e)i.fields.sort((e,i)=>(t.get(e)??1/0)-(t.get(i)??1/0))}return e}static detect(e,t){if(t?.columnGroups&&Array.isArray(t.columnGroups)&&t.columnGroups.length>0)return!0;const i=t?.columns;return!!Array.isArray(i)&&function(e){return e.some(e=>null!=e.group)}(i)}processColumns(e){const t=this.grid?.gridConfig?.columnGroups;let i;if(t&&Array.isArray(t)&&t.length>0){const n=new Map;for(const e of t)for(const t of e.children)n.set(t,{id:e.id,label:e.header});i=e.map(e=>{const t=n.get(e.field);return t&&!e.group?{...e,group:t}:e})}else i=[...e];const n=Ut(i);if(0===n.length)return this.isActive=!1,this.groups=[],i;this.isActive=!0,this.groups=n,this.#jt.clear();for(const r of n){const e=r.columns[r.columns.length-1];e?.field&&this.#jt.add(e.field)}return i}afterRender(){if(!this.isActive){const e=this.gridElement?.querySelector(".header"),t=e?.querySelector(".header-group-row");return void(t&&t.remove())}const e=this.gridElement?.querySelector(".header");if(!e)return;const t=e.querySelector(".header-group-row");t&&t.remove();const i=this.visibleColumns,n=Ut(i);if(0===n.length)return;this.#jt.clear();for(let s=0;s<n.length;s++){const e=n[s],t=e.columns[e.columns.length-1];t?.field&&s<n.length-1&&this.#jt.add(t.field)}const r=function(e,t){if(0===e.length)return null;const i=document.createElement("div");i.className="header-group-row",i.setAttribute("role","row");for(const n of e){const e=n.columns[0],r=e?t.findIndex(t=>t.field===e.field):-1;if(-1===r)continue;const o=String(n.id).startsWith("__implicit__"),s=o?"":n.label||n.id,l=document.createElement("div");l.className="cell header-group-cell",o&&l.classList.add("implicit-group"),l.setAttribute("data-group",String(n.id)),l.style.gridColumn=`${r+1} / span ${n.columns.length}`,l.textContent=s,i.appendChild(l)}return i}(n,i);if(r){r.classList.toggle("no-borders",!this.config.showGroupBorders);const t=e.querySelector(".header-row");t?e.insertBefore(r,t):e.appendChild(r)}const o=e.querySelector(".header-row");o&&(o.classList.toggle("no-group-borders",!this.config.showGroupBorders),function(e,t){if(!t.length||!e)return;const i=new Map;for(const r of t)for(const e of r.columns)e.field&&i.set(e.field,r.id);const n=Array.from(e.querySelectorAll(".cell[data-field]"));n.forEach(e=>{const t=e.getAttribute("data-field")||"",n=i.get(t);n&&(e.classList.add("grouped"),e.getAttribute("data-group")||e.setAttribute("data-group",n))});for(const r of t){const e=r.columns[r.columns.length-1],t=n.find(t=>t.getAttribute("data-field")===e.field);t&&t.classList.add("group-end")}}(o,n))}afterCellRender(e){this.isActive&&this.config.showGroupBorders&&e.cellElement.classList.toggle("group-end",this.#jt.has(e.column.field))}isGroupingActive(){return this.isActive}getGroups(){return this.groups}getGroupColumns(e){const t=this.groups.find(t=>t.id===e);return t?t.columns:[]}refresh(){this.requestRender()}},e.GroupingRowsPlugin=class extends rt{static manifest={events:[{type:"grouping-state-change",description:"Emitted when groups are expanded/collapsed. Subscribers can react to row visibility changes."}],queries:[{type:"canMoveRow",description:"Returns false for group header rows (cannot be reordered)"}],configRules:[{id:"groupingRows/accordion-defaultExpanded",severity:"warn",message:'"accordion: true" and "defaultExpanded" (non-false) are used together.\n → In accordion mode, only one group can be open at a time.\n → Using defaultExpanded with multiple groups will collapse to one on first toggle.\n → Consider using "defaultExpanded: false" or a single group key/index with accordion mode.',check:e=>!0===e.accordion&&!1!==e.defaultExpanded&&void 0!==e.defaultExpanded&&!("number"==typeof e.defaultExpanded)&&!("string"==typeof e.defaultExpanded)&&(!0===e.defaultExpanded||Array.isArray(e.defaultExpanded)&&e.defaultExpanded.length>1)}]};name="groupingRows";styles="@layer tbw-plugins{.group-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-grouping-rows-bg, var(--tbw-color-panel-bg));font-weight:500;border-bottom:var(--tbw-row-divider);min-height:var(--tbw-row-height)}.group-row .cell{display:flex;align-items:center;padding:var(--tbw-cell-padding, .125rem .5rem)}.group-row:hover{background:var(--tbw-grouping-rows-bg-hover, var(--tbw-color-row-hover))}.group-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-toggle-size, 1.25rem);height:var(--tbw-toggle-size, 1.25rem);margin-right:.25rem;background:none;border:0;font:inherit}.group-toggle:hover{background:var(--tbw-grouping-rows-toggle-hover, var(--tbw-color-row-hover));border-radius:var(--tbw-border-radius, .125rem)}.group-label{display:inline-flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.group-count{color:var(--tbw-grouping-rows-count-color, var(--tbw-color-fg-muted));font-size:var(--tbw-font-size-xs, .85em);font-weight:400}.group-aggregates{display:inline-flex;align-items:center;gap:var(--tbw-spacing-lg, 1rem);margin-left:var(--tbw-spacing-lg, 1rem);font-weight:400;font-size:var(--tbw-font-size-sm, .875em);color:var(--tbw-grouping-rows-aggregate-color, var(--tbw-color-fg-muted))}.group-aggregate{white-space:nowrap}.group-row{padding-left:calc(var(--tbw-group-depth, 0) * var(--tbw-group-indent-width, 1.25em))}.data-grid-row.tbw-group-slide-in{animation:tbw-group-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.data-grid-row.tbw-group-fade-in{animation:tbw-group-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-fade-in{0%{opacity:0}to{opacity:1}}}";get defaultConfig(){return{defaultExpanded:!1,showRowCount:!0,indentWidth:20,aggregators:{},animation:"slide",accordion:!1}}expandedKeys=new Set;flattenedRows=[];isActive=!1;previousVisibleKeys=new Set;keysToAnimate=new Set;hasAppliedDefaultExpanded=!1;get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detach(){this.expandedKeys.clear(),this.flattenedRows=[],this.isActive=!1,this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.hasAppliedDefaultExpanded=!1}getRowHeight(e,t){if(null!=this.config.groupRowHeight)return!0===e.__isGroupRow?this.config.groupRowHeight:void 0}handleQuery(e){if("canMoveRow"===e.type){const t=e.context;if(!0===t?.__isGroupRow)return!1}}static detect(e,t){return"function"==typeof t?.groupOn||"boolean"==typeof t?.enableRowGrouping}processRows(e){const t=this.config;if("function"!=typeof t.groupOn)return this.isActive=!1,this.flattenedRows=[],[...e];const i=ei({rows:[...e],config:t,expanded:new Set});if(0===i.length)return this.isActive=!1,this.flattenedRows=[],[...e];let n;if(!this.hasAppliedDefaultExpanded&&0===this.expandedKeys.size&&!1!==t.defaultExpanded){const e=function(e){return e.filter(e=>"group"===e.kind).map(e=>e.key)}(i);n=function(e,t){if(!0===e)return new Set(t);if(!1===e||null==e)return new Set;if("number"==typeof e){const i=t[e];return i?new Set([i]):new Set}return"string"==typeof e?new Set([e]):Array.isArray(e)?new Set(e):new Set}(t.defaultExpanded??!1,e),n.size>0&&(this.expandedKeys=new Set(n),this.hasAppliedDefaultExpanded=!0)}const r=ei({rows:[...e],config:t,expanded:this.expandedKeys,initialExpanded:n});this.isActive=!0,this.flattenedRows=r,this.keysToAnimate.clear();const o=new Set;return r.forEach((e,t)=>{if("data"===e.kind){const e=`data-${t}`;o.add(e),this.previousVisibleKeys.has(e)||this.keysToAnimate.add(e)}}),this.previousVisibleKeys=o,r.map(e=>{return"group"===e.kind?{__isGroupRow:!0,__groupKey:e.key,__groupValue:e.value,__groupDepth:e.depth,__groupRows:e.rows,__groupExpanded:e.expanded,__groupRowCount:(t=e,"group"!==t.kind?0:t.rows.length),__rowCacheKey:`group:${e.key}`}:e.row;var t})}onCellClick(e){const t=e.row;if(t?.__isGroupRow){const i=e.originalEvent.target;if(i?.closest(".group-toggle"))return this.toggle(t.__groupKey),!0}}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusRow,i=this.rows[t];return i?.__isGroupRow?(e.preventDefault(),this.toggle(i.__groupKey),this.requestRenderWithFocus(),!0):void 0}renderRow(e,t,i){if(!e?.__isGroupRow)return!1;const n=this.config;if(n.groupRowRenderer){const i=()=>{this.toggle(e.__groupKey)},r=n.groupRowRenderer({key:e.__groupKey,value:e.__groupValue,depth:e.__groupDepth,rows:e.__groupRows,expanded:e.__groupExpanded,toggleExpand:i});if(r)return t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),"string"==typeof r?t.innerHTML=r:(t.innerHTML="",t.appendChild(r)),!0}const r=()=>{this.toggle(e.__groupKey)};t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),t.setAttribute("role","row"),t.setAttribute("aria-expanded",String(e.__groupExpanded)),t.style.setProperty("--tbw-group-depth",String(e.__groupDepth||0)),void 0!==n.indentWidth&&t.style.setProperty("--tbw-group-indent-width",`${n.indentWidth}px`),t.style.height="",t.innerHTML="";return!1!==n.fullWidth?this.renderFullWidthGroupRow(e,t,r):this.renderPerColumnGroupRow(e,t,r),!0}afterRender(){const e=this.animationStyle;if(!1===e||0===this.keysToAnimate.size)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const i="fade"===e?"tbw-group-fade-in":"tbw-group-slide-in";for(const n of t.querySelectorAll(".data-grid-row:not(.group-row)")){const e=n.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,r=this.flattenedRows[t],o="data"===r?.kind?`data-${t}`:void 0;o&&this.keysToAnimate.has(o)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}createToggleButton(e,t){const i=document.createElement("button");return i.type="button",i.className="group-toggle"+(e?" expanded":""),i.setAttribute("aria-label",e?"Collapse group":"Expand group"),this.setIcon(i,this.resolveIcon(e?"collapse":"expand")),i.addEventListener("click",e=>{e.stopPropagation(),t()}),i}getGroupLabelText(e,t,i){const n=this.config;return n.formatLabel?n.formatLabel(e,t,i):String(e)}renderFullWidthGroupRow(e,t,i){const n=this.config,r=n.aggregators??{},o=e.__groupRows??[],s=document.createElement("div");s.className="cell group-full",s.style.gridColumn="1 / -1",s.setAttribute("role","gridcell"),s.setAttribute("data-col","0"),s.appendChild(this.createToggleButton(e.__groupExpanded,i));const l=document.createElement("span");if(l.className="group-label",l.textContent=this.getGroupLabelText(e.__groupValue,e.__groupDepth||0,e.__groupKey),s.appendChild(l),!1!==n.showRowCount){const t=document.createElement("span");t.className="group-count",t.textContent=`(${e.__groupRowCount??e.__groupRows?.length??0})`,s.appendChild(t)}const a=Object.entries(r);if(a.length>0){const e=document.createElement("span");e.className="group-aggregates";for(const[t,i]of a){const n=this.columns.find(e=>e.field===t),r=Jt(i,o,t,n);if(null!=r){const i=document.createElement("span");i.className="group-aggregate",i.setAttribute("data-field",t);const o=n?.header??t;i.textContent=`${o}: ${r}`,e.appendChild(i)}}e.children.length>0&&s.appendChild(e)}t.appendChild(s)}renderPerColumnGroupRow(e,t,i){const n=this.config,r=n.aggregators??{},o=this.columns,s=e.__groupRows??[],l=this.gridElement?.querySelector(".body"),a=l?.style.gridTemplateColumns||"";a&&(t.style.display="grid",t.style.gridTemplateColumns=a);let d=!1;o.forEach((o,l)=>{const a=document.createElement("div");if(a.className="cell group-cell",a.setAttribute("data-col",String(l)),a.setAttribute("role","gridcell"),Bt(o))return a.setAttribute("data-field",o.field),void t.appendChild(a);if(d){const e=r[o.field];if(e){const t=Jt(e,s,o.field,o);a.textContent=null!=t?String(t):""}else a.textContent=""}else{d=!0,a.appendChild(this.createToggleButton(e.__groupExpanded,i));const t=document.createElement("span"),l=r[o.field];if(l){const i=Jt(l,s,o.field,o);t.textContent=String(null!=i?i:e.__groupValue)}else t.textContent=this.getGroupLabelText(e.__groupValue,e.__groupDepth||0,e.__groupKey);if(a.appendChild(t),!1!==n.showRowCount){const e=document.createElement("span");e.className="group-count",e.textContent=` (${s.length})`,a.appendChild(e)}}t.appendChild(a)})}expandAll(){this.expandedKeys=function(e){const t=new Set;for(const i of e)"group"===i.kind&&t.add(i.key);return t}(this.flattenedRows),this.emitPluginEvent("grouping-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("grouping-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}toggle(e){const t=!this.expandedKeys.has(e),i=this.config,n=this.flattenedRows.find(t=>"group"===t.kind&&t.key===e);if(i.accordion&&t&&n){const t=new Set;for(const i of this.expandedKeys)if(e.startsWith(i+"||")||i.startsWith(e+"||"))e.startsWith(i+"||")&&t.add(i);else{const e=this.flattenedRows.find(e=>"group"===e.kind&&e.key===i);e&&e.depth!==n.depth&&t.add(i)}t.add(e),this.expandedKeys=t}else this.expandedKeys=function(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}(this.expandedKeys,e);this.emit("group-toggle",{key:e,expanded:this.expandedKeys.has(e),value:n?.value,depth:n?.depth??0}),this.emitPluginEvent("grouping-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}expand(e){this.expandedKeys.has(e)||(this.expandedKeys=new Set([...this.expandedKeys,e]),this.requestRender())}collapse(e){if(this.expandedKeys.has(e)){const t=new Set(this.expandedKeys);t.delete(e),this.expandedKeys=t,this.requestRender()}}getGroupState(){const e=this.flattenedRows.filter(e=>"group"===e.kind);return{isActive:this.isActive,expandedCount:this.expandedKeys.size,totalGroups:e.length,expandedKeys:[...this.expandedKeys]}}getRowCount(){return this.flattenedRows.length}refreshGroups(){this.requestRender()}getExpandedGroups(){return[...this.expandedKeys]}getFlattenedRows(){return this.flattenedRows}isGroupingActive(){return this.isActive}setGroupOn(e){this.config.groupOn=e,this.requestRender()}},e.MasterDetailPlugin=ni,e.MultiSortPlugin=class extends rt{name="multiSort";styles='@layer tbw-plugins{.header-cell[data-sort=asc]:after{content:"↑";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.header-cell[data-sort=desc]:after{content:"↓";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-indicator{margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-index{font-size:var(--tbw-font-size-2xs, .7em);background:var(--tbw-multi-sort-badge-bg, var(--tbw-color-panel-bg));color:var(--tbw-multi-sort-badge-color, var(--tbw-color-fg));border-radius:50%;width:var(--tbw-multi-sort-badge-size, 1em);height:var(--tbw-multi-sort-badge-size, 1em);display:inline-flex;align-items:center;justify-content:center;margin-left:var(--tbw-spacing-xs, .125em);font-weight:600}}';get defaultConfig(){return{maxSortColumns:3,showSortIndex:!0}}sortModel=[];cachedSortResult=null;clearCoreSortState(){const e=this.gridElement;e&&(e._sortState=null)}detach(){this.sortModel=[],this.cachedSortResult=null}processRows(e){if(0===this.sortModel.length)return this.cachedSortResult=null,[...e];const t=this.gridElement;if(t&&!t._isGridEditMode&&"number"==typeof t._activeEditRows&&-1!==t._activeEditRows&&this.cachedSortResult&&this.cachedSortResult.length===e.length)return[...this.cachedSortResult];const i=function(e,t,i){return t.length?[...e].sort((e,n)=>{for(const r of t){const t=i.find(e=>e.field===r.field),o=(t?.sortComparator??ri)(e[r.field],n[r.field],e,n);if(0!==o)return"asc"===r.direction?o:-o}return 0}):[...e]}([...e],this.sortModel,[...this.columns]);return this.cachedSortResult=i,i}onHeaderClick(e){const t=this.columns.find(t=>t.field===e.field);if(!t?.sortable)return!1;const i=e.originalEvent.shiftKey,n=this.config.maxSortColumns??3;return this.sortModel=function(e,t,i,n){const r=e.find(e=>e.field===t);return i?r?"asc"===r.direction?e.map(e=>e.field===t?{...e,direction:"desc"}:e):e.filter(e=>e.field!==t):e.length<n?[...e,{field:t,direction:"asc"}]:e:"asc"===r?.direction?[{field:t,direction:"desc"}]:"desc"===r?.direction?[]:[{field:t,direction:"asc"}]}(this.sortModel,e.field,i,n),this.clearCoreSortState(),this.emit("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),this.grid?.requestStateChange?.(),!0}afterRender(){const e=this.gridElement;if(!e)return;const t=!1!==this.config.showSortIndex;e.querySelectorAll(".header-row .cell[data-field]").forEach(e=>{const i=e.getAttribute("data-field");if(!i)return;const n=oi(this.sortModel,i),r=si(this.sortModel,i),o=e.querySelector(".sort-index");if(o?.remove(),r){const i=e.querySelector('[part~="sort-indicator"], .sort-indicator');i?.remove(),e.setAttribute("data-sort",r);const o=document.createElement("span");o.className="sort-indicator",this.setIcon(o,this.resolveIcon("asc"===r?"sortAsc":"sortDesc"));const s=e.querySelector(".tbw-filter-btn"),l=e.querySelector(".resize-handle"),a=s??l;if(a?e.insertBefore(o,a):e.appendChild(o),t&&this.sortModel.length>1&&void 0!==n){const t=document.createElement("span");t.className="sort-index",t.textContent=String(n),o.nextSibling?e.insertBefore(t,o.nextSibling):e.appendChild(t)}}else{e.removeAttribute("data-sort");const t=e.querySelector('[part~="sort-indicator"], .sort-indicator');t?.remove()}})}getSortModel(){return[...this.sortModel]}setSortModel(e){this.sortModel=[...e],this.clearCoreSortState(),this.emit("sort-change",{sortModel:[...e]}),this.requestRender(),this.grid?.requestStateChange?.()}clearSort(){this.sortModel=[],this.clearCoreSortState(),this.emit("sort-change",{sortModel:[]}),this.requestRender(),this.grid?.requestStateChange?.()}getSortIndex(e){return oi(this.sortModel,e)}getSortDirection(e){return si(this.sortModel,e)}getColumnState(e){const t=this.sortModel.findIndex(t=>t.field===e);if(-1===t)return;return{sort:{direction:this.sortModel[t].direction,priority:t}}}applyColumnState(e,t){if(!t.sort)return void(this.sortModel=this.sortModel.filter(t=>t.field!==e));const i=this.sortModel.findIndex(t=>t.field===e),n={field:e,direction:t.sort.direction};-1!==i?this.sortModel[i]=n:this.sortModel.splice(t.sort.priority,0,n),this.clearCoreSortState()}},e.PLUGIN_QUERIES={CAN_MOVE_COLUMN:"canMoveColumn",GET_CONTEXT_MENU_ITEMS:"getContextMenuItems"},e.PinnedColumnsPlugin=class extends rt{static manifest={ownedProperties:[{property:"pinned",level:"column",description:'the "pinned" column property',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e},{property:"sticky",level:"column",description:'the "sticky" column property (deprecated, use "pinned")',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e}],incompatibleWith:[{name:"groupingColumns",reason:"Pinning reorders columns to the grid edges, but moving a column out of its column group is not supported. The group header layout cannot accommodate members at different positions."}],queries:[{type:pi,description:"Prevents pinned (sticky) columns from being moved/reordered"},{type:"getStickyOffsets",description:"Returns the sticky offsets for left/right pinned columns"},{type:"getContextMenuItems",description:"Contributes pin/unpin items to the header context menu"}]};name="pinnedColumns";get defaultConfig(){return{}}isApplied=!1;leftOffsets=new Map;rightOffsets=new Map;#ti=[];detach(){this.leftOffsets.clear(),this.rightOffsets.clear(),this.isApplied=!1,this.#ti=[]}static detect(e,t){const i=t?.columns;return!!Array.isArray(i)&&hi(i)}processColumns(e){const t=[...e];if(this.isApplied=hi(t),!this.isApplied)return t;const i=this.gridElement;return function(e,t="ltr"){const i=[],n=[],r=[];for(const o of e){const e=li(o);e?"left"===ai(e,t)?i.push(o):r.push(o):n.push(o)}return[...i,...n,...r]}(t,i?M(i):"ltr")}afterRender(){if(!this.isApplied)return;const e=this.grid,t=[...this.columns];if(!hi(t))return gi(e),void(this.isApplied=!1);queueMicrotask(()=>{ui(e,t)})}handleQuery(e){switch(e.type){case pi:return null==li(e.context)&&void 0;case"getStickyOffsets":return{left:Object.fromEntries(this.leftOffsets),right:Object.fromEntries(this.rightOffsets)};case"getContextMenuItems":{const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field)return;if(i.meta?.lockPinning)return;const n=this.grid?.getPluginByName("groupingColumns");if(n?.isGroupingActive())return;const r=[];return null!=li(i)?r.push({id:"pinned/unpin",label:"Unpin Column",icon:"📌",order:40,action:()=>this.setPinPosition(i.field,void 0)}):(r.push({id:"pinned/pin-left",label:"Pin Left",icon:"⬅",order:40,action:()=>this.setPinPosition(i.field,"left")}),r.push({id:"pinned/pin-right",label:"Pin Right",icon:"➡",order:41,action:()=>this.setPinPosition(i.field,"right")})),r}default:return}}setPinPosition(e,t){const i=this.columns;if(!i?.length)return;const n=i.findIndex(t=>t.field===e);if(-1===n)return;const r=this.grid;if(t){0===this.#ti.length&&(this.#ti=i.map(e=>e.field));const n=i.map(i=>{if(i.field!==e)return i;const n={...i};return n.pinned=t,delete n.sticky,n});r.columns=n}else{const t={...i[n]};delete t.pinned,delete t.sticky;const o=[...i];o.splice(n,1);const s=this.#ti.indexOf(e);if(s>=0){let e=o.length;for(let t=0;t<o.length;t++){if(li(o[t]))continue;if(this.#ti.indexOf(o[t].field)>s){e=t;break}}o.splice(e,0,t)}else o.splice(Math.min(n,o.length),0,t);o.some(e=>null!=li(e))||(this.#ti=[]),r.columns=o}}refreshStickyOffsets(){const e=[...this.columns];ui(this.grid,e)}getLeftPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>di(e,t))}([...this.columns],M(this.grid))}getRightPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>ci(e,t))}([...this.columns],M(this.grid))}clearStickyPositions(){gi(this.grid)}getHorizontalScrollOffsets(e,t){if(!this.isApplied)return;let i=0,n=0;if(e){const t=e.querySelectorAll(".sticky-left"),r=e.querySelectorAll(".sticky-right");t.forEach(e=>{i+=e.offsetWidth}),r.forEach(e=>{n+=e.offsetWidth})}else{this.grid.querySelectorAll(".header-row .cell").forEach(e=>{e.classList.contains("sticky-left")?i+=e.offsetWidth:e.classList.contains("sticky-right")&&(n+=e.offsetWidth)})}const r=t?.classList.contains("sticky-left")||t?.classList.contains("sticky-right");return{left:i,right:n,skipScroll:r}}},e.PinnedRowsPlugin=class extends rt{name="pinnedRows";styles="@layer tbw-plugins{.tbw-footer{flex-shrink:0;z-index:var(--tbw-z-layer-pinned-rows, 20);background:var(--tbw-color-panel-bg)}.tbw-pinned-rows{display:flex;align-items:center;justify-content:space-between;padding:var(--tbw-button-padding, var(--tbw-spacing-md, .5rem) var(--tbw-spacing-lg, .75rem));background:var(--tbw-pinned-rows-bg, var(--tbw-color-panel-bg));border-top:1px solid var(--tbw-pinned-rows-border, var(--tbw-color-border));font-size:var(--tbw-font-size-xs, .75rem);color:var(--tbw-pinned-rows-color, var(--tbw-color-fg-muted));min-height:32px;box-sizing:border-box;min-width:fit-content}.tbw-pinned-rows-left,.tbw-pinned-rows-center,.tbw-pinned-rows-right{display:flex;align-items:center;gap:var(--tbw-spacing-xl, 1rem)}.tbw-pinned-rows-left{justify-content:flex-start}.tbw-pinned-rows-center{justify-content:center;flex:1}.tbw-pinned-rows-right{justify-content:flex-end}.tbw-status-panel{white-space:nowrap}.tbw-aggregation-rows{min-width:fit-content;background:var(--tbw-aggregation-bg, var(--tbw-color-header-bg))}.tbw-aggregation-rows-top{border-bottom:1px solid var(--tbw-aggregation-border, var(--tbw-color-border))}.tbw-aggregation-rows-bottom{border-top:1px solid var(--tbw-aggregation-border, var(--tbw-color-border))}.tbw-aggregation-row{display:grid;grid-template-columns:var(--tbw-column-template);font-size:var(--tbw-aggregation-font-size, .8em);font-weight:var(--tbw-aggregation-font-weight, 600)}.tbw-aggregation-cell{padding:var(--tbw-cell-padding, .125rem .5rem);min-height:var(--tbw-row-height, 1.75rem);display:block;align-items:center;align-content:center;border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;text-overflow:ellipsis;white-space:var(--tbw-cell-white-space, nowrap)}.tbw-aggregation-cell:last-child{border-right:0}.tbw-aggregation-cell-full{grid-column:1 / -1;border-right:0;display:flex;align-items:center;gap:var(--tbw-spacing-lg, .75rem)}.tbw-aggregation-label{white-space:nowrap}.tbw-aggregation-aggregates{display:flex;align-items:center;gap:var(--tbw-spacing-lg, .75rem);font-weight:400;opacity:.85}.tbw-aggregation-aggregate{white-space:nowrap}}";get defaultConfig(){return{position:"bottom",showRowCount:!0,showSelectedCount:!0,showFilteredCount:!0}}infoBarElement=null;topAggregationContainer=null;bottomAggregationContainer=null;footerWrapper=null;detach(){this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null),this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null)}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-scroll-area")??e.querySelector(".tbw-grid-content")??e.children[0];if(!t)return;this.footerWrapper&&!t.contains(this.footerWrapper)&&(this.footerWrapper=null,this.bottomAggregationContainer=null,this.infoBarElement=null),this.topAggregationContainer&&!t.contains(this.topAggregationContainer)&&(this.topAggregationContainer=null),this.infoBarElement&&!t.contains(this.infoBarElement)&&(this.infoBarElement=null);const i=this.getSelectionState(),n=this.getFilterState(),r=xi(this.sourceRows,this.columns,this.grid,i,n),o=this.config.aggregationRows||[],s=o.filter(e=>"top"===e.position),l=o.filter(e=>"top"!==e.position);if(s.length>0){if(!this.topAggregationContainer){this.topAggregationContainer=wi("top");const i=e.querySelector(".header");i&&i.nextSibling?t.insertBefore(this.topAggregationContainer,i.nextSibling):t.appendChild(this.topAggregationContainer)}mi(this.topAggregationContainer,s,this.visibleColumns,this.sourceRows,this.config.fullWidth)}else this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null);const a=!1!==this.config.showRowCount||this.config.showSelectedCount&&r.selectedRows>0||this.config.showFilteredCount&&r.filteredRows!==r.totalRows||this.config.customPanels&&this.config.customPanels.length>0,d=a&&"top"!==this.config.position,c=l.length>0||d;if(a&&"top"===this.config.position)if(this.infoBarElement){const e=fi(this.config,r);this.infoBarElement.replaceWith(e),this.infoBarElement=e}else this.infoBarElement=fi(this.config,r),t.insertBefore(this.infoBarElement,t.firstChild);else"top"===this.config.position&&this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null);c?(this.footerWrapper||(this.footerWrapper=document.createElement("div"),this.footerWrapper.className="tbw-footer",t.appendChild(this.footerWrapper)),this.footerWrapper.innerHTML="",l.length>0&&(this.bottomAggregationContainer||(this.bottomAggregationContainer=wi("bottom")),this.footerWrapper.appendChild(this.bottomAggregationContainer),mi(this.bottomAggregationContainer,l,this.visibleColumns,this.sourceRows,this.config.fullWidth)),d&&(this.infoBarElement=fi(this.config,r),this.footerWrapper.appendChild(this.infoBarElement))):this.cleanupFooter()}cleanup(){this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null),this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null)}cleanupFooter(){this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.infoBarElement&&"top"!==this.config.position&&(this.infoBarElement.remove(),this.infoBarElement=null)}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}getFilterState(){try{return this.grid?.getPluginState?.("filtering")??null}catch{return null}}refresh(){this.requestRender()}getContext(){const e=this.getSelectionState(),t=this.getFilterState();return xi(this.rows,this.columns,this.grid,e,t)}addPanel(e){this.config.customPanels||(this.config.customPanels=[]),this.config.customPanels.push(e),this.requestRender()}removePanel(e){this.config.customPanels&&(this.config.customPanels=this.config.customPanels.filter(t=>t.id!==e),this.requestRender())}addAggregationRow(e){this.config.aggregationRows||(this.config.aggregationRows=[]),this.config.aggregationRows.push(e),this.requestRender()}removeAggregationRow(e){this.config.aggregationRows&&(this.config.aggregationRows=this.config.aggregationRows.filter(t=>t.id!==e),this.requestRender())}},e.PivotPlugin=zi,e.PluginEvents={SELECTION_CHANGE:"selection-change",TREE_EXPAND:"tree-expand",FILTER_CHANGE:"filter-change",SORT_MODEL_CHANGE:"sort-model-change",EXPORT_START:"export-start",EXPORT_COMPLETE:"export-complete",CLIPBOARD_COPY:"clipboard-copy",CLIPBOARD_PASTE:"clipboard-paste",CONTEXT_MENU_OPEN:"context-menu-open",CONTEXT_MENU_CLOSE:"context-menu-close",HISTORY_CHANGE:"history-change",SERVER_LOADING:"server-loading",SERVER_ERROR:"server-error",COLUMN_VISIBILITY_CHANGE:"column-visibility-change",COLUMN_REORDER:"column-reorder",DETAIL_EXPAND:"detail-expand",GROUP_EXPAND:"group-expand"},e.PluginManager=it,e.PrintPlugin=class extends rt{name="print";version="1.0.0";styles=".tbw-print-header,.tbw-print-footer{display:none}@media print{tbw-grid{overflow:visible!important;height:auto!important;border:none!important;border-radius:0!important;color-scheme:light only;-webkit-print-color-adjust:exact;print-color-adjust:exact}tbw-grid .tbw-grid-content{overflow:visible!important;height:auto!important;max-height:none!important}tbw-grid .tbw-scroll-area{overflow:visible!important;height:auto!important;max-height:none!important}tbw-grid .rows-body{overflow:visible!important;height:auto!important;max-height:none!important}tbw-grid .rows-container,tbw-grid .rows-viewport,tbw-grid .rows{overflow:visible!important;height:auto!important;max-height:none!important;transform:none!important}tbw-grid .rows-viewport .rows{position:static!important}tbw-grid .resize-handle,tbw-grid [part=sort-indicator],tbw-grid .tbw-filter-btn,tbw-grid .tool-panel,tbw-grid .tool-panel-content,tbw-grid .tbw-shell-header,tbw-grid .shell-toolbar,tbw-grid .tool-panel-toggle,tbw-grid [data-print-hide],tbw-grid .expander-cell,tbw-grid .tree-toggle,tbw-grid .context-menu,tbw-grid .faux-vscroll{display:none!important}tbw-grid .tbw-print-header{display:flex;justify-content:space-between;align-items:baseline;padding:var(--tbw-spacing-md, .5em) 0;margin-bottom:var(--tbw-spacing-md, .5em);border-bottom:2px solid var(--tbw-print-border, var(--tbw-color-border-strong));font-family:inherit}.tbw-print-header-title{font-size:1.25em;font-weight:700}.tbw-print-header-timestamp{font-size:var(--tbw-font-size-sm, .875em);color:var(--tbw-print-muted, var(--tbw-color-fg-muted))}tbw-grid .tbw-print-footer{display:block;margin-top:var(--tbw-spacing-md, .5em);padding-top:var(--tbw-spacing-md, .5em);border-top:1px solid var(--tbw-print-border, var(--tbw-color-border));font-size:var(--tbw-font-size-xs, .75em);color:var(--tbw-print-muted, var(--tbw-color-fg-muted));text-align:end}tbw-grid .data-grid-row{break-inside:avoid;page-break-inside:avoid}tbw-grid .cell{border:1px solid var(--tbw-print-cell-border, var(--tbw-color-border))!important}tbw-grid .header-row,tbw-grid .data-grid-row{padding-inline-end:1px}tbw-grid .data-grid-row:hover,tbw-grid .cell:hover{background:inherit!important}@page{margin:1cm}@page{tbw-grid.print-landscape{size:landscape}}@page{tbw-grid.print-portrait{size:portrait}}}";#ii=!1;#ni=null;#ri=null;#oi=null;#si=null;#li=null;#ai=null;get#di(){return this.grid}isPrinting(){return this.#ii}async print(e){if(this.#ii)return void console.warn("[PrintPlugin] Print already in progress");const t=this.gridElement;if(!t)return void console.warn("[PrintPlugin] Grid not available");const i={...Fi,...this.config,...e},n=this.rows.length;let r=n,o=!1;if(i.warnThreshold>0&&n>i.warnThreshold){const e=i.maxRows>0?`\n\nNote: Output will be limited to ${i.maxRows.toLocaleString()} rows.`:"";if(!confirm(`This grid has ${n.toLocaleString()} rows. Printing large datasets may cause performance issues or browser slowdowns.${e}\n\nClick OK to continue, or Cancel to abort.`))return}i.maxRows>0&&n>i.maxRows&&(r=i.maxRows,o=!0),this.#ii=!0;const s=performance.now();this.emit("print-start",{rowCount:r,limitApplied:o,originalRowCount:n});try{const e=this.#di;this.#ri={bypassThreshold:e._virtualization?.bypassThreshold??24},this.#ci(),o&&(this.#oi=this.sourceRows,this.grid.rows=this.sourceRows.slice(0,r),await new Promise(e=>setTimeout(e,50))),(i.includeTitle||i.includeTimestamp)&&this.#hi(i),await this.#ui(),await new Promise(e=>requestAnimationFrame(e)),await new Promise(e=>requestAnimationFrame(e)),t.classList.add(`print-${i.orientation}`),await new Promise(e=>requestAnimationFrame(e)),await new Promise(e=>requestAnimationFrame(e)),i.isolate?await this.#gi(i):await this.#pi(),this.emit("print-complete",{success:!0,rowCount:r,duration:Math.round(performance.now()-s)})}catch(l){console.error("[PrintPlugin] Print failed:",l),this.emit("print-complete",{success:!1,rowCount:0,duration:Math.round(performance.now()-s)})}finally{this.#fi(),this.#ii=!1}}#hi(e){const t=this.gridElement;if(t){if(this.#si=document.createElement("div"),this.#si.className="tbw-print-header",e.includeTitle){const t=e.title||this.grid.effectiveConfig?.shell?.header?.title||"Grid Data",i=document.createElement("div");i.className="tbw-print-header-title",i.textContent=t,this.#si.appendChild(i)}if(e.includeTimestamp){const e=document.createElement("div");e.className="tbw-print-header-timestamp",e.textContent=`Printed: ${(new Date).toLocaleString()}`,this.#si.appendChild(e)}t.insertBefore(this.#si,t.firstChild),this.#li=document.createElement("div"),this.#li.className="tbw-print-footer",this.#li.textContent=`Page generated from ${window.location.hostname}`,t.appendChild(this.#li)}}async#ui(){const e=this.#di;if(!e._virtualization)return;const t=this.rows.length;e._virtualization.bypassThreshold=t+100,e.refreshVirtualWindow(!0),await new Promise(e=>setTimeout(e,100))}async#pi(){return new Promise(e=>{const t=()=>{window.removeEventListener("afterprint",t),e()};window.addEventListener("afterprint",t),window.print(),setTimeout(()=>{"undefined"!=typeof window&&window.removeEventListener("afterprint",t),e()},1e3)})}async#gi(e){const t=this.gridElement;t&&await qi(t,{orientation:e.orientation})}#ci(){const e=this.columns;if(e){this.#ni=new Map;for(const t of e)t.printHidden&&t.field&&(this.#ni.set(t.field,!t.hidden),this.grid.setColumnVisible(t.field,!1))}}#wi(){if(this.#ni){for(const[e,t]of this.#ni)this.grid.setColumnVisible(e,t);this.#ni=null}}#fi(){const e=this.gridElement;if(!e)return;this.#wi(),e.classList.remove("print-portrait","print-landscape"),null!==this.#ai&&(e.style.transform="",e.style.transformOrigin="",e.style.width="",this.#ai=null),this.#si&&(this.#si.remove(),this.#si=null),this.#li&&(this.#li.remove(),this.#li=null);const t=this.#di;this.#ri&&t._virtualization&&(t._virtualization.bypassThreshold=this.#ri.bypassThreshold,t.refreshVirtualWindow(!0),this.#ri=null),null!==this.#oi&&(this.grid.rows=this.#oi,this.#oi=null)}afterRender(){this.config?.button&&!this.#mi&&(this.#bi(),this.#mi=!0)}#mi=!1;#bi(){const e=this.#di;e.registerToolbarContent?.({id:"print-button",order:900,render:e=>{const t=document.createElement("button");t.className="tbw-toolbar-btn tbw-print-btn",t.title="Print grid",t.type="button";const i=this.resolveIcon("print")||"🖨️";this.setIcon(t,i),t.addEventListener("click",()=>{this.print()},{signal:this.disconnectSignal}),e.appendChild(t)}})}},e.ROW_DRAG_HANDLE_FIELD=Gi,e.RenderPhase=he,e.ReorderPlugin=class extends rt{name="reorder";styles='@layer tbw-plugins{.header-row>.cell[draggable=true]{cursor:grab;position:relative}.header-row>.cell.dragging{opacity:.5;cursor:grabbing}.header-row>.cell.drop-before:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.header-row>.cell.drop-after:after{content:"";position:absolute;right:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.cell.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}@keyframes reorder-fade-in{0%{opacity:0}to{opacity:1}}.cell.fade-animating{animation:reorder-fade-in var(--tbw-animation-duration, .2s) ease-out backwards}}';get defaultConfig(){return{animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}get animationDuration(){return void 0!==this.config.animationDuration?this.config.animationDuration:super.animationDuration}isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;canMoveColumnWithPlugins(e){if(!e||!function(e){const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}(e))return!1;return!this.grid.query("canMoveColumn",e).includes(!1)}clearDragClasses(){this.gridElement?.querySelectorAll(".header-row > .cell").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-reorder-request",e=>{const t=e.detail;t?.field&&"number"==typeof t.toIndex&&this.moveColumn(t.field,t.toIndex)},{signal:this.disconnectSignal})}detach(){this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}afterRender(){const e=this.gridElement;if(!e)return;e.querySelectorAll(".header-row > .cell").forEach(e=>{const t=e,i=t.getAttribute("data-field");if(!i)return;const n=this.columns.find(e=>e.field===i);this.canMoveColumnWithPlugins(n)?(t.draggable=!0,t.getAttribute("data-dragstart-bound")||(t.setAttribute("data-dragstart-bound","true"),t.addEventListener("dragstart",e=>{const n=this.getColumnOrder().indexOf(i);this.isDragging=!0,this.draggedField=i,this.draggedIndex=n,e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",i)),t.classList.add("dragging")}),t.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses()}),t.addEventListener("dragover",e=>{if(e.preventDefault(),!this.isDragging||this.draggedField===i)return;const n=t.getBoundingClientRect(),r=n.left+n.width/2,o=this.getColumnOrder().indexOf(i);this.dropIndex=e.clientX<r?o:o+1,t.classList.add("drop-target"),t.classList.toggle("drop-before",e.clientX<r),t.classList.toggle("drop-after",e.clientX>=r)}),t.addEventListener("dragleave",()=>{t.classList.remove("drop-target","drop-before","drop-after")}),t.addEventListener("drop",e=>{e.preventDefault();const t=this.draggedField,i=this.draggedIndex,n=this.dropIndex;if(!this.isDragging||null===t||null===i||null===n)return;const r=n>i?n-1:n,o=Ni(this.getColumnOrder(),i,r),s={field:t,fromIndex:i,toIndex:r,columnOrder:o};this.emitCancelable("column-move",s)||this.updateColumnOrder(o)}))):t.draggable=!1})}onKeyDown(e){if(!e.altKey||"ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;const t=this.grid,i=t._focusCol,n=t._visibleColumns;if(i<0||i>=n.length)return;const r=n[i];if(!this.canMoveColumnWithPlugins(r))return;const o=this.getColumnOrder(),s=o.indexOf(r.field);if(-1===s)return;const l="ArrowLeft"===e.key?s-1:s+1;if(l<0||l>=o.length)return;const a=n.find(e=>e.field===o[l]);return this.canMoveColumnWithPlugins(a)?(this.moveColumn(r.field,l),t._focusCol=l,K(this.grid),e.preventDefault(),e.stopPropagation(),!0):void 0}getColumnOrder(){return this.grid.getColumnOrder()}moveColumn(e,t){const i=this.getColumnOrder(),n=i.indexOf(e);if(-1===n)return;const r=Ni(i,n,t);this.emitCancelable("column-move",{field:e,fromIndex:n,toIndex:t,columnOrder:r})||this.updateColumnOrder(r)}setColumnOrder(e){this.updateColumnOrder(e)}resetColumnOrder(){const e=this.columns.map(e=>e.field);this.updateColumnOrder(e)}captureHeaderPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const i=t.getAttribute("data-field");i&&e.set(i,t.getBoundingClientRect().left)}),e}animateFLIP(e){const t=this.gridElement;if(!t||0===e.size)return;const i=new Map;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const n=t.getAttribute("data-field");if(!n)return;const r=e.get(n);if(void 0===r)return;const o=r-t.getBoundingClientRect().left;Math.abs(o)>1&&i.set(n,o)}),0===i.size)return;const n=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=i.get(e.getAttribute("data-field")??"");if(void 0!==t){const i=e;i.style.transform=`translateX(${t}px)`,n.push(i)}}),0===n.length)return;this.gridElement.offsetHeight;const r=this.animationDuration;requestAnimationFrame(()=>{n.forEach(e=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{n.forEach(e=>{e.style.transform="",e.classList.remove("flip-animating")})},r+50)})}animateFade(e){const t=this.gridElement;if(!t)return void e();const i=this.captureHeaderPositions();e();const n=new Set;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(!t)return;const r=i.get(t);if(void 0===r)return;const o=e.getBoundingClientRect().left;Math.abs(r-o)>1&&n.add(t)}),0===n.size)return;const r=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(t&&n.has(t)){const t=e;t.classList.add("fade-animating"),r.push(t)}}),0===r.length)return;const o=this.animationDuration;setTimeout(()=>{r.forEach(e=>e.classList.remove("fade-animating"))},o+50)}updateColumnOrder(e){const t=this.animationType;if("flip"===t&&this.gridElement){const t=this.captureHeaderPositions();this.grid.setColumnOrder(e),requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(t)})}else"fade"===t?this.animateFade(()=>this.grid.setColumnOrder(e)):this.grid.setColumnOrder(e);this.grid.requestStateChange?.()}},e.ResponsivePlugin=class extends rt{name="responsive";version="1.0.0";styles='tbw-grid[data-responsive-animate] .data-grid-row,tbw-grid[data-responsive-animate] .data-grid-row>.cell{transition:opacity var(--tbw-responsive-duration, .2s) ease-out,transform var(--tbw-responsive-duration, .2s) ease-out}tbw-grid[data-responsive][data-responsive-animate] .data-grid-row{animation:responsive-card-enter var(--tbw-responsive-duration, .2s) ease-out}@keyframes responsive-card-enter{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}tbw-grid[data-responsive] .header{display:none!important}tbw-grid[data-responsive] .footer-row{display:none}tbw-grid[data-responsive] .tbw-scroll-area{overflow-x:hidden;min-width:0!important}tbw-grid[data-responsive] .rows-body-wrapper{min-width:0!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row){display:block!important;grid-template-columns:none!important;padding:var(--tbw-cell-padding);padding-inline-start:var(--tbw-spacing-xl);border-bottom:1px solid var(--tbw-color-border);min-height:auto!important;height:auto!important;contain:none!important;content-visibility:visible!important;background:var(--tbw-color-bg);position:relative}tbw-grid[data-responsive] .data-grid-row:not(.group-row):nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid[data-responsive] .data-grid-row:not(.group-row):hover{background:var(--tbw-color-row-hover)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]{background:var(--tbw-color-selection)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]:before{content:"";position:absolute;inset-inline-start:0;top:0;bottom:0;width:4px;background:var(--tbw-color-accent)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell{display:flex!important;justify-content:space-between;align-items:center;padding:var(--tbw-spacing-xs) var(--tbw-spacing-md);width:100%!important;min-width:0!important;min-height:auto!important;height:auto!important;line-height:1.5!important;position:static!important;left:auto!important;right:auto!important;border:none!important;border-bottom:none!important;border-inline-end:none!important;background:transparent!important;white-space:normal!important;overflow:visible!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:before{content:attr(data-header) ": ";font-weight:600;color:var(--tbw-color-header-fg);flex-shrink:0;margin-inline-end:var(--tbw-spacing-md);min-width:100px}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:after{content:none}tbw-grid[data-responsive] .cell[data-utility]{display:none!important}tbw-grid[data-responsive] .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .cell[data-responsive-value-only]:before{display:none!important}tbw-grid:not([data-responsive]) .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .tbw-footer,tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows{display:none!important}tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows,tbw-grid[data-responsive] .tbw-aggregation-row{min-width:0!important}tbw-grid[data-responsive] .data-grid-row.responsive-card{display:block!important;padding:var(--tbw-cell-padding);border-bottom:1px solid var(--tbw-color-border)}tbw-grid[data-responsive] .data-grid-row.responsive-card>*{width:100%}tbw-grid[data-responsive] .data-grid-row.responsive-card .cell:before{display:none}';static manifest={incompatibleWith:[{name:"groupingRows",reason:"Responsive card layout does not yet support row grouping. The variable row heights (cards vs group headers) cause scroll calculation issues."}],queries:[{type:"isCardMode",description:"Returns whether the grid is currently in responsive card mode"}]};#K;#vi=!1;#yi;#Ci=!1;#xi=0;#Ei=new Set;#Ri=new Set;#Si=null;#_i=[];isResponsive(){return this.#vi}setResponsive(e){e!==this.#vi&&(this.#vi=e,this.#Ai(),this.emit("responsive-change",{isResponsive:e,width:this.#xi,breakpoint:this.config.breakpoint??0}))}setBreakpoint(e){this.config.breakpoint=e,this.#ki(this.#xi)}setCardRenderer(e){this.config.cardRenderer=e,this.#vi&&this.requestRender()}getWidth(){return this.#xi}getActiveBreakpoint(){return this.#Si}attach(e){super.attach(e),this.#Ti(),this.#Li(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#_i=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#K=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#xi=t,clearTimeout(this.#yi),this.#yi=setTimeout(()=>{this.#ki(t)},this.config.debounceMs??100)}),this.#K.observe(this.gridElement)}#Ti(){const e=this.grid;if(!e||"function"!=typeof e.querySelector)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const i=e;if(i.__frameworkAdapter?.parseResponsiveCardElement){const e=i.__frameworkAdapter.parseResponsiveCardElement(t);e&&(this.config={...this.config,cardRenderer:e})}const n=t.getAttribute("breakpoint"),r=t.getAttribute("card-row-height"),o=t.getAttribute("hidden-columns"),s=t.getAttribute("hide-header"),l=t.getAttribute("debounce-ms"),a={};if(null!==n){const e=parseInt(n,10);isNaN(e)||(a.breakpoint=e)}if(null!==r&&(a.cardRowHeight="auto"===r?"auto":parseInt(r,10)),null!==o&&(a.hiddenColumns=o.split(",").map(e=>e.trim()).filter(e=>e.length>0)),null!==s&&(a.hideHeader="false"!==s),null!==l){const e=parseInt(l,10);isNaN(e)||(a.debounceMs=e)}const d=t.innerHTML.trim();!d||this.config.cardRenderer||i.__frameworkAdapter?.parseResponsiveCardElement||(a.cardRenderer=e=>{const t=y(C(d,{value:e,row:e})),i=document.createElement("div");return i.className="tbw-responsive-card-content",i.innerHTML=t,i}),Object.keys(a).length>0&&(this.config={...this.config,...a})}#Li(e){if(this.#Ei.clear(),this.#Ri.clear(),e)for(const t of e)"string"==typeof t?this.#Ei.add(t):t.showValue?this.#Ri.add(t.field):this.#Ei.add(t.field)}detach(){this.#K?.disconnect(),this.#K=void 0,clearTimeout(this.#yi),this.#yi=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#vi}afterRender(){this.#Mi();if(!(this.#_i.length>0?null!==this.#Si:this.#vi))return;const e=this.#Ei.size>0,t=this.#Ri.size>0;if(!e&&!t)return;const i=this.gridElement.querySelectorAll(".cell[data-field]");for(const n of i){const e=n.getAttribute("data-field");e&&(this.#Ei.has(e)?(n.setAttribute("data-responsive-hidden",""),n.removeAttribute("data-responsive-value-only")):this.#Ri.has(e)?(n.setAttribute("data-responsive-value-only",""),n.removeAttribute("data-responsive-hidden")):(n.removeAttribute("data-responsive-hidden"),n.removeAttribute("data-responsive-value-only")))}}#ki(e){if(this.#_i.length>0)return void this.#Pi(e);const t=this.config.breakpoint??0;0!==t||this.#Ci||(this.#Ci=!0,console.warn("[tbw-grid:ResponsivePlugin] No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count."));const i=t>0&&e<t;i!==this.#vi&&(this.#vi=i,this.#Ai(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#Pi(e){let t=null;for(const i of this.#_i)e<=i.maxWidth&&(t=i);if(t!==this.#Si){this.#Si=t,t?.hiddenColumns?this.#Li(t.hiddenColumns):this.#Li(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#vi&&(this.#vi=i,this.#Ai()),this.emit("responsive-change",{isResponsive:this.#vi,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#Hi;#Ai(){this.gridElement.toggleAttribute("data-responsive",this.#vi);const e=!1!==this.config.animate;this.gridElement.toggleAttribute("data-responsive-animate",e),this.config.animationDuration&&this.gridElement.style.setProperty("--tbw-responsive-duration",`${this.config.animationDuration}ms`);const t=this.grid;if(this.#vi){t._virtualization&&(this.#Hi=t._virtualization.rowHeight);const e=this.gridElement.querySelector(".tbw-scroll-area");e&&(e.scrollLeft=0)}else{const e=this.gridElement.querySelectorAll(".data-grid-row");for(const t of e)t.style.height="",t.classList.remove("responsive-card");this.#Hi&&this.#Hi>0&&t._virtualization&&(t._virtualization.rowHeight=this.#Hi,this.#Hi=void 0),this.#Ii=void 0,this.#Di=void 0,this.#zi=void 0}}renderRow(e,t,i){if(!this.#vi||!this.config.cardRenderer)return;if(e.__isGroupRow)return;t.replaceChildren();const n=this.config.cardRenderer(e,i);t.className="data-grid-row responsive-card";const r=this.config.cardRowHeight??"auto";return t.style.height="auto"!==r?`${r}px`:"auto",t.appendChild(n),!0}onKeyDown(e){if(!this.#vi)return!1;if(this.config.cardRenderer){if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return!1}const t=this.rows.length-1,i=this.visibleColumns.length-1;switch(e.key){case"ArrowDown":if(this.grid._focusCol<i)return this.grid._focusCol+=1,e.preventDefault(),K(this.grid),!0;if(this.grid._focusRow<t)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),K(this.grid),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),K(this.grid),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=i,e.preventDefault(),K(this.grid),!0;break;case"ArrowRight":if(this.grid._focusRow<t)return this.grid._focusRow+=1,e.preventDefault(),K(this.grid),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),K(this.grid),!0}return!1}#Ii;#Di;#zi;#Oi(){if(this.#Ii&&this.#Ii>0)return this.#Ii;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#qi(){return this.#Di&&this.#Di>0?this.#Di:this.#Hi??28}#Fi(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}#Ni(){let e=0,t=0;for(const i of this.rows)i.__isGroupRow?e++:t++;return{groupCount:e,cardCount:t}}getExtraHeight(){if(!this.#vi||!this.config.cardRenderer)return 0;if(!this.#Fi())return 0;const e=this.#Hi??28,t=this.#qi(),i=this.#Oi(),{groupCount:n,cardCount:r}=this.#Ni();return n*Math.max(0,t-e)+r*Math.max(0,i-e)}getExtraHeightBefore(e){if(!this.#vi||!this.config.cardRenderer)return 0;if(!this.#Fi())return 0;const t=this.#Hi??28,i=this.#qi(),n=this.#Oi(),r=Math.max(0,i-t),o=Math.max(0,n-t);let s=0,l=0;const a=this.rows,d=Math.min(e,a.length);for(let c=0;c<d;c++)a[c].__isGroupRow?s++:l++;return s*r+l*o}getRowHeight(e,t){if(this.#vi&&this.config.cardRenderer)return e.__isGroupRow?this.#qi():this.#Oi()}#Gi(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#Vi=!1;#Mi(){if(!this.#vi||!this.config.cardRenderer)return;let e=!1;const t=this.grid,i=this.#Fi(),n=this.#Gi();if(n!==this.#zi&&(this.#zi=n,e=!0),i){const t=this.gridElement.querySelector(".data-grid-row.group-row");if(t){const i=t.getBoundingClientRect().height;i>0&&i!==this.#Di&&(this.#Di=i,e=!0)}}const r=this.gridElement.querySelector(".data-grid-row.responsive-card");if(r){const n=r.getBoundingClientRect().height;n>0&&n!==this.#Ii&&(this.#Ii=n,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=n))}e&&!this.#Vi&&(this.#Vi=!0,queueMicrotask(()=>{this.#Vi=!1,this.grid&&this.#vi&&this.grid.refreshVirtualWindow?.(!0,!0)}))}},e.RowReorderPlugin=class extends rt{name="rowReorder";styles='@layer tbw-plugins{[data-field=__tbw_row_drag]{display:flex;align-items:center;justify-content:center}.dg-row-drag-handle{display:flex;align-items:center;justify-content:center;min-width:1em;min-height:1em;cursor:grab;-webkit-user-select:none;user-select:none;color:var(--tbw-row-reorder-handle-color, var(--tbw-color-fg-muted));transition:color var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease);font-size:var(--tbw-font-size, 1em);letter-spacing:-2px}.dg-row-drag-handle:hover{color:var(--tbw-row-reorder-handle-hover, var(--tbw-color-fg))}.dg-row-drag-handle:active{cursor:grabbing}.data-grid-row.dragging{opacity:.6}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before{content:"";position:absolute;top:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.drop-target.drop-after:after{content:"";position:absolute;bottom:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.keyboard-moving{background-color:var(--tbw-row-reorder-moving-bg, var(--tbw-focus-background));box-shadow:0 0 0 1px var(--tbw-row-reorder-moving-border, var(--tbw-color-accent)) inset}.data-grid-row.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}}';get defaultConfig(){return{enableKeyboard:!0,showDragHandle:!0,dragHandlePosition:"left",dragHandleWidth:40,debounceMs:150,animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}isDragging=!1;draggedRowIndex=null;dropRowIndex=null;pendingMove=null;debounceTimer=null;lastFocusCol=0;detach(){this.clearDebounceTimer(),this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.pendingMove=null}processColumns(e){if(!this.config.showDragHandle)return[...e];const t={field:Gi,header:"",width:this.config.dragHandleWidth??40,resizable:!1,sortable:!1,filterable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0},viewRenderer:()=>{const e=document.createElement("div");return e.className="dg-row-drag-handle",e.setAttribute("aria-label","Drag to reorder"),e.setAttribute("role","button"),e.setAttribute("tabindex","-1"),e.draggable=!0,this.setIcon(e,this.resolveIcon("dragHandle")),e}};return"right"===this.config.dragHandlePosition?[...e,t]:[t,...e]}afterRender(){if(!this.config.showDragHandle)return;const e=this.gridElement;if(!e)return;e.querySelectorAll(".dg-row-drag-handle").forEach(e=>{const t=e;if(t.getAttribute("data-drag-bound"))return;t.setAttribute("data-drag-bound","true");const i=t.closest(".data-grid-row");i&&this.setupHandleDragListeners(t,i)});e.querySelectorAll(".data-grid-row").forEach(e=>{const t=e;t.getAttribute("data-drop-bound")||(t.setAttribute("data-drop-bound","true"),this.setupRowDropListeners(t))})}onKeyDown(e){if(!this.config.enableKeyboard)return;if(!e.ctrlKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key)return;const t=this.grid,i=t._focusRow,n=t._rows??this.sourceRows;if(i<0||i>=n.length)return;const r="ArrowUp"===e.key?"up":"down",o="up"===r?i-1:i+1;if(o<0||o>=n.length)return;const s=n[i];return!this.config.canMove||this.config.canMove(s,i,o,r)?(this.handleKeyboardMove(s,i,o,r,t._focusCol),e.preventDefault(),e.stopPropagation(),!0):void 0}onCellClick(){this.flushPendingMove()}moveRow(e,t){const i=[...this.sourceRows];if(e<0||e>=i.length)return;if(t<0||t>=i.length)return;if(e===t)return;const n=t<e?"up":"down",r=i[e];this.config.canMove&&!this.config.canMove(r,e,t,n)||this.executeMove(r,e,t,"keyboard")}canMoveRow(e,t){const i=this.sourceRows;if(e<0||e>=i.length)return!1;if(t<0||t>=i.length)return!1;if(e===t)return!1;if(!this.config.canMove)return!0;const n=t<e?"up":"down";return this.config.canMove(i[e],e,t,n)}setupHandleDragListeners(e,t){e.addEventListener("dragstart",e=>{const i=this.getRowIndex(t);i<0||(this.isDragging=!0,this.draggedRowIndex=i,e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",String(i))),t.classList.add("dragging"))}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.clearDragClasses()})}setupRowDropListeners(e){e.addEventListener("dragover",t=>{if(t.preventDefault(),!this.isDragging||null===this.draggedRowIndex)return;const i=this.getRowIndex(e);if(i<0||i===this.draggedRowIndex)return;const n=e.getBoundingClientRect(),r=n.top+n.height/2,o=t.clientY<r;this.dropRowIndex=o?i:i+1,e.classList.add("drop-target"),e.classList.toggle("drop-before",o),e.classList.toggle("drop-after",!o)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",e=>{e.preventDefault();const t=this.draggedRowIndex;let i=this.dropRowIndex;if(this.isDragging&&null!==t&&null!==i&&(i>t&&i--,t!==i)){const e=this.sourceRows[t],n=i<t?"up":"down";this.config.canMove&&!this.config.canMove(e,t,i,n)||this.executeMove(e,t,i,"drag")}})}handleKeyboardMove(e,t,i,n,r){this.pendingMove?this.pendingMove.currentIndex=i:this.pendingMove={originalIndex:t,currentIndex:i,row:e},this.lastFocusCol=r;const o=this.grid,s=[...o._rows??this.sourceRows],[l]=s.splice(t,1);s.splice(i,0,l),o._rows=s,o._focusRow=i,o._focusCol=r,o.refreshVirtualWindow(!0),K(o),this.clearDebounceTimer(),this.debounceTimer=setTimeout(()=>{this.flushPendingMove()},this.config.debounceMs??300)}flushPendingMove(){if(this.clearDebounceTimer(),!this.pendingMove)return;const{originalIndex:e,currentIndex:t,row:i}=this.pendingMove;if(this.pendingMove=null,e===t)return;const n={row:i,fromIndex:e,toIndex:t,rows:[...this.sourceRows],source:"keyboard"};if(this.emitCancelable("row-move",n)){const i=[...this.sourceRows],[n]=i.splice(t,1);i.splice(e,0,n);const r=this.grid;r._rows=i,r._focusRow=e,r._focusCol=this.lastFocusCol,r.refreshVirtualWindow(!0),K(r)}}executeMove(e,t,i,n){const r=[...this.sourceRows],[o]=r.splice(t,1);r.splice(i,0,o);const s={row:e,fromIndex:t,toIndex:i,rows:r,source:n};if(!this.emitCancelable("row-move",s))if("flip"===this.animationType&&this.gridElement){const e=this.captureRowPositions();this.grid.rows=r,requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(e,t,i)})}else this.grid.rows=r}captureRowPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".data-grid-row").forEach(t=>{const i=this.getRowIndex(t);i>=0&&e.set(i,t.getBoundingClientRect().top)}),e}animateFLIP(e,t,i){const n=this.gridElement;if(!n||0===e.size)return;const r=Math.min(t,i),o=Math.max(t,i),s=[];if(n.querySelectorAll(".data-grid-row").forEach(n=>{const l=n,a=this.getRowIndex(l);if(a<0||a<r||a>o)return;let d;d=a===i?t:t<i?a+1:a-1;const c=e.get(d);if(void 0===c)return;const h=c-l.getBoundingClientRect().top;Math.abs(h)>1&&s.push({el:l,deltaY:h})}),0===s.length)return;s.forEach(({el:e,deltaY:t})=>{e.style.transform=`translateY(${t}px)`}),n.offsetHeight;const l=this.animationDuration;requestAnimationFrame(()=>{s.forEach(({el:e})=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{s.forEach(({el:e})=>{e.style.transform="",e.classList.remove("flip-animating")})},l+50)})}getRowIndex(e){const t=e.querySelector(".cell[data-row]");return t?parseInt(t.getAttribute("data-row")??"-1",10):-1}clearDragClasses(){this.gridElement?.querySelectorAll(".data-grid-row").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}},e.SelectionPlugin=class extends rt{static manifest={queries:[{type:"getSelection",description:"Get the current selection state"},{type:"selectRows",description:"Select specific rows by index (row mode only)"},{type:"getSelectedRowIndices",description:"Get sorted array of selected row indices"},{type:"getSelectedRows",description:"Get actual row objects for the current selection (works in all modes)"}],configRules:[{id:"selection/range-dblclick",severity:"warn",message:'"triggerOn: \'dblclick\'" has no effect when mode is "range".\n → Range selection uses drag interaction (mousedown → mousemove), not click events.\n → The "triggerOn" option only affects "cell" and "row" selection modes.',check:e=>"range"===e.mode&&"dblclick"===e.triggerOn}]};name="selection";styles='@layer tbw-plugins{tbw-grid.selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}tbw-grid:has(.selection){-webkit-user-select:none;user-select:none}tbw-grid .data-grid-row.row-focus{background-color:var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%));outline:none;position:relative}tbw-grid .data-grid-row.row-focus:after{content:"";position:absolute;inset:0;pointer-events:none;border-width:0;border-style:var(--tbw-selection-border-style, var(--tbw-border-style));border-color:var(--tbw-range-border-color, var(--tbw-color-accent));border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width));border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width));z-index:1}tbw-grid .data-grid-row.row-focus+.data-grid-row.row-focus:after{border-top-width:0}tbw-grid .data-grid-row.row-focus:has(+.data-grid-row.row-focus):after{border-bottom-width:0}tbw-grid[data-selection-mode=row] .cell-focus,tbw-grid[data-selection-mode=row] .row-focus,tbw-grid[data-selection-mode=range] .cell-focus{outline:none}tbw-grid .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg);position:relative}tbw-grid .data-grid-row>.cell.selected:after{content:"";position:absolute;inset:0;pointer-events:none;border:0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1}tbw-grid .data-grid-row>.cell.selected.top:after{border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.bottom:after{border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.first:after{border-left-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.last:after{border-right-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row[data-selectable=false].row-focus{background-color:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row>.cell[data-selectable=false].selected{background-color:var(--tbw-selection-warning-bg, rgba(from var(--tbw-color-error) r g b / 50%))}tbw-grid .tbw-selection-summary{font-size:var(--tbw-font-size-sm, .8125rem);color:var(--tbw-color-fg-muted);white-space:nowrap}tbw-grid .data-grid-row>.cell[data-field=__tbw_checkbox],tbw-grid .header-row>.cell[data-field=__tbw_checkbox]{text-align:center;cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .tbw-select-row-checkbox{pointer-events:none;margin:0;cursor:pointer}tbw-grid .tbw-checkbox-header{display:flex;justify-content:center;align-items:center;height:100%}tbw-grid .tbw-select-all-checkbox{margin:0;cursor:pointer}}';get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0}}selected=new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;selectedCell=null;lastSyncedFocusRow=-1;lastSyncedFocusCol=-1;explicitSelection=!1;isSelectionEnabled(){return!1!==this.config.enabled&&!1!==this.grid.effectiveConfig?.selectable}checkSelectable(e,t){const{isSelectable:i}=this.config;if(!i)return!0;const n=this.rows[e];if(!n)return!1;return i(n,e,void 0!==t?this.visibleColumns[t]:void 0,t)}isRowSelectable(e){return this.checkSelectable(e)}isCellSelectable(e,t){return this.checkSelectable(e,t)}attach(e){super.attach(e),this.on("filter-applied",()=>this.clearSelectionSilent()),this.on("grouping-state-change",()=>this.clearSelectionSilent()),this.on("tree-state-change",()=>this.clearSelectionSilent())}handleQuery(e){return"getSelection"===e.type?this.getSelection():"getSelectedRowIndices"===e.type?this.getSelectedRowIndices():"getSelectedRows"===e.type?this.getSelectedRows():"selectRows"===e.type?(this.selectRows(e.context),!0):void 0}detach(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.pendingKeyboardUpdate=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1}clearSelectionSilent(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedCell=null,this.lastSelected=null,this.anchor=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,this.requestAfterRender()}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{rowIndex:t,colIndex:i,originalEvent:n}=e,{mode:r,triggerOn:o="click"}=this.config;if(n.type!==o)return!1;const s=e.column,l=s&&Wt(s);if("cell"===r){if(l)return!1;if(!this.isCellSelectable(t,i))return!1;const e=this.selectedCell;return e&&e.row===t&&e.col===i||(this.selectedCell={row:t,col:i},this.emit("selection-change",this.#$i()),this.requestAfterRender()),!1}if("row"===r){if(!this.isRowSelectable(t))return!1;const e=!1!==this.config.multiSelect,i=n.shiftKey&&e,r=(n.ctrlKey||n.metaKey)&&e,o=!0===s?.meta?.checkboxColumn;if(i&&null!==this.anchor){const e=Math.min(this.anchor,t),i=Math.max(this.anchor,t);r||this.selected.clear();for(let t=e;t<=i;t++)this.isRowSelectable(t)&&this.selected.add(t)}else if(r||o&&e)this.selected.has(t)?this.selected.delete(t):this.selected.add(t),this.anchor=t;else{if(1===this.selected.size&&this.selected.has(t))return!1;this.selected.clear(),this.selected.add(t),this.anchor=t}return this.lastSelected=t,this.explicitSelection=!0,this.emit("selection-change",this.#$i()),this.requestAfterRender(),!1}if("range"===r){if(l)return!1;if(!this.isCellSelectable(t,i))return!1;const e=n.shiftKey,r=(n.ctrlKey||n.metaKey)&&!1!==this.config.multiSelect;if(e&&this.cellAnchor){const e=Ui(this.cellAnchor,{row:t,col:i}),n=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(n&&ji(n,e))return!1;r?this.ranges.length>0?this.ranges[this.ranges.length-1]=e:this.ranges.push(e):this.ranges=[e],this.activeRange=e}else if(r){const e={startRow:t,startCol:i,endRow:t,endCol:i};this.ranges.push(e),this.activeRange=e,this.cellAnchor={row:t,col:i}}else{const e={startRow:t,startCol:i,endRow:t,endCol:i};if(1===this.ranges.length&&ji(this.ranges[0],e))return!1;this.ranges=[e],this.activeRange=e,this.cellAnchor={row:t,col:i}}return this.emit("selection-change",this.#$i()),this.requestAfterRender(),!1}return!1}onKeyDown(e){if(!this.isSelectionEnabled())return!1;const{mode:t}=this.config,i=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"].includes(e.key);if("Escape"===e.key){return!this.grid.query("isEditing").some(Boolean)&&("cell"===t?this.selectedCell=null:"row"===t?(this.selected.clear(),this.anchor=null):"range"===t&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#$i()),this.requestAfterRender(),!0)}if("cell"===t&&i)return queueMicrotask(()=>{const e=this.grid._focusRow,t=this.grid._focusCol;this.isCellSelectable(e,t)?this.selectedCell={row:e,col:t}:this.selectedCell=null,this.emit("selection-change",this.#$i()),this.requestAfterRender()}),!1;if("row"===t){const t=!1!==this.config.multiSelect;if("ArrowUp"===e.key||"ArrowDown"===e.key){const i=e.shiftKey&&t;return i&&null===this.anchor&&(this.anchor=this.grid._focusRow),queueMicrotask(()=>{const e=this.grid._focusRow;if(i&&null!==this.anchor){this.selected.clear();const t=Math.min(this.anchor,e),i=Math.max(this.anchor,e);for(let e=t;e<=i;e++)this.isRowSelectable(e)&&this.selected.add(e)}else this.isRowSelectable(e)?(this.selected.clear(),this.selected.add(e),this.anchor=e):this.selected.clear();this.lastSelected=e,this.explicitSelection=!0,this.emit("selection-change",this.#$i()),this.requestAfterRender()}),!1}if(t&&"a"===e.key&&(e.ctrlKey||e.metaKey)){return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}}if("range"===t&&i){const t="Tab"===e.key,i=e.shiftKey&&!t;return i&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:i},queueMicrotask(()=>this.requestAfterRender()),!1}if("range"===t&&!1!==this.config.multiSelect&&"a"===e.key&&(e.ctrlKey||e.metaKey)){return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}return!1}onCellMouseDown(e){if(!this.isSelectionEnabled())return;if("range"!==this.config.mode)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;if(e.column&&Wt(e.column))return;if(!this.isCellSelectable(e.rowIndex,e.colIndex))return;if(e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const t=e.rowIndex,i=e.colIndex,n=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&!1!==this.config.multiSelect,r={startRow:t,startCol:i,endRow:t,endCol:i};return!n&&1===this.ranges.length&&ji(this.ranges[0],r)?(this.cellAnchor={row:t,col:i},!0):(this.cellAnchor={row:t,col:i},n||(this.ranges=[]),this.ranges.push(r),this.activeRange=r,this.emit("selection-change",this.#$i()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled())return;if("range"!==this.config.mode)return;if(!this.isDragging||!this.cellAnchor)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;let t=e.colIndex;const i=this.visibleColumns[t];if(i&&Wt(i)){const e=this.visibleColumns.findIndex(e=>!Wt(e));e>=0&&(t=e)}const n=Ui(this.cellAnchor,{row:e.rowIndex,col:t}),r=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return r&&ji(r,n)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=n:this.ranges.push(n),this.activeRange=n,this.emit("selection-change",this.#$i()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&"range"===this.config.mode)return this.isDragging?(this.isDragging=!1,!0):void 0}processColumns(e){if(this.config.checkbox&&"row"===this.config.mode){if(e.some(e=>e.field===Yi))return e;const t=this.#Bi(),i=e.findIndex(Bt),n=i>=0?i+1:0;return[...e.slice(0,n),t,...e.slice(n)]}return e}#Bi(){return{field:Yi,header:"",width:32,resizable:!1,sortable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0,checkboxColumn:!0},headerRenderer:()=>{const e=document.createElement("div");if(e.className="tbw-checkbox-header",!1===this.config.multiSelect)return e;const t=document.createElement("input");return t.type="checkbox",t.className="tbw-select-all-checkbox",t.addEventListener("click",e=>{e.stopPropagation(),e.target.checked?this.selectAll():this.clearSelection()}),e.appendChild(t),e},renderer:e=>{const t=document.createElement("input");t.type="checkbox",t.className="tbw-select-row-checkbox";const i=e.cellEl;if(i){const e=parseInt(i.getAttribute("data-row")??"-1",10);e>=0&&(t.checked=this.selected.has(e))}return t}}}#Wi(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const t=e.closest(".cell"),i=t?T(t):-1;i>=0&&(e.checked=this.selected.has(i))});const t=e.querySelector(".tbw-select-all-checkbox");if(t){const e=this.rows.length;let i=0;if(this.config.isSelectable)for(let t=0;t<e;t++)this.isRowSelectable(t)&&i++;else i=e;const n=i>0&&this.selected.size>=i,r=this.selected.size>0;t.checked=n,t.indeterminate=r&&!n}}#Ki(e){const t=this.grid._focusRow,i=this.grid._focusCol;if("row"===e){if(this.explicitSelection)return this.explicitSelection=!1,void(this.lastSyncedFocusRow=t);t!==this.lastSyncedFocusRow&&(this.lastSyncedFocusRow=t,this.isRowSelectable(t)&&(this.selected.has(t)&&1===this.selected.size||(this.selected.clear(),this.selected.add(t),this.lastSelected=t,this.anchor=t,this.emit("selection-change",this.#$i()))))}if("cell"===e){if(this.explicitSelection)return this.explicitSelection=!1,this.lastSyncedFocusRow=t,void(this.lastSyncedFocusCol=i);if((t!==this.lastSyncedFocusRow||i!==this.lastSyncedFocusCol)&&(this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=i,this.isCellSelectable(t,i))){const e=this.selectedCell;e&&e.row===t&&e.col===i||(this.selectedCell={row:t,col:i},this.emit("selection-change",this.#$i()))}}}#Ui(){const e=this.gridElement;if(!e)return;const{mode:t}=this.config,i=!!this.config.isSelectable;e.querySelectorAll(".cell").forEach(e=>{e.classList.remove("selected","top","bottom","first","last"),i&&e.removeAttribute("data-selectable")});const n=e.querySelectorAll(".data-grid-row");if(n.forEach(e=>{e.classList.remove("selected","row-focus"),i&&e.removeAttribute("data-selectable")}),"row"===t&&(L(e),n.forEach(e=>{const t=T(e.querySelector(".cell[data-row]"));t>=0&&(i&&!this.isRowSelectable(t)&&e.setAttribute("data-selectable","false"),this.selected.has(t)&&e.classList.add("selected","row-focus"))}),this.config.checkbox&&this.#Wi(e)),("cell"===t||"range"===t)&&i){e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),i=parseInt(e.getAttribute("data-col")??"-1",10);t>=0&&i>=0&&(this.isCellSelectable(t,i)||e.setAttribute("data-selectable","false"))})}if("range"===t&&this.ranges.length>0){L(e);const t=this.ranges.map(Vi),i=(e,i)=>{for(const n of t)if(e>=n.startRow&&e<=n.endRow&&i>=n.startCol&&i<=n.endCol)return!0;return!1};e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),n=parseInt(e.getAttribute("data-col")??"-1",10);if(t>=0&&n>=0){const r=this.visibleColumns[n];if(r&&Wt(r))return;i(t,n)&&(e.classList.add("selected"),i(t-1,n)||e.classList.add("top"),i(t+1,n)||e.classList.add("bottom"),i(t,n-1)||e.classList.add("first"),i(t,n+1)||e.classList.add("last"))}})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.children[0],{mode:i}=this.config;if(this.pendingKeyboardUpdate&&"range"===i){const{shiftKey:e}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const t=this.grid._focusRow,i=this.grid._focusCol;if(e&&this.cellAnchor){const e=Ui(this.cellAnchor,{row:t,col:i});this.ranges=[e],this.activeRange=e}else e||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:t,col:i});this.emit("selection-change",this.#$i())}this.#Ki(i),this.grid.setAttribute("data-selection-mode",i),t&&t.classList.toggle("selecting",this.isDragging),this.#Ui()}onScrollRender(){this.isSelectionEnabled()&&this.#Ui()}getSelection(){return{mode:this.config.mode,ranges:this.#$i().ranges,anchor:this.cellAnchor}}getSelectedCells(){return function(e){const t=new Map;for(const i of e)for(const e of Ki(i))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return Wi(e,t,this.ranges)}selectAll(){const{mode:e,multiSelect:t}=this.config;if(!1!==t)if("row"===e){this.selected.clear();for(let e=0;e<this.rows.length;e++)this.isRowSelectable(e)&&this.selected.add(e);this.explicitSelection=!0,this.emit("selection-change",this.#$i()),this.requestAfterRender()}else if("range"===e){const e=this.rows.length,t=this.columns.length;if(e>0&&t>0){const i={startRow:0,startCol:0,endRow:e-1,endCol:t-1};this.ranges=[i],this.activeRange=i,this.emit("selection-change",this.#$i()),this.requestAfterRender()}}}selectRows(e){if("row"!==this.config.mode)return;const t=!1===this.config.multiSelect&&e.length>1?[e[e.length-1]]:e;this.selected.clear();for(const i of t)i>=0&&i<this.rows.length&&this.isRowSelectable(i)&&this.selected.add(i);this.anchor=t.length>0?t[t.length-1]:null,this.explicitSelection=!0,this.emit("selection-change",this.#$i()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const{mode:e}=this.config,t=this.rows;if("row"===e)return this.getSelectedRowIndices().filter(e=>e>=0&&e<t.length).map(e=>t[e]);if("cell"===e&&this.selectedCell){const{row:e}=this.selectedCell;return e>=0&&e<t.length?[t[e]]:[]}if("range"===e&&this.ranges.length>0){const e=new Set;for(const i of this.ranges){const n=Math.max(0,Math.min(i.startRow,i.endRow)),r=Math.min(t.length-1,Math.max(i.startRow,i.endRow));for(let t=n;t<=r;t++)e.add(t)}return[...e].sort((e,t)=>e-t).map(e=>t[e])}return[]}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.emit("selection-change",{mode:this.config.mode,ranges:[]}),this.requestAfterRender()}setRanges(e){this.ranges=e.map(e=>({startRow:e.from.row,startCol:e.from.col,endRow:e.to.row,endCol:e.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",{mode:this.config.mode,ranges:Bi(this.ranges)}),this.requestAfterRender()}#$i(){return function(e,t,i){if("cell"===e&&t.selectedCell)return{mode:e,ranges:[{from:{row:t.selectedCell.row,col:t.selectedCell.col},to:{row:t.selectedCell.row,col:t.selectedCell.col}}]};if("row"===e&&t.selected.size>0){const n=[...t.selected].sort((e,t)=>e-t),r=[];let o=n[0],s=o;for(let e=1;e<n.length;e++)n[e]===s+1?s=n[e]:(r.push({from:{row:o,col:0},to:{row:s,col:i-1}}),o=n[e],s=o);return r.push({from:{row:o,col:0},to:{row:s,col:i-1}}),{mode:e,ranges:r}}return"range"===e&&t.ranges.length>0?{mode:e,ranges:Bi(t.ranges)}:{mode:e,ranges:[]}}(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}},e.ServerSidePlugin=class extends rt{name="serverSide";get defaultConfig(){return{pageSize:100,cacheBlockSize:100,maxConcurrentRequests:2}}dataSource=null;totalRowCount=0;loadedBlocks=new Map;loadingBlocks=new Set;lastRequestId=0;scrollDebounceTimer;detach(){this.dataSource=null,this.totalRowCount=0,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.lastRequestId=0,this.scrollDebounceTimer&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=void 0)}loadRequiredBlocks(){if(!this.dataSource)return;const e=this.grid,t=this.config.cacheBlockSize??100,i={startRow:e._virtualization.start,endRow:e._virtualization.end},n=function(e,t,i){const n=Xi(e,i),r=Xi(t-1,i),o=[];for(let s=n;s<=r;s++)o.push(s);return o}(i.startRow,i.endRow,t);for(const r of n)if(!this.loadedBlocks.has(r)&&!this.loadingBlocks.has(r)){if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2))break;this.loadingBlocks.add(r),Zi(this.dataSource,r,t,{}).then(e=>{this.loadedBlocks.set(r,e.rows),this.totalRowCount=e.totalRowCount,this.loadingBlocks.delete(r),this.requestRender(),this.loadRequiredBlocks()}).catch(()=>{this.loadingBlocks.delete(r)})}}processRows(e){if(!this.dataSource)return[...e];const t=[];for(let i=0;i<this.totalRowCount;i++){const e=Qi(i,this.config.cacheBlockSize??100,this.loadedBlocks);t.push(e??{__loading:!0,__index:i})}return t}onScroll(e){this.dataSource&&(this.loadRequiredBlocks(),this.scrollDebounceTimer&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.loadRequiredBlocks()},100))}setDataSource(e){this.dataSource=e,this.loadedBlocks.clear(),this.loadingBlocks.clear();Zi(e,0,this.config.cacheBlockSize??100,{}).then(e=>{this.loadedBlocks.set(0,e.rows),this.totalRowCount=e.totalRowCount,this.requestRender()})}refresh(){this.dataSource&&(this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.requestRender())}purgeCache(){this.loadedBlocks.clear()}getTotalRowCount(){return this.totalRowCount}isRowLoaded(e){const t=Xi(e,this.config.cacheBlockSize??100);return this.loadedBlocks.has(t)}getLoadedBlockCount(){return this.loadedBlocks.size}},e.TreePlugin=class extends rt{static manifest={events:[{type:"tree-state-change",description:"Emitted when tree expansion state changes (toggle, expand all, collapse all)"}],queries:[{type:"canMoveRow",description:"Returns false for rows with children (parent nodes cannot be reordered)"}]};name="tree";styles="@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-inline-end:none!important;padding:0;display:flex;align-items:center;justify-content:flex-start}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1 / 3}tbw-grid .tree-cell-wrapper{display:inline-flex;align-items:center;padding-inline-start:calc(var(--tbw-tree-depth, 0) * var(--tbw-tree-indent-width, var(--tbw-tree-toggle-size, 1.25em)))}tbw-grid .tree-expander{display:flex;align-items:center;justify-content:flex-start;width:100%;height:100%;box-sizing:border-box}tbw-grid .tree-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-tree-toggle-size, 1.25em);height:var(--tbw-tree-toggle-size, 1.25em);flex-shrink:0}tbw-grid .tree-toggle:hover{color:var(--tbw-tree-accent, var(--tbw-color-accent))}tbw-grid .tree-spacer{width:var(--tbw-tree-toggle-size, 1.25em);display:inline-block;flex-shrink:0}tbw-grid .data-grid-row.tbw-tree-slide-in{animation:tbw-tree-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .data-grid-row.tbw-tree-fade-in{animation:tbw-tree-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-tree-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}@keyframes tbw-tree-fade-in{0%{opacity:0}to{opacity:1}}}";get defaultConfig(){return{childrenField:"children",autoDetect:!0,defaultExpanded:!1,indentWidth:20,showExpandIcons:!0,animation:"slide"}}expandedKeys=new Set;initialExpansionDone=!1;flattenedRows=[];rowKeyMap=new Map;previousVisibleKeys=new Set;keysToAnimate=new Set;sortState=null;detach(){this.expandedKeys.clear(),this.initialExpansionDone=!1,this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.sortState=null}handleQuery(e){if("canMoveRow"===e.type){const t=e.context,i=this.config.childrenField??"children",n=t?.[i];if(Array.isArray(n)&&n.length>0)return!1}}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detect(e){if(!this.config.autoDetect)return!1;const t=e,i=this.config.childrenField??function(e){if(!Array.isArray(e)||0===e.length)return null;const t=["children","items","nodes","subRows","nested"];for(const i of e)if(i&&"object"==typeof i)for(const e of t){const t=i[e];if(Array.isArray(t)&&t.length>0)return e}return null}(t)??"children";return on(t,i)}processRows(e){const t=e;if(!on(t,this.config.childrenField??"children"))return this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),[...e];let i=this.withStableKeys(t);this.sortState&&(i=this.sortTree(i,this.sortState.field,this.sortState.direction)),this.config.defaultExpanded&&!this.initialExpansionDone&&(this.expandedKeys=tn(i,this.config),this.initialExpansionDone=!0),this.flattenedRows=this.flattenTree(i,this.expandedKeys),this.rowKeyMap.clear(),this.keysToAnimate.clear();const n=new Set;for(const r of this.flattenedRows)this.rowKeyMap.set(r.key,r),n.add(r.key),!this.previousVisibleKeys.has(r.key)&&r.depth>0&&this.keysToAnimate.add(r.key);return this.previousVisibleKeys=n,this.flattenedRows.map(e=>({...e.data,__treeKey:e.key,__treeDepth:e.depth,__treeHasChildren:e.hasChildren,__treeExpanded:e.isExpanded}))}withStableKeys(e,t=null){const i=this.config.childrenField??"children";return e.map((e,n)=>{const r=e.__stableKey,o=void 0!==e.id?String(e.id):r??(t?`${t}-${n}`:String(n)),s=e[i],l=Array.isArray(s)&&s.length>0;return{...e,__stableKey:o,...l?{[i]:this.withStableKeys(s,o)}:{}}})}flattenTree(e,t,i=0){const n=this.config.childrenField??"children",r=[];for(const o of e){const e=o.__stableKey??String(o.id??"?"),s=o[n],l=Array.isArray(s)&&s.length>0,a=t.has(e);r.push({key:e,data:o,depth:i,hasChildren:l,isExpanded:a,parentKey:i>0&&e.substring(0,e.lastIndexOf("-"))||null}),l&&a&&r.push(...this.flattenTree(s,t,i+1))}return r}sortTree(e,t,i){const n=this.config.childrenField??"children";return[...e].sort((e,n)=>{const r=e[t],o=n[t];return null==r&&null==o?0:null==r?-1:null==o?1:r>o?i:r<o?-i:0}).map(e=>{const r=e[n];return Array.isArray(r)&&r.length>0?{...e,[n]:this.sortTree(r,t,i)}:e})}processColumns(e){if(0===this.flattenedRows.length)return[...e];const t=[...e];if(0===t.length)return t;const i=t[0],n=i.viewRenderer,r=()=>this.config,o=this.setIcon.bind(this),s=this.resolveIcon.bind(this);return t[0]={...i,viewRenderer:e=>{const{row:t,value:i}=e,{showExpandIcons:l=!0,indentWidth:a}=r(),d=t,c=d.__treeDepth??0,h=document.createElement("span");if(h.className="tree-cell-wrapper",h.style.setProperty("--tbw-tree-depth",String(c)),void 0!==a&&h.style.setProperty("--tbw-tree-indent-width",`${a}px`),l)if(d.__treeHasChildren){const e=document.createElement("span");e.className="tree-toggle"+(d.__treeExpanded?" expanded":""),o(e,s(d.__treeExpanded?"collapse":"expand")),e.setAttribute("data-tree-key",String(d.__treeKey??"")),h.appendChild(e)}else{const e=document.createElement("span");e.className="tree-spacer",h.appendChild(e)}const u=document.createElement("span");if(u.className="tree-content",n){const t=n(e);t instanceof Node?u.appendChild(t):"string"==typeof t&&(u.innerHTML=t)}else u.textContent=null!=i?String(i):"";return h.appendChild(u),h}},t}onCellClick(e){const t=e.originalEvent?.target;if(!t?.classList.contains("tree-toggle"))return!1;const i=t.getAttribute("data-tree-key");if(!i)return!1;const n=this.rowKeyMap.get(i);return!!n&&(this.expandedKeys=en(this.expandedKeys,i),this.emit("tree-expand",{key:i,row:n.data,expanded:this.expandedKeys.has(i),depth:n.depth}),this.requestRender(),!0)}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusRow,i=this.flattenedRows[t];return i?.hasChildren?(e.preventDefault(),this.expandedKeys=en(this.expandedKeys,i.key),this.emit("tree-expand",{key:i.key,row:i.data,expanded:this.expandedKeys.has(i.key),depth:i.depth}),this.requestRenderWithFocus(),!0):void 0}onHeaderClick(e){if(0===this.flattenedRows.length||!e.column.sortable)return!1;const{field:t}=e.column;this.sortState&&this.sortState.field===t?1===this.sortState.direction?this.sortState={field:t,direction:-1}:this.sortState=null:this.sortState={field:t,direction:1};const i=this.grid;return void 0!==i._sortState&&(i._sortState=this.sortState?{...this.sortState}:null),this.emit("sort-change",{field:t,direction:this.sortState?.direction??0}),this.requestRender(),!0}afterRender(){const e=this.animationStyle;if(!1===e||0===this.keysToAnimate.size)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const i="fade"===e?"tbw-tree-fade-in":"tbw-tree-slide-in";for(const n of t.querySelectorAll(".data-grid-row")){const e=n.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,r=this.flattenedRows[t]?.key;r&&this.keysToAnimate.has(r)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}expand(e){this.expandedKeys.add(e),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}toggle(e){this.expandedKeys=en(this.expandedKeys,e),this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}expandAll(){this.expandedKeys=tn(this.rows,this.config),this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}getExpandedKeys(){return[...this.expandedKeys]}getFlattenedRows(){return[...this.flattenedRows]}getRowByKey(e){return this.rowKeyMap.get(e)?.data}expandToKey(e){this.expandedKeys=rn(this.rows,e,this.config,this.expandedKeys),this.requestRender()}},e.UndoRedoPlugin=class extends rt{static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];attach(e){super.attach(e),this.on("cell-edit-committed",e=>{this.recordEdit(e.rowIndex,e.field,e.oldValue,e.newValue)})}detach(){this.undoStack=[],this.redoStack=[]}onKeyDown(e){const t=(e.ctrlKey||e.metaKey)&&"z"===e.key&&!e.shiftKey,i=(e.ctrlKey||e.metaKey)&&("y"===e.key||"z"===e.key&&e.shiftKey);if(t){const e=sn({undoStack:this.undoStack,redoStack:this.redoStack});if(e.action){const t=this.rows;t[e.action.rowIndex]&&(t[e.action.rowIndex][e.action.field]=e.action.oldValue),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.emit("undo",{action:e.action,type:"undo"}),this.requestRender()}return!0}if(i){const e=ln({undoStack:this.undoStack,redoStack:this.redoStack});if(e.action){const t=this.rows;t[e.action.rowIndex]&&(t[e.action.rowIndex][e.action.field]=e.action.newValue),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.emit("redo",{action:e.action,type:"redo"}),this.requestRender()}return!0}return!1}recordEdit(e,t,i,n){const r=function(e,t,i,n){return{type:"cell-edit",rowIndex:e,field:t,oldValue:i,newValue:n,timestamp:Date.now()}}(e,t,i,n),o=function(e,t,i){const n=[...e.undoStack,t];for(;n.length>i;)n.shift();return{undoStack:n,redoStack:[]}}({undoStack:this.undoStack,redoStack:this.redoStack},r,this.config.maxHistorySize??100);this.undoStack=o.undoStack,this.redoStack=o.redoStack}undo(){const e=sn({undoStack:this.undoStack,redoStack:this.redoStack});if(e.action){const t=this.rows;t[e.action.rowIndex]&&(t[e.action.rowIndex][e.action.field]=e.action.oldValue),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.requestRender()}return e.action}redo(){const e=ln({undoStack:this.undoStack,redoStack:this.redoStack});if(e.action){const t=this.rows;t[e.action.rowIndex]&&(t[e.action.rowIndex][e.action.field]=e.action.newValue),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.requestRender()}return e.action}canUndo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.undoStack.length>0}canRedo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.redoStack.length>0}clearHistory(){const e={undoStack:[],redoStack:[]};this.undoStack=e.undoStack,this.redoStack=e.redoStack}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}},e.VisibilityPlugin=dn,e.builtInSort=Q,e.createGrid=function(e){const t=document.createElement("tbw-grid");return e&&(t.gridConfig=e),t},e.defaultComparator=Z,e.defaultEditorFor=Mt,e.defaultPasteHandler=ut,e.getUniqueValuesBatch=Vt,e.printGridIsolated=qi,e.queryGrid=function(e,t=document){return t.querySelector(e)},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
187
2
  //# sourceMappingURL=grid.all.umd.js.map