@toolbox-web/grid 1.26.1 → 1.27.0
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.
- package/all.js +2 -2
- package/all.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/lib/core/grid.d.ts +64 -1
- package/lib/core/internal/diagnostics.d.ts +4 -3
- package/lib/core/internal/row-manager.d.ts +3 -1
- package/lib/core/plugin/base-plugin.d.ts +2 -2
- package/lib/core/types.d.ts +59 -3
- package/lib/features/registry.js.map +1 -1
- package/lib/plugins/clipboard/ClipboardPlugin.d.ts +1 -1
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/lib/plugins/column-virtualization/index.js.map +1 -1
- package/lib/plugins/context-menu/ContextMenuPlugin.d.ts +24 -5
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/editing/EditingPlugin.d.ts +1 -1
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/export/ExportPlugin.d.ts +1 -1
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/filtering/index.d.ts +2 -2
- package/lib/plugins/filtering/index.js +1 -1
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/grouping-columns/GroupingColumnsPlugin.d.ts +2 -2
- package/lib/plugins/grouping-columns/grouping-columns.d.ts +18 -3
- package/lib/plugins/grouping-columns/index.d.ts +0 -1
- package/lib/plugins/grouping-columns/index.js +1 -1
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-columns/types.d.ts +1 -7
- package/lib/plugins/grouping-rows/index.d.ts +2 -1
- package/lib/plugins/grouping-rows/index.js +1 -1
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/master-detail/MasterDetailPlugin.d.ts +2 -0
- package/lib/plugins/master-detail/index.js +1 -1
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/master-detail/types.d.ts +20 -1
- package/lib/plugins/multi-sort/index.js.map +1 -1
- package/lib/plugins/pinned-columns/PinnedColumnsPlugin.d.ts +8 -1
- package/lib/plugins/pinned-columns/index.js +1 -1
- package/lib/plugins/pinned-columns/index.js.map +1 -1
- package/lib/plugins/pinned-columns/pinned-columns.d.ts +11 -1
- package/lib/plugins/pinned-rows/index.d.ts +1 -1
- package/lib/plugins/pinned-rows/index.js +1 -1
- package/lib/plugins/pinned-rows/index.js.map +1 -1
- package/lib/plugins/pinned-rows/types.d.ts +10 -3
- package/lib/plugins/pivot/PivotPlugin.d.ts +107 -1
- package/lib/plugins/pivot/index.d.ts +2 -1
- package/lib/plugins/pivot/index.js +1 -1
- package/lib/plugins/pivot/index.js.map +1 -1
- package/lib/plugins/print/index.js.map +1 -1
- package/lib/plugins/print/types.d.ts +0 -3
- package/lib/plugins/reorder-columns/ReorderPlugin.d.ts +19 -2
- package/lib/plugins/reorder-columns/index.js +1 -1
- package/lib/plugins/reorder-columns/index.js.map +1 -1
- package/lib/plugins/reorder-rows/index.d.ts +1 -1
- package/lib/plugins/reorder-rows/index.js.map +1 -1
- package/lib/plugins/responsive/ResponsivePlugin.d.ts +1 -1
- package/lib/plugins/responsive/index.js +1 -1
- package/lib/plugins/responsive/index.js.map +1 -1
- package/lib/plugins/selection/SelectionPlugin.d.ts +1 -1
- package/lib/plugins/selection/index.js +1 -1
- package/lib/plugins/selection/index.js.map +1 -1
- package/lib/plugins/selection/types.d.ts +3 -3
- package/lib/plugins/server-side/ServerSidePlugin.d.ts +6 -1
- package/lib/plugins/server-side/index.js +1 -1
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/tree/TreePlugin.d.ts +116 -0
- package/lib/plugins/tree/index.d.ts +1 -1
- package/lib/plugins/tree/index.js +1 -1
- package/lib/plugins/tree/index.js.map +1 -1
- package/lib/plugins/tree/types.d.ts +16 -1
- package/lib/plugins/undo-redo/UndoRedoPlugin.d.ts +1 -1
- package/lib/plugins/undo-redo/index.js.map +1 -1
- package/lib/plugins/undo-redo/types.d.ts +15 -3
- package/lib/plugins/visibility/VisibilityPlugin.d.ts +18 -5
- package/lib/plugins/visibility/index.js +1 -1
- package/lib/plugins/visibility/index.js.map +1 -1
- package/package.json +1 -1
- package/public.d.ts +2 -4
- package/themes/dg-theme-material.css +16 -4
- package/umd/grid.all.umd.js +1 -1
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +1 -1
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/clipboard.umd.js.map +1 -1
- package/umd/plugins/context-menu.umd.js.map +1 -1
- package/umd/plugins/editing.umd.js.map +1 -1
- package/umd/plugins/export.umd.js.map +1 -1
- package/umd/plugins/filtering.umd.js +1 -1
- package/umd/plugins/filtering.umd.js.map +1 -1
- package/umd/plugins/grouping-columns.umd.js +1 -1
- package/umd/plugins/grouping-columns.umd.js.map +1 -1
- package/umd/plugins/grouping-rows.umd.js +1 -1
- package/umd/plugins/grouping-rows.umd.js.map +1 -1
- package/umd/plugins/master-detail.umd.js +1 -1
- package/umd/plugins/master-detail.umd.js.map +1 -1
- package/umd/plugins/pinned-columns.umd.js +1 -1
- package/umd/plugins/pinned-columns.umd.js.map +1 -1
- package/umd/plugins/pinned-rows.umd.js +1 -1
- package/umd/plugins/pinned-rows.umd.js.map +1 -1
- package/umd/plugins/pivot.umd.js +1 -1
- package/umd/plugins/pivot.umd.js.map +1 -1
- package/umd/plugins/reorder-columns.umd.js +1 -1
- package/umd/plugins/reorder-columns.umd.js.map +1 -1
- package/umd/plugins/responsive.umd.js +1 -1
- package/umd/plugins/responsive.umd.js.map +1 -1
- package/umd/plugins/selection.umd.js +1 -1
- package/umd/plugins/selection.umd.js.map +1 -1
- package/umd/plugins/server-side.umd.js +1 -1
- package/umd/plugins/server-side.umd.js.map +1 -1
- package/umd/plugins/tree.umd.js +1 -1
- package/umd/plugins/tree.umd.js.map +1 -1
- package/umd/plugins/undo-redo.umd.js.map +1 -1
- package/umd/plugins/visibility.umd.js +1 -1
- package/umd/plugins/visibility.umd.js.map +1 -1
package/umd/grid.all.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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";function t(e,t){const i=e.querySelector?.(".tbw-sr-only");i&&(i.textContent="",requestAnimationFrame(()=>{i.textContent=t}))}const i={STRETCH:"stretch",FIXED:"fixed"},n={mode:"reduced-motion",duration:200,easing:"ease-out"},r='<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>',o={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:r,filterActive:r,print:"🖨️"};function s(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}const l="TBW041",a="TBW061",d="TBW062";function c(e,t,i,n){return`${s(i,n)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}function h(e,t,i,n){throw new Error(c(e,t,i,n))}function u(e,t,i,n){console.warn(c(e,t,i,n))}function g(e,t,i,n){console.info(c(e,t,i,n))}function p(e,t,i,n){console.error(c(e,t,i,n))}function f(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 w(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 m(e){const t=e.effectiveConfig?.fitMode||e.fitMode||i.STRETCH;if(t!==i.STRETCH&&t!==i.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&&y(e),e.__didInitialAutoSize=!0}const b=/^(?:\d+(?:\.\d+)?(?:px|%|fr|em|rem|ch|vw|vh|vmin|vmax)|calc\(.+\)|min-content|max-content|minmax\(.+\)|fit-content\(.+\)|auto)$/i;function v(e,t){return"number"==typeof e?`${e}px`:(b.test(e)||u("TBW050",`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 y(e){const t=e.effectiveConfig?.fitMode||e.fitMode||i.STRETCH;e._gridTemplate=t===i.STRETCH?e._visibleColumns.map(e=>{if(null!=e.width)return v(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?v(e.width,e.field):"max-content").join(" "),e.style.setProperty("--tbw-column-template",e._gridTemplate)}const C=/{{\s*([^}]+)\s*}}/g,x="__DG_EMPTY__",R=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,E=/__(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 S=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"]),_=/^on\w+$/i,A=new Set(["href","src","action","formaction","data","srcdoc","xlink:href","poster","srcset"]),k=/^\s*(javascript|vbscript|data|blob):/i;function T(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(S.has(e)){t.push(n);continue}if("svg"===e||"http://www.w3.org/2000/svg"===n.namespaceURI){if(Array.from(n.attributes).some(e=>_.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();_.test(e)?i.push(t.name):(A.has(e)&&k.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 M(e,t){if(!e||-1===e.indexOf("{{"))return e;const i=[],n=e.replace(C,(e,n)=>{const r=function(e,t){if(e=(e||"").trim(),!e)return x;if(L.test(e))return x;if("value"===e)return null==t.value?x: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?x:String(n)}if(e.length>80)return x;if(!R.test(e)||E.test(e))return x;const i=e.match(/\./g);if(i&&i.length>1)return x;try{const i=new Function("value","row",`return (${e});`)(t.value,t.row),n=null==i?"":String(i);return L.test(n)?x:n||x}catch{return x}}(n,t);return i.push({expr:n.trim(),result:r}),r}),r=(o=n)?o.replace(new RegExp(x,"g"),"").replace(/Reflect\.[^<>{}\s]+|\bProxy\b|ownKeys\([^)]*\)/g,""):o;var o;const s=i.length&&i.every(e=>""===e.result||e.result===x);return L.test(e)||s?"":r}const L=/Reflect|Proxy|ownKeys/;function I(e){if(L.test(e.textContent||"")){for(const t of e.childNodes)t.nodeType===Node.TEXT_NODE&&L.test(t.textContent||"")&&(t.textContent="");L.test(e.textContent||"")&&(e.textContent="")}}function P(e){const t=L.test(e),i=i=>{if(t)return"";return M(e,i)};return i.__blocked=t,i}function H(e,t){return null==e&&null==t?0:null==e?-1:null==t||e>t?1:e<t?-1:0}function D(e,t,i){const n=i.find(e=>e.field===t.field),r=n?.sortComparator??H,{field:o,direction:s}=t;return[...e].sort((e,t)=>r(e[o],t[o],e,t)*s)}function z(e,i,n,r){e._rows=i,e.__rowRenderEpoch++,e._rowPool.forEach(e=>e.__epoch=-1),B(e),e.refreshVirtualWindow(!0),e.dispatchEvent(new CustomEvent("sort-change",{detail:{field:n.field,direction:r}})),t(e,`Sorted by ${n.header??n.field}, ${1===r?"ascending":"descending"}`),e.requestStateChange?.()}function F(e,i){if(e._sortState&&e._sortState.field===i.field)if(1===e._sortState.direction)O(e,i,-1);else{e._sortState=null,e.__rowRenderEpoch++,e._rowPool.forEach(e=>e.__epoch=-1),e._rows=e.__originalOrder.slice(),B(e);const n=e._headerRowEl?.querySelectorAll('[role="columnheader"].sortable');n?.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:i.field,direction:0}})),t(e,"Sort cleared"),e.requestStateChange?.()}else e._sortState||(e.__originalOrder=e._rows.slice()),O(e,i,1)}function O(e,t,i){e._sortState={field:t.field,direction:i};const n={field:t.field,direction:i},r=e._columns,o=(e.effectiveConfig?.sortHandler??D)(e._rows,n,r);o&&"function"==typeof o.then?o.then(n=>{z(e,n,t,i)}):z(e,o,t,i)}function q(e,t){return!1!==e.effectiveConfig?.sortable&&!0===t.sortable}function N(e,t){return!1!==e.effectiveConfig?.resizable&&!1!==t.resizable}function G(e,t){const i=document.createElement("span");w(i,"sort-indicator");const n=e._sortState?.field===t.field?e._sortState.direction:0,r={...o,...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?r.sortAsc:-1===n?r.sortDesc:r.sortNone),i}function $(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 W(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)||F(e,t)}),n.addEventListener("keydown",i=>{if("Enter"===i.key||" "===i.key){if(i.preventDefault(),e._dispatchHeaderClick?.(i,t,n))return;F(e,t)}})}function B(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",w(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,s=e._sortState?.field===i.field?e._sortState.direction:0,l=1===s?"asc":-1===s?"desc":null;if(i.headerRenderer){const t={column:i,value:o,sortState:l,filterActive:!1,cellEl:r,renderSortIcon:()=>q(e,i)?G(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=T(t);i.firstChild;)e.appendChild(i.firstChild)}else t instanceof Node&&e.appendChild(t)}(r,s),q(e,i)&&W(e,i,0,r),N(e,i)&&(r.classList.add("resizable"),r.appendChild($(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=T(s):s instanceof Node&&l.appendChild(s),r.appendChild(l),q(e,i)&&(W(e,i,0,r),r.appendChild(G(e,i))),N(e,i)&&(r.classList.add("resizable"),r.appendChild($(e,n,r)))}else if(i.__headerTemplate)Array.from(i.__headerTemplate.childNodes).forEach(e=>r.appendChild(e.cloneNode(!0))),q(e,i)&&(W(e,i,0,r),r.appendChild(G(e,i))),N(e,i)&&(r.classList.add("resizable"),r.appendChild($(e,n,r)));else{const t=document.createElement("span");t.textContent=o,r.appendChild(t),q(e,i)&&(W(e,i,0,r),r.appendChild(G(e,i))),N(e,i)&&(r.classList.add("resizable"),r.appendChild($(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")))}function V(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}}var K=(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))(K||{});class U{#e;#t=0;#i=0;#n=null;#r=null;#o=null;#s=!1;constructor(e){this.#e=e}requestPhase(e,t){e>this.#t&&(this.#t=e),0===this.#i&&(this.#l(),this.#i=requestAnimationFrame(()=>this.#a()))}whenReady(){return this.#n?this.#n:Promise.resolve()}setInitialReadyResolver(e){this.#o=e}cancel(){0!==this.#i&&(cancelAnimationFrame(this.#i),this.#i=0),this.#t=0,this.#r&&(this.#r(),this.#r=null,this.#n=null)}get isPending(){return 0!==this.#t}get pendingPhase(){return this.#t}#l(){this.#n||(this.#n=new Promise(e=>{this.#r=e}))}#a(){if(this.#i=0,!this.#e._schedulerIsConnected)return this.#t=0,void(this.#r&&(this.#r(),this.#r=null,this.#n=null));const e=this.#t;this.#t=0,e>=5&&this.#e._schedulerMergeConfig(),e>=4&&this.#e._schedulerProcessRows(),e>=5&&(this.#e._schedulerProcessColumns(),this.#e._schedulerUpdateTemplate()),e>=3&&this.#e._schedulerRenderHeader(),e>=2&&this.#e.refreshVirtualWindow(!0,!0),e>=1&&this.#e._schedulerAfterRender(),!this.#s&&this.#o&&(this.#s=!0,this.#o()),this.#r&&(this.#r(),this.#r=null,this.#n=null)}}class j{#d;#c;#h;#u;#g;#p={};#f={};#w=!0;#m=[];#b;#v;#y;#C;#e;#x;constructor(e){this.#e=e}get original(){return this.#p}get effective(){return this.#f}get columns(){return this.#f.columns??[]}set columns(e){this.#f.columns=e}get lightDomColumnsCache(){return this.#u}set lightDomColumnsCache(e){this.#u=e}get originalColumnNodes(){return this.#g}set originalColumnNodes(e){this.#g=e}get lightDomTitle(){return this.#x}set lightDomTitle(e){this.#x=e}get initialColumnState(){return this.#C}set initialColumnState(e){this.#C=e}get sourcesChanged(){return this.#w}markSourcesChanged(){this.#w=!0}setGridConfig(e){this.#d=e,this.#w=!0,this.#u=void 0}getGridConfig(){return this.#d}setColumns(e){this.#c=e,this.#w=!0}getColumns(){return this.#c}setFitMode(e){this.#h=e,this.#w=!0}getFitMode(){return this.#h}merge(){const e=(this.#f.columns?.length??0)>0;if(!this.#w&&e)return;const t=this.#R();this.#w=!1,this.#p=t,Object.freeze(this.#p),this.#p.columns&&Object.freeze(this.#p.columns),this.#f=this.#E(this.#p),this.#S()}#E(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}#S(){const e=this.#f;if(this.#_(),"number"==typeof e.rowHeight&&e.rowHeight>0&&(this.#e._virtualization.rowHeight=e.rowHeight),"fixed"===e.fitMode){this.columns.forEach(e=>{null==e.width&&(e.width=80)})}this.#e._applyAnimationConfig(e)}#_(){const e=this.#f.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))}}#R(){const e=this.#d?{...this.#d}:{},t=Array.isArray(e.columns)?[...e.columns]:[],i=(this.#u??[]).map(e=>({...e}));let n=f(t,i);this.#c&&this.#c.length&&(n=f(this.#c,i));const r=this.#e.sourceRows;if(0===n.length&&r.length){n=V(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=P(e.__viewTemplate.innerHTML)),e.__editorTemplate&&!e.__compiledEditor&&(e.__compiledEditor=P(e.__editorTemplate.innerHTML))}),e.columns=n),this.#h&&(e.fitMode=this.#h),e.fitMode||(e.fitMode="stretch"),this.#A(e),e.columnState&&!this.#C&&(this.#C=e.columnState),e}#A(e){e.shell=e.shell?{...e.shell}:{},e.shell.header=e.shell.header?{...e.shell.header}:{};const t=this.#e._shellState.lightDomTitle;t&&(this.#x=t),this.#x&&!e.shell.header.title&&(e.shell.header.title=this.#x);const i=this.#e._shellState.lightDomHeaderContent;i?.length>0&&(e.shell.header.lightDomContent=i),this.#e._shellState.hasToolButtonsContainer&&(e.shell.header.hasToolButtonsContainer=!0);const n=this.#e._shellState.toolPanels;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.#e._shellState.headerContents;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.#e._shellState.toolbarContents,s=Array.from(o.values()),l=this.#d?.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.#k();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.#e._sortState={field:e.field,direction:"asc"===e.sort.direction?1:-1})}else this.#e._sortState=null;for(const s of t)if(s.applyColumnState)for(const t of e.columns)s.applyColumnState(t.field,t)}resetState(e){this.#C=void 0,this.#e._sortState=null,this.#f=this.#E(this.#p),this.#S();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)}#k(){const e=new Map,t=this.#e._sortState;return t&&e.set(t.field,{direction:1===t.direction?"asc":"desc",priority:0}),e}requestStateChange(e){this.#v&&clearTimeout(this.#v),this.#v=setTimeout(()=>{this.#v=void 0;const t=this.collectState(e);this.#e._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.#e._emit("column-visibility",{field:e,visible:t,visibleColumns:i.filter(e=>!e.hidden).map(e=>e.field)}),this.#e._clearRowPool(),this.#e._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.#e._emit("column-visibility",{visibleColumns:e.map(e=>e.field)}),this.#e._clearRowPool(),this.#e._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,B(this.#e),y(this.#e),this.#e._requestSchedulerPhase(K.VIRTUALIZATION,"configManager")}parseLightDomColumns(e){this.#u||(this.#g=Array.from(e.querySelectorAll("tbw-grid-column")),this.#u=this.#g.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.#u=void 0}#T=new Map;registerLightDomHandler(e,t){this.#T.set(e.toLowerCase(),t)}unregisterLightDomHandler(e){this.#T.delete(e.toLowerCase())}observeLightDOM(e){this.#b&&this.#b.disconnect();const t=new Set,i=()=>{this.#y=void 0;for(const e of t){const t=this.#T.get(e);t?.()}t.clear()};this.#b=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.#T.has(i)&&t.add(i)}if("attributes"===i.type&&i.target.nodeType===Node.ELEMENT_NODE){const e=i.target.tagName.toLowerCase();this.#T.has(e)&&t.add(e)}}t.size>0&&!this.#y&&(this.#y=setTimeout(i,0))}),this.#b.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["title","field","header","width","hidden","id","icon","tooltip","order"]})}onChange(e){this.#m.push(e)}notifyChange(){for(const e of this.#m)e()}dispose(){this.#b?.disconnect(),this.#m=[],this.#v&&clearTimeout(this.#v),this.#y&&(clearTimeout(this.#y),this.#y=void 0)}}function Y(){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 X(e){return`<span role="checkbox" aria-checked="${e}" aria-label="${e}">${e?"🗹":"☐"}</span>`}function Z(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 Q(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 J(e){e&&e.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function ee(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 te(e){return"rtl"===ee(e)}function ie(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 ne(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 re='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function oe(e){return(e.__editingCellCount??0)>0}function se(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing");e.querySelectorAll(".cell.editing").forEach(e=>e.classList.remove("editing"))}const le=document.createElement("template");le.innerHTML='<div class="cell" role="gridcell" part="cell"></div>';const ae=document.createElement("template");function de(){return le.content.firstElementChild.cloneNode(!0)}function ce(){return ae.content.firstElementChild.cloneNode(!0)}function he(e){e.__cellDisplayCache=void 0,e.__cellCacheEpoch=void 0,e.__hasSpecialColumns=void 0}function ue(e,t,i,n){const r=t.children,o=e._visibleColumns,s=o.length,l=r.length,c=s<l?s:l,h=e._focusRow,g=e._focusCol,p=e._hasAfterCellRenderHook?.()??!1;let f=e.__hasSpecialColumns;if(void 0===f){f=!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||i.cellClass||"date"===i.type||"boolean"===i.type||i.type&&t?.getTypeDefault?.(i.type)?.renderer||i.type&&t?.getTypeDefault?.(i.type)?.format){f=!0;break}}e.__hasSpecialColumns=f}const w=String(n);if(f){for(let s=0;s<c;s++){if(o[s].externalView){if(!r[s].querySelector("[data-external-view]"))return void ge(e,t,i,n)}}for(let s=0;s<c;s++){const l=o[s],c=r[s];c.getAttribute("data-row")!==w&&c.setAttribute("data-row",w);const f=c.classList.contains("editing");if(!f){const e=h===n&&g===s;e!==c.classList.contains("cell-focus")&&(c.classList.toggle("cell-focus",e),c.setAttribute("aria-selected",String(e)))}const b=l.cellClass;if(b){const t=c.getAttribute("data-dynamic-classes");t&&t.split(" ").forEach(e=>e&&c.classList.remove(e));try{const e=b(i[l.field],i,l),t="string"==typeof e?e.split(/\s+/):e;if(t&&t.length>0){const e=t.filter(e=>e&&"string"==typeof e);e.forEach(e=>c.classList.add(e)),c.setAttribute("data-dynamic-classes",e.join(" "))}else c.removeAttribute("data-dynamic-classes")}catch(m){u(a,`cellClass callback error for column '${l.field}': ${m}`,e.id),c.removeAttribute("data-dynamic-classes")}}if(f)continue;const v=ie(e,l);if(v){const r=i[l.field],o=v({row:i,value:r,field:l.field,column:l,cellEl:c});"string"==typeof o?(e.__frameworkAdapter?.releaseCell?.(c),c.innerHTML=T(o)):o instanceof Node?o.parentElement!==c&&(e.__frameworkAdapter?.releaseCell?.(c),c.innerHTML="",c.appendChild(o)):null==o&&(e.__frameworkAdapter?.releaseCell?.(c),c.textContent=null==r?"":String(r)),p&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:r,cellElement:c,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?c.textContent="":(c.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(c),c.innerHTML=T(o),I(c)),p&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:r,cellElement:c,rowElement:t});continue}if(l.__viewTemplate){const r=i[l.field],o=l.__viewTemplate.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(o)?c.textContent="":(c.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(c),c.innerHTML=T(M(o,{row:i,value:r})),I(c)),p&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:r,cellElement:c,rowElement:t});continue}if(l.externalView)continue;const y=i[l.field];let C;const x=ne(e,l);if(x){try{const e=x(y,i);C=null==e?"":String(e)}catch(m){u(d,`Format error in column '${l.field}': ${m}`,e.id),C=null==y?"":String(y)}c.textContent=C}else"date"===l.type?(C=Z(y),c.textContent=C):"boolean"===l.type?c.innerHTML=X(!!y):(C=null==y?"":String(y),c.textContent=C);p&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:y,cellElement:c,rowElement:t})}}else for(let a=0;a<c;a++){const s=r[a];if(s.classList.contains("editing"))continue;s.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(s);const l=o[a],d=i[l.field];s.textContent=null==d?"":String(d),s.getAttribute("data-row")!==w&&s.setAttribute("data-row",w);const c=h===n&&g===a;c!==s.classList.contains("cell-focus")&&(s.classList.toggle("cell-focus",c),s.setAttribute("aria-selected",String(c))),p&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:a,value:d,cellElement:s,rowElement:t})}}function ge(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,c=e._focusCol,h=e._hasAfterCellRenderHook?.()??!1,g=document.createDocumentFragment();for(let f=0;f<s;f++){const r=o[f],s=de();s.setAttribute("aria-colindex",String(f+1)),s.setAttribute("data-col",String(f)),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 w=i[r.field];const m=ne(e,r);if(m)try{w=m(w,i)}catch(p){u(d,`Format error in column '${r.field}': ${p}`,e.id)}const b=r.__compiledView,v=r.__viewTemplate,y=ie(e,r),C=r.externalView;let x=!1;if(y){const e=y({row:i,value:w,field:r.field,column:r,cellEl:s});"string"==typeof e?(s.innerHTML=T(e),x=!0):e instanceof Node?e.parentElement!==s&&(s.textContent="",s.appendChild(e)):null==e&&(s.textContent=null==w?"":String(w))}else if(C){const t=C,n=document.createElement("div");n.setAttribute("data-external-view",""),n.setAttribute("data-field",r.field),s.appendChild(n);const o={row:i,value:w,field:r.field,column:r};if(t.mount)try{t.mount({placeholder:n,context:o,spec:t})}catch(p){u("TBW063",`External view mount error for column '${r.field}': ${p}`,e.id)}else queueMicrotask(()=>{try{e.dispatchEvent(new CustomEvent("mount-external-view",{bubbles:!0,composed:!0,detail:{placeholder:n,spec:t,context:o}}))}catch(p){u("TBW064",`External view event dispatch error for column '${r.field}': ${p}`,e.id)}});n.setAttribute("data-mounted","")}else if(b){const e=b({row:i,value:w,field:r.field,column:r}),t=b.__blocked;s.innerHTML=t?"":T(e),x=!0,t&&(s.textContent="",s.setAttribute("data-blocked-template",""))}else if(v){const e=v.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(e)?(s.textContent="",s.setAttribute("data-blocked-template","")):(s.innerHTML=T(M(e,{row:i,value:w})),x=!0)}else m?s.textContent=null==w?"":String(w):"date"===r.type?s.textContent=Z(w):"boolean"===r.type?s.innerHTML=X(!!w):s.textContent=null==w?"":String(w);if(x){I(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="");("function"==typeof r.editable?r.editable(i):r.editable)?s.tabIndex=0:"boolean"===r.type&&(s.hasAttribute("tabindex")||(s.tabIndex=0)),l===n&&c===f?(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),t="string"==typeof e?e.split(/\s+/):e;if(t&&t.length>0){let e="";for(const i of t)i&&"string"==typeof i&&(s.classList.add(i),e+=(e?" ":"")+i);s.setAttribute("data-dynamic-classes",e)}}catch(p){u(a,`cellClass callback error for column '${r.field}': ${p}`,e.id)}h&&e._afterCellRender?.({row:i,rowIndex:n,column:r,colIndex:f,value:w,cellElement:s,rowElement:t}),g.appendChild(s)}t.appendChild(g)}function pe(e,t,i){if(t.target?.closest(".resize-handle"))return;const n=Q(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&&(J(e._bodyEl??e),o.classList.add("cell-focus"));const i=t.target,n=o.contains(i)&&i.matches(re)?i:o.querySelector(re);try{n?.focus({preventScroll:!0})}catch{}return}fe(e)}}}function fe(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||!!e._isGridEditMode;i||e.refreshVirtualWindow(!1),J(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(re);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 i||document.activeElement!==e&&e.focus({preventScroll:!0})}}}ae.innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const we=new WeakMap;function me(e,t){const i=Q(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,J(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 be(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 ve(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 fe(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=te(e);e._focusCol=i?Math.max(0,e._focusCol-1):Math.min(n,e._focusCol+1),t.preventDefault();break}case"ArrowLeft":{const i=te(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 fe(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 fe(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}fe(e)}}(e,t),{signal:n}),i.addEventListener("mousedown",t=>function(e,t,i){const n=be(e,t,i,"mousedown");e._dispatchCellMouseDown?.(n)&&we.set(e,!0)}(e,i,t),{signal:n}),document.addEventListener("mousemove",t=>function(e,t,i){if(!we.get(e))return;const n=be(e,t,i,"mousemove");e._dispatchCellMouseMove?.(n)}(e,i,t),{signal:n}),document.addEventListener("mouseup",t=>function(e,t,i){if(!we.get(e))return;const n=be(e,t,i,"mouseup");e._dispatchCellMouseUp?.(n),we.set(e,!1)}(e,i,t),{signal:n})}let ye;class Ce{#e;#M=new Set;#L=new Map;constructor(e){this.#e=e}focusCell(e,t){const i=this.#e,n=i._rows.length-1;if(n<0)return;let r;if("string"==typeof t){if(r=i._visibleColumns.findIndex(e=>e.field===t),r<0)return}else r=t;const o=i._visibleColumns.length-1;o<0||(i._focusRow=Math.max(0,Math.min(e,n)),i._focusCol=Math.max(0,Math.min(r,o)),fe(i))}get focusedCell(){const e=this.#e;if(0===e._rows.length||0===e._visibleColumns.length)return null;const t=e._visibleColumns[e._focusCol];return{rowIndex:e._focusRow,colIndex:e._focusCol,field:t?.field??""}}scrollToRow(e,t){const i=this.#e._virtualization;if(!i.enabled)return;const n=i.container;if(!n)return;const r=this.#e._rows.length;if(0===r)return;const o=Math.max(0,Math.min(e,r-1)),s=t?.align??"nearest",l=t?.behavior??"instant";let a,d;const c=i.positionCache;i.variableHeights&&c&&c.length>o?(a=c[o].offset,d=c[o].height):(a=o*i.rowHeight,d=i.rowHeight);const h=i.viewportEl?.clientHeight??n.clientHeight??0;if(h<=0)return;const u=n.scrollTop,g=a+d,p=u+h;let f;switch(s){case"start":f=a;break;case"center":f=a-h/2+d/2;break;case"end":f=g-h;break;default:if(a>=u&&g<=p)return;f=a<u?a:g-h}f=Math.max(0,f),"smooth"===l?n.scrollTo({top:f,behavior:"smooth"}):n.scrollTop=f}scrollToRowById(e,t){const i=this.#e._getRowEntry(e);i&&this.scrollToRow(i.index,t)}registerExternalFocusContainer(e){if(this.#M.has(e))return;this.#M.add(e);const t=new AbortController,i=t.signal,n=this.#e;e.addEventListener("focusin",()=>{n.dataset.hasFocus=""},{signal:i}),e.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&this.containsFocus(t)||delete n.dataset.hasFocus},{signal:i}),this.#L.set(e,()=>t.abort())}unregisterExternalFocusContainer(e){this.#M.delete(e);const t=this.#L.get(e);t&&(t(),this.#L.delete(e))}containsFocus(e){const t=e??document.activeElement;return!!t&&(!!this.#e.contains(t)||this.isInExternalFocusContainer(t))}isInExternalFocusContainer(e){for(const t of this.#M)if(t.contains(e))return!0;return!1}destroy(){for(const e of this.#L.values())e();this.#L.clear(),this.#M.clear()}}const xe="function"==typeof requestIdleCallback;function Re(e){xe?cancelIdleCallback(e):clearTimeout(e)}function Ee(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)}function Se(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 _e="data-animating",Ae={change:"--tbw-row-change-duration",insert:"--tbw-row-insert-duration",remove:"--tbw-row-remove-duration"},ke={change:500,insert:300,remove:200};function Te(e,t){const i=Ae[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 ke[t]}function Me(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(_e),e.offsetWidth,e.setAttribute(_e,t);const n=Te(e,t);setTimeout(()=>{"remove"!==t&&e.removeAttribute(_e),i?.()},n)}(n,i,()=>e(!0))}):Promise.resolve(!1)}function Le(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}function Ie(e,t,i){const n=Le(e,i);return void 0===n&&h("TBW040",'Cannot determine row ID. Configure getRowId in gridConfig or ensure rows have an "id" property.',t),n}class Pe{#e;constructor(e){this.#e=e}resolveRowId(e){return Ie(e,this.#e.id,this.#e.effectiveConfig?.getRowId)}getRow(e){return this.#e._getRowEntry(e)?.row}getRowEntry(e){return this.#e._getRowEntry(e)}updateRow(e,t,i="api"){const n=this.#e,r=n._getRowEntry(e);r||h(l,`Row with ID "${e}" not found. Ensure the row exists and getRowId is correctly configured.`,n.id);const{row:o,index:s}=r,a=[];for(const[l,d]of Object.entries(t)){const e=o[l];e!==d&&(a.push({field:l,oldValue:e,newValue:d}),o[l]=d)}for(const{field:l,oldValue:d,newValue:c}of a)n.dispatchEvent(new CustomEvent("cell-change",{detail:{row:o,rowId:e,rowIndex:s,field:l,oldValue:d,newValue:c,changes:t,source:i},bubbles:!0,composed:!0}));a.length>0&&(he(n),n._requestSchedulerPhase(K.VIRTUALIZATION,"updateRow"),n._emitDataChange())}updateRows(e,t="api"){const i=this.#e;let n=!1;for(const{id:r,changes:o}of e){const e=i._getRowEntry(r);e||h(l,`Row with ID "${r}" not found. Ensure the row exists and getRowId is correctly configured.`,i.id);const{row:s,index:a}=e;for(const[l,d]of Object.entries(o)){const e=s[l];e!==d&&(n=!0,s[l]=d,i.dispatchEvent(new CustomEvent("cell-change",{detail:{row:s,rowId:r,rowIndex:a,field:l,oldValue:e,newValue:d,changes:o,source:t},bubbles:!0,composed:!0})))}}n&&(he(i),i._requestSchedulerPhase(K.VIRTUALIZATION,"updateRows"),i._emitDataChange())}async insertRow(e,t,i=!0){const n=this.#e,r=Math.max(0,Math.min(e,n._rows.length));n.sourceRows=[...n.sourceRows,t];const o=[...n._rows];o.splice(r,0,t),n._rows=o,n._sortState&&(n.__originalOrder=[...n.__originalOrder,t]),he(n),n._rebuildRowIdMap(),n.__rowRenderEpoch++;for(const s of n._rowPool)s.__epoch=-1;n.refreshVirtualWindow(!0),n._emitPluginEvent("row-inserted",{row:t,index:r}),n._emitDataChange(),i&&(await new Promise(e=>requestAnimationFrame(()=>e())),await Me(n,r,"insert"))}async removeRow(e,t=!0){const i=this.#e,n=i._rows[e];if(!n)return;t&&await Me(i,e,"remove");const r=i._rows.indexOf(n);if(r<0)return n;const o=[...i._rows];o.splice(r,1),i._rows=o;const s=i.sourceRows.indexOf(n);if(s>=0){const e=[...i.sourceRows];e.splice(s,1),i.sourceRows=e}if(i._sortState){const e=i.__originalOrder.indexOf(n);if(e>=0){const t=[...i.__originalOrder];t.splice(e,1),i.__originalOrder=t}}he(i),i._rebuildRowIdMap(),i.__rowRenderEpoch++;for(const l of i._rowPool)l.__epoch=-1;return i.refreshVirtualWindow(!0),i._emitDataChange(),t&&requestAnimationFrame(()=>{i.querySelectorAll('[data-animating="remove"]').forEach(e=>{e.removeAttribute("data-animating")})}),n}}function He(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 De(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 ze(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 Fe=document.createElement("template");function Oe(){return Fe.content.cloneNode(!0)}function qe(e){const t=document.createDocumentFragment(),i=De(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=De("tbw-grid-content");e.appendChild(Oe()),i.appendChild(e)}return t.appendChild(i),t}function Ne(e){return e?"string"==typeof e?e:e.outerHTML:""}function Ge(e){return!!e?.header?.title||(!!e?.header?.toolbarContents?.length||(!!e?.toolPanels?.length||(!!e?.headerContents?.length||(!!e?.header?.lightDomContent?.length||!!e?.header?.hasToolButtonsContainer))))}function $e(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 We(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 Be(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 u("TBW070",`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 g={id:r,title:o,icon:s,tooltip:l,order:a,render:d};t.toolPanels.set(r,g),t.lightDomToolPanelIds.add(r),n.style.display="none"})}function Ve(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 Ke(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 Ue(e,t,i){if(t.isPanelOpen)for(const[n,r]of t.toolPanels){const i=t.expandedSections.has(n),o=e.querySelector(`[data-section="${n}"]`),s=o?.querySelector(".tbw-accordion-content");if(!o||!s)continue;o.classList.toggle("expanded",i);const l=o.querySelector(".tbw-accordion-header");if(l&&l.setAttribute("aria-expanded",String(i)),i){if(0===s.children.length){const e=r.render(s);e&&t.panelCleanups.set(n,e)}}else{const e=t.panelCleanups.get(n);e&&(e(),t.panelCleanups.delete(n)),s.innerHTML=""}}}function je(e,t){const i=e.querySelector("[data-panel-toggle]");i&&(i.classList.toggle("active",t.isPanelOpen),i.setAttribute("aria-pressed",String(t.isPanelOpen)))}function Ye(e,t){const i=e.querySelector(".tbw-tool-panel");i&&(i.classList.toggle("open",t.isPanelOpen),t.isPanelOpen||(i.style.width=""))}function Xe(e){for(const t of e.toolbarContentCleanups.values())t();e.toolbarContentCleanups.clear();for(const t of e.panelCleanups.values())t();e.panelCleanups.clear();for(const t of e.headerContentCleanups.values())t();e.headerContentCleanups.clear(),e.lightDomContentMoved=!1}function Ze(e,t,i){const n=e.querySelector(`[data-section="${t}"]`);n&&n.classList.toggle("expanded",i)}function Qe(e,t,i,n){const r=Ge(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 o of l){e.querySelectorAll(`:scope > ${o}`).forEach(e=>s.push(e))}e.replaceChildren();for(const o of s)e.appendChild(o);if(r){const r=Ne(n?.toolPanel??o.toolPanel),s=Ne(n?.expand??o.expand);Ne(n?.collapse??o.collapse);const l=[...t?.header?.toolbarContents??[]].sort((e,t)=>(e.order??0)-(t.order??0)),a=[...t?.toolPanels??[]].sort((e,t)=>(e.order??100)-(t.order??100)),d={title:t?.header?.title??void 0,hasPanels:a.length>0,isPanelOpen:i.isPanelOpen,toolPanelIcon:r,configButtons:l.map(e=>({id:e.id,hasElement:!1,hasRender:!!e.render})),apiButtons:[]},c={position:t?.toolPanel?.position??"right",isPanelOpen:i.isPanelOpen,expandIcon:s,panels:a.map(e=>({id:e.id,title:e.title,icon:Ne(e.icon),isExpanded:i.expandedSections.has(e.id)}))},h=qe({hasShell:!0,shellHeader:function(e){const t=De("tbw-shell-header",{part:"shell-header",role:"presentation"});if(e.title){const i=De("tbw-shell-title");i.textContent=e.title,t.appendChild(i)}const i=De("tbw-shell-content",{part:"shell-content",role:"presentation","data-light-dom-header-content":""});t.appendChild(i);const n=De("tbw-shell-toolbar",{part:"shell-toolbar",role:"presentation"});for(const r of e.configButtons)r.hasRender&&n.appendChild(De("tbw-toolbar-content-slot",{"data-toolbar-content":r.id}));for(const r of e.apiButtons)r.hasRender&&n.appendChild(De("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(De("tbw-toolbar-separator")),e.hasPanels){const t=ze(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}(d),shellBody:function(e){const t=De("tbw-shell-body"),i=e.panels.length>0,n=1===e.panels.length,r=De("tbw-grid-content");r.appendChild(Oe());let o=null;if(i){o=He("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(De("tbw-tool-panel-resize",{"data-resize-handle":"","data-handle-position":t,"aria-hidden":"true"}));const i=De("tbw-tool-panel-content",{role:"presentation"}),r=De("tbw-accordion");for(const o of e.panels){const t=De(`tbw-accordion-section${o.isExpanded?" expanded":""}${n?" single":""}`,{"data-section":o.id}),i=ze("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=He("span",{class:"tbw-accordion-icon"});e.innerHTML=o.icon,i.appendChild(e)}const s=He("span",{class:"tbw-accordion-title"});if(s.textContent=o.title,i.appendChild(s),!n){const t=He("span",{class:"tbw-accordion-chevron"});t.innerHTML=e.expandIcon,i.appendChild(t)}t.appendChild(i),t.appendChild(De("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}(c)});e.appendChild(h)}else{const t=qe({hasShell:!1});e.appendChild(t)}return r}Fe.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 <div class="tbw-sr-only" aria-live="polite" aria-atomic="true"></div>\n';const Je="tbw-grid-styles";let et="";const tt=new Map;function it(){const e=function(){let e=document.getElementById(Je);return e||(e=document.createElement("style"),e.id=Je,e.setAttribute("data-tbw-grid","true"),document.head.appendChild(e)),e}(),t=Array.from(tt.values()).join("\n");e.textContent=`${et}\n\n/* Plugin Styles */\n${t}`}async function nt(e){if(et)return;if("string"==typeof e&&e.length>0)return et=e,void it();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){u("TBW120",`Failed to extract grid.css from document stylesheets: ${e}`)}return null}();t?(et=t,it()):"undefined"!=typeof process&&"test"===process.env?.NODE_ENV||u("TBW121",`Could not find grid.css in document.styleSheets. Grid styling will not work. Available stylesheets: ${Array.from(document.styleSheets).map(e=>e.href||"(inline)").join(", ")}`)}function rt(e){e.startY=null,e.startX=null,e.lastY=null,e.lastX=null,e.lastTime=null,e.locked=!1}function ot(e){e.momentumRaf&&(cancelAnimationFrame(e.momentumRaf),e.momentumRaf=0)}function st(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),rt(e)}function lt(e,t,i,n){e.addEventListener("pointerdown",i=>{"touch"===i.pointerType&&null===t.activePointerId&&(t.activePointerId=i.pointerId,e.setPointerCapture(i.pointerId),function(e,t,i){ot(i),i.startY=t,i.startX=e,i.lastY=t,i.lastX=e,i.lastTime=performance.now(),i.velocityY=0,i.velocityX=0,i.locked=!1}(i.clientX,i.clientY,t))},{passive:!0,signal:n}),e.addEventListener("pointermove",e=>{if(e.pointerId!==t.activePointerId)return;const n=function(e,t,i,n){if(null===i.lastY||null===i.lastX)return!1;const r=performance.now(),o=i.lastY-t,s=i.lastX-e;if(null!==i.lastTime){const e=r-i.lastTime;e>0&&(i.velocityY=o/e,i.velocityX=s/e)}if(i.lastY=t,i.lastX=e,i.lastTime=r,i.locked)return n.fauxScrollbar.scrollTop+=o,n.scrollArea&&(n.scrollArea.scrollLeft+=s),!0;const l=null!==i.startY?Math.abs(i.startY-t):0,a=null!==i.startX?Math.abs(i.startX-e):0;if(l<3&&a<3)return!1;const d=l>=a,{scrollHeight:c,clientHeight:h}=n.fauxScrollbar,u=c-h>0;let g=!1;if(n.scrollArea){const{scrollWidth:e,clientWidth:t}=n.scrollArea;g=e-t>0}return!!(d&&u||!d&&g)&&(i.locked=!0,n.fauxScrollbar.scrollTop+=o,n.scrollArea&&(n.scrollArea.scrollLeft+=s),!0)}(e.clientX,e.clientY,t,i);n&&e.preventDefault()},{passive:!1,signal:n}),e.addEventListener("pointerup",e=>{e.pointerId===t.activePointerId&&(t.activePointerId=null,st(t,i))},{passive:!0,signal:n}),e.addEventListener("pointercancel",e=>{e.pointerId===t.activePointerId&&(t.activePointerId=null,rt(t))},{passive:!0,signal:n}),e.addEventListener("lostpointercapture",e=>{e.pointerId===t.activePointerId&&(t.activePointerId=null,rt(t))},{passive:!0,signal:n})}const at=[{property:"editable",pluginName:"editing",level:"column",description:'the "editable" column property',isUsed:e=>!0===e||"function"==typeof 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}],dt=[{property:"rowEditable",pluginName:"editing",level:"config",description:'the "rowEditable" config property',isUsed:e=>"function"==typeof e},{property:"columnGroups",pluginName:"groupingColumns",level:"config",description:'the "columnGroups" config property',isUsed:e=>Array.isArray(e)&&e.length>0}];function ct(e){return`import { ${ht(e)}Plugin } from '@toolbox-web/grid/plugins/${t=e,t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}';`;var t}function ht(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ut(e,t){return e.some(e=>e.name===t)}function gt(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 pt(e,t,i){const n=gt(t,i);return"string"==typeof n?e.byKey.get(n):n&&"object"==typeof n?e.byRef.get(n):void 0}function ft(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 wt(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 mt(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)&&(ft(i,c,u),d=!0))}const g=e.offsetHeight;if(g>0){const e=i[c];(!e.measured||Math.abs(e.height-g)>1)&&(ft(i,c,g),function(e,t,i,n){const r=gt(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 bt{#e;state;constructor(e,t){this.#e=e,this.state={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,...t}}updateCachedGeometry(){const e=this.state,t=e.container,i=e.viewportEl??t;i&&(e.cachedViewportHeight=i.clientHeight),t&&(e.cachedFauxHeight=t.clientHeight);const n=e.scrollAreaEl;n&&(e.cachedScrollAreaHeight=n.clientHeight)}calculateTotalSpacerHeight(e,t=!1){const i=this.state;let n,r,o;if(t){const e=i.container??this.#e._hostElement,t=i.viewportEl??e,s=i.scrollAreaEl;n=e?.clientHeight??0,r=t?.clientHeight??0,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;return 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.#e._getPluginExtraHeight()),a+s+d+l}initializePositionCache(){const e=this.state;if(!e.variableHeights)return;const t=this.#e,i=t._rows,n=e.rowHeight||28,r=t.effectiveConfig?.rowHeight,o=t.effectiveConfig?.getRowId,s=o?e=>o(e):void 0;e.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=pt(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}(i,e.heightCache,n,{rowId:s},(e,i)=>{const n=t._getPluginRowHeight(e,i);if(void 0!==n)return n;if(r){const t=r(e,i);if(void 0!==t&&t>0)return t}});const l=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}}(e.positionCache,i,n,(e,i)=>t._getPluginRowHeight(e,i));e.measuredCount=l.measuredCount,l.measuredCount>0&&(e.averageHeight=l.averageHeight)}invalidateRowHeight(e,t){const i=this.state;if(!i.variableHeights)return;if(!i.positionCache)return;const n=this.#e._rows;if(e<0||e>=n.length)return;const r=n[e];let o=t;void 0===o&&(o=this.#e._getPluginRowHeight(r,e)),void 0===o&&(o=i.rowHeight);const s=i.positionCache[e];if(s&&!(Math.abs(s.height-o)<1)&&(ft(i.positionCache,e,o),i.totalHeightEl)){const e=this.calculateTotalSpacerHeight(n.length);i.totalHeightEl.style.height=`${e}px`}}measureRenderedRowHeights(e,t){const i=this.state;if(!i.variableHeights)return;if(!i.positionCache)return;const n=this.#e,r=n._bodyEl;if(!r)return;const o=r.querySelectorAll(".data-grid-row"),s=n.effectiveConfig?.getRowId,l=n._rows,a=mt({positionCache:i.positionCache,heightCache:i.heightCache,rows:l,defaultHeight:i.rowHeight,start:e,end:t,getPluginHeight:(e,t)=>n._getPluginRowHeight(e,t),getRowId:s?e=>s(e):void 0},o);if(a.hasChanges&&(i.measuredCount=a.measuredCount,i.averageHeight=a.averageHeight,i.totalHeightEl)){const e=this.calculateTotalSpacerHeight(l.length);i.totalHeightEl.style.height=`${e}px`}}refreshVirtualWindow(e=!1,t=!1){const i=this.state,n=this.#e,r=n._bodyEl;if(!r)return!1;const o=n._rows.length;if(!i.enabled)return n._renderVisibleRows(0,o),t||n._afterPluginRender(),!0;if(o<=i.bypassThreshold)return i.start=0,i.end=o,e&&(r.style.transform="translateY(0px)"),n._renderVisibleRows(0,o,n.__rowRenderEpoch),e&&i.totalHeightEl&&(i.totalHeightEl.style.height=`${this.calculateTotalSpacerHeight(o,!0)}px`),n._updateAriaCounts(o,n._visibleColumns.length),t||n._afterPluginRender(),!0;const s=i.container,l=i.viewportEl??s,a=e?i.cachedViewportHeight=l.clientHeight:i.cachedViewportHeight||(i.cachedViewportHeight=l.clientHeight),d=i.rowHeight,c=s.scrollTop;let h;e&&i.variableHeights&&this.initializePositionCache();const u=i.positionCache;if(i.variableHeights&&u&&u.length>0)h=wt(u,c),-1===h&&(h=0);else{h=Math.floor(c/d);let e=0;const t=10;for(;e<t;){const t=n._getPluginExtraHeightBefore(h),i=Math.floor((c-t)/d);if(i>=h||i<0)break;h=i,e++}}h-=h%2,h<0&&(h=0);const g=n._adjustPluginVirtualStart(h,c,d);let p;if(void 0!==g&&g<h&&(h=g,h-=h%2,h<0&&(h=0)),i.variableHeights&&u&&u.length>0){const e=a+3*d;let t=0;for(p=h;p<o&&t<e;)t+=u[p].height,p++;const i=Math.ceil(a/d)+3;p-h<i&&(p=Math.min(h+i,o))}else{p=h+(Math.ceil(a/d)+3)}p>o&&(p=o);const f=i.start,w=i.end;if(!e&&h===f&&p===w)return!1;i.start=h,i.end=p;const m=e?i.cachedFauxHeight=s.clientHeight:i.cachedFauxHeight||(i.cachedFauxHeight=s.clientHeight);if(e){const e=i.scrollAreaEl;e&&(i.cachedScrollAreaHeight=e.clientHeight)}if(0===m&&a>0)return n._requestSchedulerPhase(K.VIRTUALIZATION,"stale-refs-retry"),!1;if(e&&i.totalHeightEl){const e=this.calculateTotalSpacerHeight(o);i.totalHeightEl.style.height=`${e}px`}let b;if(i.variableHeights&&u&&u[h])b=u[h].offset;else{b=h*d+n._getPluginExtraHeightBefore(h)}const v=-(c-b);return r.style.transform=`translateY(${v}px)`,n._renderVisibleRows(h,p,n.__rowRenderEpoch),e&&i.variableHeights&&this.measureRenderedRowHeights(h,p),n._updateAriaCounts(o,n._visibleColumns.length),e&&!t&&(n._afterPluginRender(),queueMicrotask(()=>{if(!i.totalHeightEl)return;const e=this.calculateTotalSpacerHeight(o);0===i.cachedFauxHeight&&i.cachedViewportHeight>0||(i.totalHeightEl.style.height=`${e}px`)})),!0}}class vt{constructor(e){this.grid=e}plugins=[];getPlugins(){return this.plugins}pluginMap=new Map;cellRenderers=new Map;headerRenderers=new Map;cellEditors=new Map;_hasAfterCellRender=!1;_hasAfterRowRender=!1;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,i){const n=e.name,r=e.constructor.dependencies??[];for(const o of r){const e=o.name,r=o.required??!0,s=o.reason;if(!t.some(t=>t.name===e)){const t=s??`${ht(n)}Plugin requires ${ht(e)}Plugin`,o=ct(e);r?h("TBW020",`Plugin dependency error:\n\n${t}.\n\n → Add the plugin to your gridConfig.plugins array BEFORE ${ht(n)}Plugin:\n ${o}\n plugins: [new ${ht(e)}Plugin(), new ${ht(n)}Plugin()]`,i):g("TBW021",`${ht(n)}Plugin: Optional "${e}" plugin not found. Some features may be unavailable.`,i)}}}(e,this.plugins,this.grid.getAttribute("id")??void 0),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),this.#I();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(vt.deprecationWarned.has(t))return;if(!Y())return;const i="function"==typeof e.getExtraHeight||"function"==typeof e.getExtraHeightBefore,n="function"==typeof e.getRowHeight;i&&!n&&(vt.deprecationWarned.add(t),u("TBW023",`"${e.name}" uses getExtraHeight() / getExtraHeightBefore() which are deprecated and will be removed in v2.0.\n → Migrate to getRowHeight(row, index) for better variable row height support.`,this.grid.getAttribute("id")??void 0))}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(),this._hasAfterCellRender=!1,this._hasAfterRowRender=!1}getPlugin(e){return this.pluginMap.get(e)}getPluginByName(e){return this.plugins.find(t=>t.name===e||t.aliases?.includes(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._hasAfterCellRender}afterRowRender(e){for(const t of this.plugins)t.afterRowRender?.(e)}hasAfterRowRenderHook(){return this._hasAfterRowRender}#I(){this._hasAfterCellRender=this.plugins.some(e=>"function"==typeof e.afterCellRender),this._hasAfterRowRender=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){p("TBW024",`Error in plugin event handler for "${e}": ${n}`,this.grid.getAttribute("id")??void 0)}}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 yt extends HTMLElement{static tagName="tbw-grid";static version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";static#P=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#H(){return this}#D=!1;#n;#r;#z=[];get#f(){return this.#F?.effective??{}}#O=!1;#q=!1;#N={rows:!1,columns:!1,gridConfig:!1,fitMode:!1};#G;#$=0;#W=null;#B=!1;#V=!1;#K=0;#U;#j={startY:null,startX:null,lastY:null,lastX:null,lastTime:null,velocityY:0,velocityX:0,momentumRaf:0,locked:!1,activePointerId:null};#Y;#X;#Z;#Q;#J={scrollTop:0,scrollLeft:0,scrollHeight:0,scrollWidth:0,clientHeight:0,clientWidth:0};#ee;#te;#ie;#ne;#re;#oe;get _pluginManager(){return this.#ee}#se=!1;#le;#ae;#C;#F;#de=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,apiHeaderContentIds:new Set,isPanelOpen:!1,expandedSections:new Set,headerContentCleanups:new Map,panelCleanups:new Map,toolbarContentCleanups:new Map,lightDomContentMoved:!1}}();#ce;#he;#ue;#ge=!1;#pe=new Set;#fe=new Map;#we;#me=new Map;_rows=[];#be=[];get _columns(){return this.#f.columns??[]}set _columns(e){this.#f.columns=e,this.#ve=void 0}#ve;get _visibleColumns(){return this.#ve??=this._columns.filter(e=>!e.hidden)}_headerRowEl;_bodyEl;_rowPool=[];_resizeController;get _virtualization(){return this.#ne.state}set _virtualization(e){Object.assign(this.#ne.state,e)}_focusRow=0;_focusCol=0;_restoreFocusAfterRender=!1;_sortState=null;_gridTemplate="";__rowRenderEpoch=0;__didInitialAutoSize=!1;get __lightDomColumnsCache(){return this.#F?.lightDomColumnsCache}set __lightDomColumnsCache(e){this.#F&&(this.#F.lightDomColumnsCache=e)}get __originalColumnNodes(){return this.#F?.originalColumnNodes}set __originalColumnNodes(e){this.#F&&(this.#F.originalColumnNodes=e)}__originalOrder=[];__frameworkAdapter;__rowsBodyEl=null;get rows(){return this._rows}set rows(e){const t=this.#z;this.#z=e,t!==e&&this.#ye("rows")}get sourceRows(){return this.#z}set sourceRows(e){this.#z=e}get columns(){return[...this._columns]}set columns(e){const t=this.#F?.getColumns();this.#F?.setColumns(e),t!==e&&this.#ye("columns")}get gridConfig(){return this.#f}set gridConfig(e){e&&this.__frameworkAdapter?.processConfig&&(e=this.__frameworkAdapter.processConfig(e));const t=this.#F?.getGridConfig();this.#F?.setGridConfig(e),t!==e&&(this.#F.clearLightDomCache(),this.#ye("gridConfig"))}get fitMode(){return this.#f.fitMode??"stretch"}set fitMode(e){const t=this.#F?.getFitMode();this.#F?.setFitMode(e),t!==e&&this.#ye("fitMode")}get loading(){return this.#ge}set loading(e){const t=this.#ge;this.#ge=e,e?this.setAttribute("loading",""):this.removeAttribute("loading"),t!==e&&this.#Ce()}setRowLoading(e,t){const i=this.#pe.has(e);t?this.#pe.add(e):this.#pe.delete(e),i!==t&&this.#xe(e,t)}setCellLoading(e,t,i){let n=this.#fe.get(e);const r=n?.has(t)??!1;i?(n||(n=new Set,this.#fe.set(e,n)),n.add(t)):(n?.delete(t),0===n?.size&&this.#fe.delete(e)),r!==i&&this.#Re(e,t,i)}isRowLoading(e){return this.#pe.has(e)}isCellLoading(e,t){return this.#fe.get(e)?.has(t)??!1}clearAllLoading(){this.loading=!1;for(const e of this.#pe)this.#xe(e,!1);this.#pe.clear();for(const[e,t]of this.#fe)for(const i of t)this.#Re(e,i,!1);this.#fe.clear()}get effectiveConfig(){return this.#f}get disconnectSignal(){return this.#Y||(this.#Y=new AbortController),this.#Y.signal}constructor(){super(),this.#Ee(),this.#n=new Promise(e=>this.#r=e),this.#ne=new bt(this),this.#re=new Ce(this),this.#oe=new Pe(this),this.#G=new U(this),this.#G.setInitialReadyResolver(()=>this.#r?.()),this.#ce=function(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 u("TBW071","No tool panels registered",t.id);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._renderRoot;je(i,e),Ye(i,e),Ue(i,e,t._accordionIcons),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._renderRoot;je(i,e),Ye(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 u("TBW072",`Tool panel section "${i}" not found`,t.id);if(1===e.toolPanels.size)return;const r=t._renderRoot,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)?u("TBW073",`Tool panel "${n.id}" already registered`,t.id):(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)?u("TBW074",`Header content "${n.id}" already registered`,t.id):(e.headerContents.set(n.id,n),i&&Ke(t._renderRoot,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._renderRoot.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)?u("TBW075",`Toolbar content "${n.id}" already registered`,t.id):(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}(this.#de,this),this.#F=new j(this)}async#Ee(){await nt('@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;touch-action:none}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);touch-action:none}tbw-grid .faux-vscroll-spacer{width:1px}tbw-grid .tbw-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}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;touch-action:none}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:var(--tbw-z-layer-toolpanel, 31);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.#ee?.getPlugin(e)}getPluginByName(e){return this.#ee?.getPluginByName(e)}requestRender(){this.#G.requestPhase(K.ROWS,"plugin:requestRender")}requestColumnsRender(){this.#G.requestPhase(K.COLUMNS,"plugin:requestColumnsRender")}requestRenderWithFocus(){this._restoreFocusAfterRender=!0,this.#G.requestPhase(K.ROWS,"plugin:requestRenderWithFocus")}updateTemplate(){y(this)}requestAfterRender(){this.#G.requestPhase(K.STYLE,"plugin:requestAfterRender")}requestVirtualRefresh(){this._virtualization.start=-1,this.refreshVirtualWindow(!1)}#Se(){this.#ee=new vt(this);const e=this.#f?.plugins,t=Array.isArray(e)?e:[],i=this.#f?.features;let n=[];i&&ye&&(n=ye(i));const r=n.length>0?[...n,...t]:t;this.#ee.attachAll(r)}#_e(){!function(e){let t=!1;for(const{name:i,styles:n}of e)tt.has(i)||(tt.set(i,n),t=!0);t&&it()}(this.#ee?.getPluginStyles()??[])}#Ae(){const e=this.#f?.plugins,t=Array.isArray(e)?e:[],i=this.#f?.features??void 0,n=i!==this.#ie;if((this.#te===t||void 0!==this.#te&&this.#te.length===t.length&&this.#te.every((e,i)=>e===t[i]))&&!n)return void(this.#te=t);this.#ee&&this.#ee.detachAll();for(const o of this.#de.toolPanels.keys()){const e=this.#de.lightDomToolPanelIds.has(o),t=this.#de.apiToolPanelIds.has(o);if(!e&&!t){const e=this.#de.panelCleanups.get(o);e&&(e(),this.#de.panelCleanups.delete(o)),this.#de.toolPanels.delete(o)}}for(const o of this.#de.headerContents.keys()){if(this.#de.apiHeaderContentIds.has(o))continue;const e=this.#de.headerContentCleanups.get(o);e&&(e(),this.#de.headerContentCleanups.delete(o)),this.#de.headerContents.delete(o)}this.#Se(),this.#_e(),this.#te=t,this.#ie=i,this.#ke(),this.#Te();const r=this.#B;if(this.#B=this.#ee?.getAll().some(e=>e.onScroll)??!1,!r&&this.#B){const e=this.#H.querySelector(".tbw-grid-content")??this.#H.querySelector(".tbw-grid-root");this.#Me(e)}}#Le(){this.#ee?.detachAll()}#Te(){if(!this.#ee)return;const e=this.#ee.getToolPanels();for(const{panel:i}of e)this.#de.toolPanels.has(i.id)||this.#de.toolPanels.set(i.id,i);const t=this.#ee.getHeaderContents();for(const{content:i}of t)this.#de.headerContents.has(i.id)||this.#de.headerContents.set(i.id,i)}#Ie(){const e=yt.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",yt.version),this.id||(this.id="tbw-grid-"+ ++yt.#P),this._rows=Array.isArray(this.#z)?[...this.#z]:[],this.#Y&&(this.#Y.abort(),this.#se=!1),this.#Y=new AbortController,this.#Q&&(Re(this.#Q),this.#Q=void 0),this.#Pe(),this.#F.parseLightDomColumns(this),this.#F.merge(),this.#Se();const e=this.#f?.plugins;var t,i;this.#te=Array.isArray(e)?e:[],this.#ie=this.#f?.features??void 0,this.#Te(),this.#D||(this.#He(),this.#_e(),this.#D=!0),this.#De(),this.#Q=(t=()=>{this.#ze()},i={timeout:100},xe?requestIdleCallback(t,i):window.setTimeout(()=>{const e=Date.now();t({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-e))})},1))}disconnectedCallback(){this.#Q&&(Re(this.#Q),this.#Q=void 0),this.#K&&(clearTimeout(this.#K),this.#K=0),this.#Le(),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.#de),this.#ce.setInitialized(!1),this.#he?.(),this.#he=void 0,this.#ue?.(),this.#ue=void 0,ot(this.#j),this.#Y&&(this.#Y.abort(),this.#Y=void 0),this.#le?.abort(),this.#le=void 0,this.#se=!1,this._resizeController&&this._resizeController.dispose(),this.#X&&(this.#X.disconnect(),this.#X=void 0),this.#Z&&(this.#Z.disconnect(),this.#Z=void 0,this.#Fe=!1),he(this),this.#Oe.clear(),this._virtualization.heightCache?.byKey.clear(),this.#te=void 0,this.#ie=void 0;for(const e of this._rowPool)e.remove();this._rowPool.length=0,this.__rowsBodyEl=null,this.#O=!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{u("TBW130",`Invalid JSON for '${e}' attribute: ${i}`,this.id)}else"fit-mode"===e&&(this.fitMode=i)}#De(){const e=this.#H.querySelector(".tbw-grid-content")??this.#H.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.#ce.isInitialized){Ke(this.#H,this.#de),Ve(this.#H,this.#f?.shell,this.#de);const e=this.#f?.shell?.toolPanel?.defaultOpen;e&&this.#de.toolPanels.has(e)&&(this.openToolPanel(),this.#de.expandedSections.add(e)),this.#de.isPanelOpen&&(Ye(this.#H,this.#de),Ue(this.#H,this.#de,(this.#f,this.#f)),je(this.#H,this.#de))}if(this.setAttribute("data-upgraded",""),this.#O=!0,this._resizeController=Se(this),this.#qe(),this.#Me(e),this.#se)return;this.#se=!0;const t=this.disconnectSignal;ve(this,this,this.#H,t),this.#ke(),queueMicrotask(()=>this.#Ne()),this.#G.requestPhase(K.FULL,"afterConnect")}#ke(){const e=this.#f.rowHeight,t=this.#ee.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.initializePositionCache(),"function"!=typeof e&&(this.#V=!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.#ee.hasExtraHeight())return;const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;if(e.style.getPropertyValue("--tbw-row-height"))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&&r-this._virtualization.rowHeight>1&&(this._virtualization.rowHeight=r,this.#G.requestPhase(K.VIRTUALIZATION,"measureRowHeight"))}#$e(){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.initializePositionCache(),this._virtualization.totalHeightEl){const e=this.#ne.calculateTotalSpacerHeight(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}}#Me(e){this.#le?.abort(),this.#le=new AbortController;const t=this.#le.signal,i=e?.querySelector(".faux-vscroll"),n=e?.querySelector(".rows");if(this._virtualization.container=i??this,this.#B=this.#ee?.getAll().some(e=>e.onScroll)??!1,i&&n){i.addEventListener("scroll",()=>{if(!this._virtualization.enabled&&!this.#B)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=wt(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.#W=e,this.#$||(this.#$=requestAnimationFrame(()=>{this.#$=0,null!==this.#W&&(this.#We(this.#W),this.#W=null)}))},{passive:!0,signal:t});const e=this.#H.querySelector(".tbw-scroll-area");this.#ae=e,this._virtualization.scrollAreaEl=e,e&&this.#B&&e.addEventListener("scroll",()=>{const t=this.#J;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.#ee?.onScroll(t)},{passive:!0,signal:t});const r=this.#H.querySelector(".tbw-grid-content"),o=this.#ae;r&&(r.addEventListener("wheel",e=>{try{if(r.querySelector("select:open"))return}catch{}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}),lt(r,this.#j,{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]");if(!t)return;if(t.classList.contains("editing"))return;const i=e.target;i.draggable||i.closest('[draggable="true"]')||e.preventDefault(),me(r,t)},{signal:s}),o.addEventListener("click",e=>{const t=e.target.closest(".data-grid-row");if(t&&pe(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&&pe(r,e,t)},{signal:s})),this.#X?.disconnect(),this._virtualization.viewportEl&&(this.#X=new ResizeObserver(()=>{this.#Be(),this.#G.requestPhase(K.VIRTUALIZATION,"resize-observer")}),this.#X.observe(this._virtualization.viewportEl)),this.#H.addEventListener("focusin",()=>{this.dataset.hasFocus=""},{signal:t}),this.#H.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.#H.contains(t)||this.#re.isInExternalFocusContainer(t))||delete this.dataset.hasFocus},{signal:t})}#Fe=!1;#Ve(){if(this.#Fe)return;const e=this._bodyEl?.querySelector(".data-grid-row");e&&(this.#Fe=!0,this.#Z?.disconnect(),this.#Z=new ResizeObserver(()=>{this.#Ge()}),this.#Z.observe(e))}addEventListener(e,t,i){super.addEventListener(e,t,i)}removeEventListener(e,t,i){super.removeEventListener(e,t,i)}on(e,t){const i=e=>{t(e.detail,e)};return this.addEventListener(e,i),()=>this.removeEventListener(e,i)}#Ke(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}_emitDataChange(){this.#Ke("data-change",{rowCount:this._rows.length,sourceRowCount:this.#z.length})}#Ne(){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))})})}#ye(e){this.#N[e]=!0,this.#q||(this.#q=!0,queueMicrotask(()=>this.#Ue()))}#Ue(){if(!this.#q||!this.#O)return void(this.#q=!1);const e=this.#N;if(this.#q=!1,this.#N={rows:!1,columns:!1,gridConfig:!1,fitMode:!1},e.gridConfig)return this.#je(),void(e.rows&&this.#Ye());e.columns&&this.#Xe(),e.rows&&this.#Ye(),e.fitMode&&this.#Ze()}#Ye(){this._rows=Array.isArray(this.#z)?[...this.#z]:[],this._rebuildRowIdMap(),this.#G.requestPhase(K.ROWS,"applyRowsUpdate")}_rebuildRowIdMap(){this.#me.clear();const e=this.#f.getRowId;this._rows.forEach((t,i)=>{const n=Le(t,e);void 0!==n&&this.#me.set(n,{row:t,index:i})})}#Xe(){he(this),this.#F.merge(),this.#qe()}#Ze(){this.#F.merge();"fixed"===this.#f.fitMode?(this.__didInitialAutoSize=!1,m(this)):(this._columns.forEach(e=>{!e.__userResized&&e.__autoSized&&delete e.width}),y(this))}#je(){$e(this,this.#de),We(this,this.#de);const e=!!this.#H.querySelector(".has-shell"),t=!!this.#H.querySelector(".tbw-tool-panel"),i=this.#H.querySelectorAll(".tbw-accordion-section").length,n=this.#H.querySelector(".tbw-tool-panel")?.dataset.position??"right";this.#F.parseLightDomColumns(this),this.#F.merge(),this.#Ae(),this.#ke(),Be(this,this.#de,this.#Ie()),this.#F.markSourcesChanged(),this.#F.merge();const r=Ge(this.#f?.shell),o=(this.#f?.shell?.toolPanels?.length??0)>0,s=this.#f?.shell?.toolPanels?.length??0,l=this.#f?.shell?.toolPanel?.position??"right";if(e!==r||!t&&o||t&&s!==i||t&&n!==l)return Xe(this.#de),this.#He(),this.#_e(),this.#De(),void this._rebuildRowIdMap();e&&this.#Qe(),this._rebuildRowIdMap(),this.#G.requestPhase(K.COLUMNS,"applyGridConfigUpdate")}#Qe(){const e=this.#H.querySelector(".tbw-shell-header");if(!e)return;const t=this.#f.shell?.header?.title??this.#de.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()}#Je(){if(this.__rowRenderEpoch++,this.#ee){const e=this.#be.length>0?this.#be:this._columns,t=e.filter(e=>!e.hidden),i=e.filter(e=>e.hidden),n=this.#ee.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.#et(e,n,i)}else this._columns=[...e]}}#et(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}#tt(){he(this);const e=function(e,t){if(!e._sortState)return t;e.__originalOrder=[...t];const i=(e.effectiveConfig?.sortHandler??D)(t,e._sortState,e._columns);return i&&"function"==typeof i.then?t:i}(this,Array.isArray(this.#z)?[...this.#z]:[]),t=this.#ee?.processRows(e)??e;this._rows=t,this._rebuildRowIdMap(),this._virtualization.variableHeights&&this.#ne.initializePositionCache(),this._emitDataChange()}#it(e){const t={...n,...e.animation},i=t.mode??"reduced-motion";let r=1;!1===i||"off"===i?r=0:!0!==i&&"on"!==i||(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 i?i?"on":"off":i}_renderVisibleRows(e,t,i=this.__rowRenderEpoch){if(this.#U||(this.#U=(e,t,i)=>this.#ee?.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=ce();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,g=e._virtualization?.variableHeights&&"function"==typeof e.effectiveConfig?.rowHeight?e.effectiveConfig.rowHeight:null;for(let f=0;f<o;f++){const i=t+f,o=e._rows[i],w=e._rowPool[f];if(w.setAttribute("aria-rowindex",String(i+d+1)),c&&r(o,w,i)){w.__epoch=n,w.__rowDataRef=o,w.parentNode!==s&&s.appendChild(w);continue}const m=w.__epoch,b=w.__rowDataRef;let v=w.children.length;v>a&&w.lastElementChild?.classList.contains("tbw-row-loading-overlay")&&v--;const y=m===n&&v===a,C=b!==o,x=!!e._isGridEditMode;let R=!1;if(y&&C)for(let e=0;e<a;e++)if(l[e].externalView&&!w.querySelector(`.cell[data-col="${e}"] [data-external-view]`)){R=!0;break}if(!y||R){const t=oe(w),r=x&&!C||e._activeEditRows===i;t&&!r?(w.__isCustomRow&&(w.className="data-grid-row",w.setAttribute("role","row"),w.__isCustomRow=!1),se(w),ge(e,w,o,i),w.__epoch=n,w.__rowDataRef=o):t&&r?(ue(e,w,o,i),w.__rowDataRef=o):(w.__isCustomRow&&(w.className="data-grid-row",w.setAttribute("role","row"),w.__isCustomRow=!1),ge(e,w,o,i),w.__epoch=n,w.__rowDataRef=o)}else if(C){const t=oe(w),r=e._activeEditRows===i;t&&!r?(se(w),ge(e,w,o,i),w.__epoch=n,w.__rowDataRef=o):(ue(e,w,o,i),w.__rowDataRef=o)}else{const t=oe(w),r=x||e._activeEditRows===i;t&&!r?(se(w),ge(e,w,o,i),w.__epoch=n,w.__rowDataRef=o):ue(e,w,o,i)}let E=!1;const S=e._changedRowIdSet;if(S&&S.size>0)try{const t=e.getRowId?.(o);t&&(E=S.has(t))}catch{}E!==w.classList.contains("changed")&&w.classList.toggle("changed",E);const _=e.effectiveConfig?.rowClass;if(_){const t=w.getAttribute("data-dynamic-classes");t&&t.split(" ").forEach(e=>e&&w.classList.remove(e));try{const e=_(o),t="string"==typeof e?e.split(/\s+/):e;if(t&&t.length>0){let e="";for(const i of t)i&&"string"==typeof i&&(w.classList.add(i),e+=(e?" ":"")+i);w.setAttribute("data-dynamic-classes",e)}else w.removeAttribute("data-dynamic-classes")}catch(p){u("TBW060",`rowClass callback error: ${p}`,e.id),w.removeAttribute("data-dynamic-classes")}}if(g){const e=g(o,i);void 0!==e&&e>0?w.style.setProperty("--tbw-row-height",`${e}px`):w.style.removeProperty("--tbw-row-height")}h&&e._afterRowRender?.({row:o,rowIndex:i,rowElement:w}),w.parentNode!==s&&s.appendChild(w)}}(this,e,t,i,this.#U),this.#pe.size>0)for(const n of this.#pe)this.#xe(n,!0)}#nt={rowCount:-1,colCount:-1,ariaLabel:void 0,ariaDescribedBy:void 0};_updateAriaCounts(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.#nt,this.__rowsBodyEl,this._bodyEl,e,t)}_requestSchedulerPhase(e,t){this.#G.requestPhase(e,t)}_getPluginExtraHeight(){return this.#ee?.getExtraHeight()??0}_getPluginRowHeight(e,t){return this.#ee?.getRowHeight?.(e,t)}_getPluginExtraHeightBefore(e){return this.#ee?.getExtraHeightBefore?.(e)??0}_adjustPluginVirtualStart(e,t,i){return this.#ee?.adjustVirtualStart(e,t,i)}_afterPluginRender(){this.#ee?.afterRender()}_emitPluginEvent(e,t){this.#ee?.emitPluginEvent(e,t)}_schedulerMergeConfig(){this.#F.parseLightDomColumns(this),this.#F.merge(),this.#Ae(),function(e,t,i){const n=at,r=dt,o=new Map;function s(e,t,i,n,r=!1){o.has(e)||o.set(e,{description:t,importHint:i,fields:[],isConfigProperty:r});const s=o.get(e);s.fields.includes(n)||s.fields.push(n)}for(const a of r){const i=e[a.property];(a.isUsed?a.isUsed(i):void 0!==i)&&!ut(t,a.pluginName)&&s(a.pluginName,a.description,ct(a.pluginName),a.property,!0)}const l=e.columns;if(l&&l.length>0)for(const a of l)for(const e of n){const i=a[e.property];if((e.isUsed?e.isUsed(i):void 0!==i)&&!ut(t,e.pluginName)){const t=a.field||"<unknown>";s(e.pluginName,e.description,ct(e.pluginName),t)}}if(o.size>0){const e=[];for(const[t,{description:i,importHint:n,fields:r,isConfigProperty:s}]of o)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 ${ht(t)}Plugin(), ...]`);else{const o=r.slice(0,3).join(", ")+(r.length>3?`, ... (${r.length} total)`:"");e.push(`Column(s) [${o}] use ${i}, but the required plugin is not loaded.\n → Add the plugin to your gridConfig.plugins array:\n ${n}\n plugins: [new ${ht(t)}Plugin(), ...]`)}h([...o.values()].some(e=>e.isConfigProperty)?"TBW002":"TBW001",`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.`,i)}}(this.#f,this.#ee?.getPlugins()??[],this.id),function(e,t){const i=[],n=[];for(const r of e){const e=r.constructor.manifest;if(e?.configRules)for(const t of e.configRules){const e=r.config;if(t.check(e)){const e=`[${ht(r.name)}Plugin] Configuration warning: ${t.message}`;"error"===t.severity?i.push(e):n.push(e)}}}if(n.length>0&&Y())for(const r of n)u("TBW004",r,t);i.length>0&&h("TBW003",`Configuration error:\n\n${i.join("\n\n")}`,t)}(this.#ee?.getPlugins()??[],this.id),function(e,t){if(!Y())return;const i=new Set(e.map(e=>e.name)),n=new Set;for(const r of e){const e=r.constructor.manifest;if(e?.incompatibleWith)for(const o of e.incompatibleWith)if(i.has(o.name)){const e=[r.name,o.name].sort().join("↔");if(n.has(e))continue;n.add(e),u("TBW022",`${ht(r.name)}Plugin and ${ht(o.name)}Plugin are both loaded, but they are currently incompatible.\n\n → ${o.reason}\n\n Consider removing one of these plugins to avoid unexpected behavior.`,t)}}}(this.#ee?.getPlugins()??[],this.id),this.#rt(),this.#be=[...this._columns]}_schedulerProcessColumns(){this.#Je()}_schedulerProcessRows(){this.#tt()}_schedulerRenderHeader(){B(this)}_schedulerUpdateTemplate(){y(this)}_schedulerAfterRender(){this.#ee?.afterRender(),this._virtualization.enabled&&this._virtualization.totalHeightEl&&queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const e=this.#ne.calculateTotalSpacerHeight(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`});"fixed"!==this.#f.fitMode||this.__didInitialAutoSize||(this.__didInitialAutoSize=!0,m(this)),this._restoreFocusAfterRender&&(this._restoreFocusAfterRender=!1,fe(this)),this._virtualization.enabled&&!this.#Fe&&this.#Ve(),this.#V&&(this.#V=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.#$e()})})),this.#ge&&this.#Ce()}get _schedulerIsConnected(){return this.isConnected&&this.#O}get _hostElement(){return this}get _renderRoot(){return this.#H}_emit(e,t){this.#Ke(e,t)}get _accordionIcons(){return{expand:this.#f?.icons?.expand??o.expand,collapse:this.#f?.icons?.collapse??o.collapse}}get _shellState(){return this.#de}_clearRowPool(){this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++}_setup(){this.#qe()}_applyAnimationConfig(e){this.#it(e)}#rt(){!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.#nt,this.__rowsBodyEl,this.#f,this.#de)}#Ce(){const e=this.querySelector(".tbw-grid-root");var t;e&&(this.#ge?(this.#we||(this.#we=function(e){const t=document.createElement("div");return t.className="tbw-loading-overlay",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.appendChild(Ee("large",e)),t}(this.#f?.loadingRenderer)),function(e,t){e.appendChild(t)}(e,this.#we)):(t=this.#we,t?.remove()))}#xe(e,t){const i=this.#me.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)}#Re(e,t,i){const n=this.#me.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)}#qe(){if(this.isConnected&&this._headerRowEl&&this._bodyEl){if(this.#F.parseLightDomColumns(this),this.#C){const e=this.#C;this.#C=void 0,this.#F.merge();const t=this.#ee?.getAll()??[];this.#F.applyState(e,t)}this._bodyEl&&(this._bodyEl.style.display="",this._bodyEl.style.gridTemplateColumns=""),this.#G.requestPhase(K.FULL,"setup")}}#We(e){let t=0,i=0,n=0,r=0,o=0;if(this.#B){const e=this._virtualization.container,s=this.#ae;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.#ee?.onScrollRender(),this._virtualization.variableHeights&&(this.#K&&clearTimeout(this.#K),this.#K=window.setTimeout(()=>{this.#K=0,this.#ne.measureRenderedRowHeights(this._virtualization.start,this._virtualization.end)},100)),this.#B){const s=this.#J;s.scrollTop=e,s.scrollLeft=t,s.scrollHeight=i,s.scrollWidth=n,s.clientHeight=r,s.clientWidth=o,this.#ee?.onScroll(s)}}findHeaderRow(){return this.#H.querySelector(".header-row")}findRenderedRowElement(e){const t=this._virtualization,i=e-t.start;return i>=0&&i<this._rowPool.length&&i<t.end-t.start?this._rowPool[i]: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.#ee?.onCellClick(d)??!1;return this.#Ke("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.#ee?.onRowClick(r)??!1;return this.#Ke("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.#ee?.onHeaderClick(n)??!1}_dispatchKeyDown(e){return this.#ee?.onKeyDown(e)??!1}_getHorizontalScrollOffsets(e,t){return this.#ee?.getHorizontalScrollOffsets(e,t)??{left:0,right:0}}queryPlugins(e){return this.#ee?.queryPlugins(e)??[]}query(e,t){return this.#ee?.queryPlugins({type:e,context:t})??[]}_dispatchCellMouseDown(e){return this.#ee?.onCellMouseDown(e)??!1}_dispatchCellMouseMove(e){this.#ee?.onCellMouseMove(e)}_dispatchCellMouseUp(e){this.#ee?.onCellMouseUp(e)}_afterCellRender(e){this.#ee?.afterCellRender(e)}_hasAfterCellRenderHook(){return this.#ee?.hasAfterCellRenderHook()??!1}_afterRowRender(e){this.#ee?.afterRowRender(e)}_hasAfterRowRenderHook(){return this.#ee?.hasAfterRowRenderHook()??!1}async ready(){return this.#n}async forceLayout(){return this.#G.requestPhase(K.FULL,"forceLayout"),this.#G.whenReady()}async getConfig(){return Object.freeze({...this.#f||{}})}getRowId(e){return Ie(e,this.id,this.#f.getRowId)}getRow(e){return this.#oe.getRow(e)}_getRowEntry(e){return this.#me.get(e)}updateRow(e,t,i="api"){this.#oe.updateRow(e,t,i)}updateRows(e,t="api"){this.#oe.updateRows(e,t)}animateRow(e,t){return Me(this,e,t)}animateRows(e,t){return function(e,t,i){return Promise.all(t.map(t=>Me(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):Me(e,o,i)}(this,e,t)}async insertRow(e,t,i=!0){return this.#oe.insertRow(e,t,i)}async removeRow(e,t=!0){return this.#oe.removeRow(e,t)}suspendProcessing(){}focusCell(e,t){this.#re.focusCell(e,t)}get focusedCell(){return this.#re.focusedCell}scrollToRow(e,t){this.#re.scrollToRow(e,t)}scrollToRowById(e,t){this.#re.scrollToRowById(e,t)}setColumnVisible(e,t){const i=this.#F.setColumnVisible(e,t);return i&&this.requestStateChange(),i}toggleColumnVisibility(e){const t=this.#F.toggleColumnVisibility(e);return t&&this.requestStateChange(),t}isColumnVisible(e){return this.#F.isColumnVisible(e)}showAllColumns(){this.#F.showAllColumns(),this.requestStateChange()}getAllColumns(){return this.#F.getAllColumns()}setColumnOrder(e){this.#F.setColumnOrder(e),this.requestStateChange()}getColumnOrder(){return this.#F.getColumnOrder()}getColumnState(){const e=this.#ee?.getAll()??[];return this.#F.collectState(e)}set columnState(e){e&&(this.#C=e,this.#F.initialColumnState=e,this.#D&&this.#ot(e))}get columnState(){return this.getColumnState()}#ot(e){const t=this.#ee?.getAll()??[];this.#F.applyState(e,t),this.#qe()}requestStateChange(){const e=this.#ee?.getAll()??[];this.#F.requestStateChange(e)}resetColumnState(){this.#C=void 0,this.__originalOrder=[];const e=this.#ee?.getAll()??[];this.#F.resetState(e),this.#F.merge(),this.#qe()}get isToolPanelOpen(){return this.#ce.isPanelOpen}get defaultRowHeight(){return this._virtualization.rowHeight}get expandedToolPanelSections(){return this.#ce.expandedSections}openToolPanel(){this.#ce.openToolPanel()}closeToolPanel(){this.#ce.closeToolPanel()}toggleToolPanel(){this.#ce.toggleToolPanel()}toggleToolPanelSection(e){this.#ce.toggleToolPanelSection(e)}getToolPanels(){return this.#ce.getToolPanels()}registerToolPanel(e){this.#de.apiToolPanelIds.add(e.id),this.#ce.registerToolPanel(e)}unregisterToolPanel(e){this.#de.apiToolPanelIds.delete(e),this.#ce.unregisterToolPanel(e)}getHeaderContents(){return this.#ce.getHeaderContents()}registerHeaderContent(e){this.#de.apiHeaderContentIds.add(e.id),this.#ce.registerHeaderContent(e)}unregisterHeaderContent(e){this.#de.apiHeaderContentIds.delete(e),this.#ce.unregisterHeaderContent(e)}getToolbarContents(){return this.#ce.getToolbarContents()}registerToolbarContent(e){this.#ce.registerToolbarContent(e)}unregisterToolbarContent(e){this.#ce.unregisterToolbarContent(e)}#st=!1;refreshShellHeader(){this.#st||(this.#st=!0,queueMicrotask(()=>{this.#st=!1,this.isConnected&&(this.#Pe(),this.#F.markSourcesChanged(),this.#F.merge(),Xe(this.#de),this.#He(),this.#_e(),this.#lt())}))}#lt(){const e=this.#H.querySelector(".tbw-grid-content")??this.#H.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.#ce.isInitialized){Ke(this.#H,this.#de),Ve(this.#H,this.#f?.shell,this.#de);const e=this.#f?.shell?.toolPanel?.defaultOpen;e&&this.#de.toolPanels.has(e)&&(this.openToolPanel(),this.#de.expandedSections.add(e)),this.#de.isPanelOpen&&(Ye(this.#H,this.#de),Ue(this.#H,this.#de,(this.#f,this.#f)),je(this.#H,this.#de))}this._resizeController=Se(this),this.#Me(e),this.#G.requestPhase(K.COLUMNS,"shellRefresh")}#Oe=new Map;registerStyles(e,t){let i=this.#Oe.get(e);i||(i=new CSSStyleSheet,this.#Oe.set(e,i)),i.replaceSync(t),this.#at()}unregisterStyles(e){this.#Oe.delete(e)&&this.#at()}getRegisteredStyles(){return Array.from(this.#Oe.keys())}#at(){const e=Array.from(this.#Oe.values()),t=document.adoptedStyleSheets.filter(e=>!Array.from(this.#Oe.values()).includes(e));document.adoptedStyleSheets=[...t,...e]}registerExternalFocusContainer(e){this.#re.registerExternalFocusContainer(e)}unregisterExternalFocusContainer(e){this.#re.unregisterExternalFocusContainer(e)}containsFocus(e){return this.#re.containsFocus(e)}#Pe(){$e(this,this.#de),We(this,this.#de),Be(this,this.#de,this.#Ie())}#dt(){const e=this.#H.querySelector(".tbw-shell-header");if(!e)return;Xe(this.#de);const t=function(e,t,i="☰"){const n=e?.header?.title??t.lightDomTitle??"",r=!!n,o=Ne(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""}</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.#f.shell,this.#de,this.#f.icons?.toolPanel),i=document.createElement("div");i.innerHTML=t;const n=i.firstElementChild;n&&(e.replaceWith(n),this.#ct(),Ve(this.#H,this.#f?.shell,this.#de))}#ze(){const e=()=>{const e=this.#de.lightDomTitle,t=this.#de.hasToolButtonsContainer;this.#Pe();const i=this.#de.lightDomTitle,n=this.#de.hasToolButtonsContainer;(i&&!e||n&&!t)&&(this.#F.markSourcesChanged(),this.#F.merge(),this.#dt())},t=()=>{this.__lightDomColumnsCache=void 0,this.#qe()};this.#F.registerLightDomHandler("tbw-grid-header",e),this.#F.registerLightDomHandler("tbw-grid-tool-buttons",e),this.#F.registerLightDomHandler("tbw-grid-tool-panel",e),this.#F.registerLightDomHandler("tbw-grid-column",t),this.#F.registerLightDomHandler("tbw-grid-detail",t),this.#F.observeLightDOM(this)}refreshColumns(){this.__lightDomColumnsCache=void 0,he(this),this.#F.parseLightDomColumns(this);const e=this.#de.lightDomTitle,t=this.#de.hasToolButtonsContainer;this.#Pe();const i=this.#de.lightDomTitle,n=this.#de.hasToolButtonsContainer;(i&&!e||n&&!t)&&(this.#F.markSourcesChanged(),this.#F.merge(),this.#dt()),this.#G.requestPhase(K.COLUMNS,"refreshColumns")}#Be(){this.#ne.updateCachedGeometry()}refreshVirtualWindow(e=!1,t=!1){return this.#ne.refreshVirtualWindow(e,t)}invalidateRowHeight(e,t){this.#ne.invalidateRowHeight(e,t)}#He(){this.#Pe(),this.#F.markSourcesChanged(),this.#F.merge();const e=this.#f?.shell;Qe(this.#H,e,{isPanelOpen:this.#de.isPanelOpen,expandedSections:this.#de.expandedSections},this.#f?.icons)&&(this.#ct(),this.#ce.setInitialized(!0))}#ct(){!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.#H,this.#f,this.#de,{onPanelToggle:()=>this.toggleToolPanel(),onSectionToggle:e=>this.toggleToolPanelSection(e)}),this.#he?.(),this.#he=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.#H,this.#f?.shell,e=>{this.style.setProperty("--tbw-tool-panel-width",`${e}px`)}),this.#ue?.(),this.#ue=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.#f?.shell,this.#de,()=>this.closeToolPanel())}}customElements.get(yt.tagName)||customElements.define(yt.tagName,yt),globalThis.DataGridElement=yt;class Ct{static dependencies;static manifest;aliases;version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#ht;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}attach(e){this.#ht?.abort(),this.#ht=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#ht?.abort(),this.#ht=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?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}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?._hostElement}get disconnectSignal(){return this.#ht?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...o,...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,t){void 0!==t?console.warn(c(e,t,this.gridElement.id,this.name)):console.warn(`${s(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(c(e,t,this.gridElement.id,this.name))}}const xt={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"},Rt={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"},Et={ROOT:`.${xt.ROOT}`,HEADER:`.${xt.HEADER}`,HEADER_ROW:`.${xt.HEADER_ROW}`,HEADER_CELL:`.${xt.HEADER_CELL}`,ROWS_VIEWPORT:`.${xt.ROWS_VIEWPORT}`,ROWS_CONTAINER:`.${xt.ROWS_CONTAINER}`,DATA_ROW:`.${xt.DATA_ROW}`,DATA_CELL:`.${xt.DATA_CELL}`,GROUP_ROW:`.${xt.GROUP_ROW}`,ROW_BY_INDEX:e=>`.${xt.DATA_ROW}[${Rt.ROW_INDEX}="${e}"]`,CELL_BY_FIELD:e=>`.${xt.DATA_CELL}[${Rt.FIELD}="${e}"]`,CELL_AT:(e,t)=>`.${xt.DATA_ROW}[${Rt.ROW_INDEX}="${e}"] .${xt.DATA_CELL}[${Rt.COL_INDEX}="${t}"]`,SELECTED_ROWS:`.${xt.DATA_ROW}.${xt.SELECTED}`,EDITING_CELL:`.${xt.DATA_CELL}.${xt.EDITING}`};function St(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 _t(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}function At(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}function kt(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 Tt(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 Mt(e){if(null==e)return 100;if("number"==typeof e)return e;const t=parseFloat(e);return isNaN(t)?100:t}function Lt(e){return e.map(e=>Mt(e.width))}function It(e){const t=[];let i=0;for(const n of e)t.push(i),i+=Mt(n.width);return t}function Pt(e){return e.reduce((e,t)=>e+Mt(t.width),0)}function Ht(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 Dt="@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 zt(e,t){return("function"==typeof e?e(t):e).filter(e=>!0!==e.hidden&&("function"!=typeof e.hidden||!e.hidden(t)))}function Ft(e,t){return!0===e.disabled||"function"==typeof e.disabled&&e.disabled(t)}function Ot(e,t,i,n=o.submenuArrow){const r=document.createElement("div");r.className="tbw-context-menu",r.setAttribute("role","menu");const s=e.some(e=>!e.separator&&e.icon);for(const o of e){if(o.separator){const e=document.createElement("div");e.className="tbw-context-menu-separator",e.setAttribute("role","separator"),r.appendChild(e);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",o.cssClass&&e.classList.add(o.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",o.id),e.setAttribute("tabindex","-1");const l=Ft(o,t);if(l&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),o.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=o.icon,e.appendChild(t)}else if(s){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=" ",e.appendChild(t)}const a=document.createElement("span");if(a.className="tbw-context-menu-label",a.textContent=o.name,e.appendChild(a),o.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(o.shortcut))o.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=o.shortcut,t.appendChild(e)}e.appendChild(t)}if(o.subMenu?.length){const r=document.createElement("span");r.className="tbw-context-menu-arrow","string"==typeof n?r.innerHTML=n:n instanceof HTMLElement&&r.appendChild(n.cloneNode(!0)),e.appendChild(r),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!o.subMenu)return;const r=Ot(zt(o.subMenu,t),t,i,n);r.classList.add("tbw-context-submenu"),r.style.position="absolute",r.style.left="100%",r.style.top="0",e.style.position="relative",e.appendChild(r)}),e.addEventListener("mouseleave",()=>{const t=e.querySelector(".tbw-context-menu");t&&t.remove()})}l||!o.action||o.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),i(o)}),r.appendChild(e)}return r}const qt="getContextMenuItems";let Nt=null,Gt=null,$t=0;const Wt=[{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 Bt extends Ct{static manifest={queries:[{type:qt,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:Wt}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),$t++}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 Bt.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(){if(!Gt&&"undefined"!=typeof document&&Dt&&(Gt=document.createElement("style"),Gt.id="tbw-context-menu-styles",Gt.textContent=Dt,document.head.appendChild(Gt)),!Nt){Nt=new AbortController;const e=Nt.signal,t=()=>{document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())};document.addEventListener("click",t,{signal:e}),document.addEventListener("keydown",e=>{"Escape"===e.key&&t()},{signal:e}),document.addEventListener("scroll",t,{capture:!0,signal:e})}}uninstallGlobalHandlers(){$t--,$t>0||(Nt&&(Nt.abort(),Nt=null),Gt&&(Gt.remove(),Gt=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(qt,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}))}openMenuAt(e,t,i,n=!1){this.params=e,this.position={x:t,y:i};const r=this.collectPluginItems(e);let o=zt(this.config.items??Wt,e);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]}var s,l;(o=function(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}(o),o.length)&&(document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove()),this.menuElement=null,this.menuElement=Ot(o,e,t=>{t.action&&t.action(e),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),s=this.menuElement,l=()=>this.hideMenu(),s.addEventListener("keydown",e=>{const t=Array.from(s.querySelectorAll('[role="menuitem"]:not(.disabled)'));if(!t.length)return;const i=document.activeElement,n=t.indexOf(i);switch(e.key){case"ArrowDown":e.preventDefault(),t[n<t.length-1?n+1:0].focus();break;case"ArrowUp":e.preventDefault(),t[n>0?n-1:t.length-1].focus();break;case"Enter":case" ":e.preventDefault(),i&&t.includes(i)&&i.click();break;case"Escape":e.preventDefault(),l()}}),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),function(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"}(this.menuElement,t,i),this.isOpen=!0,n&&function(e){const t=e.querySelector('[role="menuitem"]:not(.disabled)');t?.focus()}(this.menuElement),this.emit("context-menu-open",{params:e,items:o}))}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.openMenuAt(o,t.clientX,t.clientY)}))}onKeyDown(e){const t="F10"===e.key&&e.shiftKey,i="ContextMenu"===e.key;if(!t&&!i)return;e.preventDefault();const n=this.grid;if(!n)return;const r=n._focusRow,o=n._focusCol,s=this.visibleColumns[o],l=this.rows[r],a=this.gridElement,d=a?.querySelector(`[data-row="${r}"][data-col="${o}"]`);let c=0,h=0;if(d){const e=d.getBoundingClientRect();c=e.left+e.width/2,h=e.bottom}const u=this.syncSelectionOnContextMenu(r),g={row:l,rowIndex:r,column:s,columnIndex:o,field:s?.field??"",value:l?.[s?.field]??null,isHeader:!1,event:e,selectedRows:u};return this.openMenuAt(g,c,h,!0),!0}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??[]};this.openMenuAt(n,e,t)}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}function Vt(e){return t=>{const i=e.editorParams,n=document.createElement("input");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);return n.addEventListener("change",()=>{var r;if(n.value)"string"==typeof t.value?t.commit(n.value):t.commit(n.valueAsDate);else if(e.nullable)t.commit(null);else{const e=i?.default;"string"==typeof t.value||"string"==typeof e?t.commit("string"==typeof e?e:`${(r=e??new Date).getFullYear()}-${String(r.getMonth()+1).padStart(2,"0")}-${String(r.getDate()).padStart(2,"0")}`):t.commit(e instanceof Date?e:new Date)}}),n.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),n}}const Kt="__tbw_null__";function Ut(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=()=>{""===n.value?e.nullable?t.commit(null):t.commit(i?.min??0):t.commit(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 Vt(e);case"select":return function(e){return t=>{const i=e.editorParams,n=document.createElement("select");if(e.multi&&(n.multiple=!0),e.nullable||i?.includeEmpty){const r=document.createElement("option");r.value=e.nullable?Kt:"",r.textContent=e.nullable?i?.emptyLabel??"(Blank)":i?.emptyLabel??"",null==t.value&&(r.selected=!0),n.appendChild(r)}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 e.nullable&&n.value===Kt?t.commit(null):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 i=n.value;""!==i?"string"==typeof t.value&&i===t.value.replace(/[\n\r]/g,"")||("number"==typeof t.value?t.commit(Number(i)):t.commit(i)):e.nullable?t.commit(null):t.commit("")};return n.addEventListener("blur",r),n.addEventListener("keydown",e=>{"Enter"===e.key&&r(),"Escape"===e.key&&t.cancel()}),n}}(e)}}function jt(e,t,i){if(e instanceof HTMLInputElement){if("checkbox"===e.type)return e.checked;if("number"===e.type){if(""===e.value){if(t?.nullable)return null;const e=t?.editorParams;return e?.min??0}return Number(e.value)}if("date"===e.type)return e.value?"string"==typeof i?e.value:e.valueAsDate:t?.nullable?null:"string"==typeof i?i||(new Date).toISOString().slice(0,10):i??new Date;if("number"==typeof i){if(""===e.value){if(t?.nullable)return null;const e=t?.editorParams;return e?.min??0}return Number(e.value)}return""===e.value&&null==i?t?.nullable?null:"":"string"==typeof i&&e.value===i.replace(/[\n\r]/g,"")?i:e.value}return"number"===t?.type&&""!==e.value||"number"==typeof i&&""!==e.value?Number(e.value):null==i&&""===e.value?t?.nullable?null:"":e.value}class Yt{#ut=new Map;#gt;constructor(e){this.#gt=e}setInvalid(e,t,i=""){let n=this.#ut.get(e);n||(n=new Map,this.#ut.set(e,n)),n.set(t,i),this.#gt(e,t,!0)}clearInvalid(e,t){const i=this.#ut.get(e);i&&(i.delete(t),0===i.size&&this.#ut.delete(e)),this.#gt(e,t,!1)}clearRowInvalid(e){const t=this.#ut.get(e);if(t){const i=Array.from(t.keys());this.#ut.delete(e),i.forEach(t=>this.#gt(e,t,!1))}}clearAllInvalid(){const e=Array.from(this.#ut.entries());this.#ut.clear(),e.forEach(([e,t])=>{t.forEach((t,i)=>this.#gt(e,i,!1))})}isCellInvalid(e,t){return this.#ut.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#ut.get(e)?.get(t)}hasInvalidCells(e){const t=this.#ut.get(e);return!!t&&t.size>0}getInvalidFields(e){return new Map(this.#ut.get(e)??[])}}function Xt(e,t,i){const n=e.get(t);return!!n&&!Zt(n,i)}function Zt(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(typeof e!=typeof t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Zt(e[i],t[i]))return!1;return!0}if("object"==typeof e){const i=e,n=t,r=Object.keys(i),o=Object.keys(n);if(r.length!==o.length)return!1;for(const e of r)if(!Zt(i[e],n[e]))return!1;return!0}return!1}function Qt(e,t,i){e.set(t,structuredClone(i))}function Jt(e,t,i){const n=e.get(t);if(!n)return!1;const r=n,o=i;for(const s of Object.keys(r))o[s]=r[s];return!0}class ei{baselines=new Map;baselinesWereCaptured=!1;newRowIds=new Set;changedRowIds=new Set;committedDirtyRowIds=new Set;clear(){this.changedRowIds.clear(),this.committedDirtyRowIds.clear(),this.baselines.clear(),this.newRowIds.clear(),this.baselinesWereCaptured=!1}capture(e,t){const i=this.baselines.size;!function(e,t,i){for(const n of t)try{const t=i(n);null==t||e.has(t)||e.set(t,structuredClone(n))}catch{}}(this.baselines,e,t),this.baselines.size>i&&(this.baselinesWereCaptured=!0)}drainCapturedFlag(){return this.baselinesWereCaptured?(this.baselinesWereCaptured=!1,this.baselines.size):null}isRowDirty(e,t){return Xt(this.baselines,e,t)}hasAnyDirty(e){if(this.newRowIds.size>0)return!0;for(const[t]of this.baselines){const i=e(t);if(i&&Xt(this.baselines,t,i))return!0}return!1}isCellDirty(e,t,i){return function(e,t,i,n){const r=e.get(t);return!!r&&!Zt(r[n],i[n])}(this.baselines,e,t,i)}getRowDirtyState(e,t){const i=this.newRowIds.has(e);return{isNew:i,isCommittedDirty:!i&&this.committedDirtyRowIds.has(e)&&Xt(this.baselines,e,t),hasBaseline:this.baselines.has(e)}}markPristine(e,t){Qt(this.baselines,e,t),this.newRowIds.delete(e),this.changedRowIds.delete(e),this.committedDirtyRowIds.delete(e)}markNew(e){this.newRowIds.add(e),this.committedDirtyRowIds.add(e)}markDirty(e){this.changedRowIds.add(e),this.committedDirtyRowIds.add(e)}markAllPristine(e){for(const[t]of this.baselines){const i=e(t);i&&Qt(this.baselines,t,i)}this.newRowIds.clear(),this.changedRowIds.clear(),this.committedDirtyRowIds.clear()}getOriginalRow(e){return function(e,t){const i=e.get(t);return i?structuredClone(i):void 0}(this.baselines,e)}hasBaseline(e){return this.baselines.has(e)}getDirtyRows(e){const t=[];for(const[i,n]of this.baselines){const r=e(i);r&&Xt(this.baselines,i,r)&&t.push({id:i,original:structuredClone(n),current:r})}for(const i of this.newRowIds){const n=e(i);n&&t.push({id:i,original:void 0,current:n})}return t}getDirtyRowIds(e){const t=[];for(const[i]of this.baselines){const n=e(i);n&&Xt(this.baselines,i,n)&&t.push(i)}for(const i of this.newRowIds)t.push(i);return t}revertRow(e,t){const i=Jt(this.baselines,e,t);return i&&(this.changedRowIds.delete(e),this.committedDirtyRowIds.delete(e)),i}revertAll(e){for(const[t]of this.baselines){const i=e(t);i&&Jt(this.baselines,t,i)}this.changedRowIds.clear(),this.committedDirtyRowIds.clear()}getChangedRows(e){const t=[];for(const i of this.changedRowIds){const n=e(i);n&&t.push(n)}return t}getChangedRowIds(){return Array.from(this.changedRowIds)}isRowChanged(e){return this.changedRowIds.has(e)}}const ti='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function ii(e){return"string"==typeof e&&("__proto__"!==e&&"constructor"!==e&&"prototype"!==e)}function ni(e){}function ri(e,t){return!1===e.onBeforeEditClose?.(t)}function oi(e,t,i,n,r,o,s,l){if(!n.editable)return;if(o.classList.contains("editing"))return;const{grid:a,isGridMode:d,config:c,editingCells:h,editorValueCallbacks:g}=e;let p;try{p=a.getRowId?.(t)}catch{}const f=p?e=>a.updateRow(p,e,"cascade"):ni,w=ii(n.field)?t[n.field]:void 0;o.classList.add("editing"),h.add(`${i}:${r}`);const m=l??o.parentElement;m&&function(e){const t=(e.__editingCellCount??0)+1;e.__editingCellCount=t,e.setAttribute("data-has-editing","")}(m);let b=!1;const v=r=>{if(b||!d&&!e.isEditSessionActive())return;const o=p?a._getRowEntry(p):void 0,s=o?.row??t,l=o?.index??i;e.commitCellValue(l,n,r,s)},y=()=>{if(b=!0,ii(n.field)){const e=p?a._getRowEntry(p):void 0;(e?.row??t)[n.field]=w}},C=document.createElement("div");C.className="tbw-editor-host",o.innerHTML="",o.appendChild(C),C.addEventListener("keydown",t=>{if("Enter"===t.key){if(d){t.stopPropagation(),t.preventDefault();const e=C.querySelector("input,textarea,select");return void(e&&v(jt(e,n,w)))}if(ri(c,t))return;t.stopPropagation(),t.preventDefault(),b=!0,e.exitRowEdit(i,!1)}if("Escape"===t.key){if(d)return t.stopPropagation(),void t.preventDefault();if(ri(c,t))return;t.stopPropagation(),t.preventDefault(),y(),e.exitRowEdit(i,!0)}});const x=n,R=x.__editorTemplate,E=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}}(a,x)??Ut(n),S=w,_=`${i}:${n.field}`,A=[];g.set(_,e=>{for(const t of A)t(e)});const k=e=>{A.push(e)};if("template"===E&&R)!function(e,t,i,n,r,o,s,l,a){const d=i.__editorTemplate;if(!d)return;const c=d.cloneNode(!0),h=i.__compiledEditor;h?c.innerHTML=h({row:n,value:r,field:i.field,column:i,commit:o,cancel:s}):c.querySelectorAll("*").forEach(e=>{1===e.childNodes.length&&e.firstChild?.nodeType===Node.TEXT_NODE&&(e.textContent=e.textContent?.replace(/{{\s*value\s*}}/g,null==r?"":String(r)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(e,t)=>{if(!ii(t))return"";const i=n[t];return null==i?"":String(i)})||"")});const u=c.querySelector("input,textarea,select");if(u){u instanceof HTMLInputElement&&"checkbox"===u.type?u.checked=!!r:u.value=String(r??"");let t=!1;u.addEventListener("blur",()=>{t||o(jt(u,i,r))}),u.addEventListener("keydown",n=>{const l=n;if("Enter"===l.key){if(ri(e.config,l))return;l.stopPropagation(),l.preventDefault(),t=!0,o(jt(u,i,r)),e.exitRowEdit(a,!1)}if("Escape"===l.key){if(ri(e.config,l))return;l.stopPropagation(),l.preventDefault(),s(),e.exitRowEdit(a,!0)}}),u instanceof HTMLInputElement&&"checkbox"===u.type&&u.addEventListener("change",()=>o(u.checked)),l||setTimeout(()=>u.focus({preventScroll:!0}),0)}t.appendChild(c)}(e,C,x,t,w,v,y,s,i),k(e=>{if(null!=e&&"object"==typeof e)return;const t=C.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if("string"==typeof E){const e=document.createElement(E);e.value=S,e.addEventListener("change",()=>v(e.value)),k(t=>{e.value=t}),C.appendChild(e),s||queueMicrotask(()=>{const e=C.querySelector(ti);e?.focus({preventScroll:!0})})}else if("function"==typeof E){const e=E({row:t,rowId:p??"",value:S,field:n.field,column:n,commit:v,cancel:y,updateRow:f,onValueChange:k});if("string"==typeof e)C.innerHTML=e,function(e,t,i,n){const r=e.querySelector("input,textarea,select");r&&(r.addEventListener("blur",()=>{i(jt(r,t,n))}),r instanceof HTMLInputElement&&"checkbox"===r.type?r.addEventListener("change",()=>i(r.checked)):r instanceof HTMLSelectElement&&r.addEventListener("change",()=>i(jt(r,t,n))))}(C,n,v,w),k(e=>{const t=C.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if(e instanceof Node){C.appendChild(e);e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?k(t=>{e instanceof HTMLInputElement&&"checkbox"===e.type?e.checked=!!t:e.value=String(t??"")}):o.setAttribute("data-editor-managed","")}else!e&&C.hasChildNodes()&&o.setAttribute("data-editor-managed","");s||queueMicrotask(()=>{const e=C.querySelector(ti);e?.focus({preventScroll:!0})})}else if(E&&"object"==typeof E){const i=document.createElement("div");i.setAttribute("data-external-editor",""),i.setAttribute("data-field",n.field),C.appendChild(i),o.setAttribute("data-editor-managed","");const r={row:t,rowId:p??"",value:S,field:n.field,column:n,commit:v,cancel:y,updateRow:f,onValueChange:k};if(E.mount)try{E.mount({placeholder:i,context:r,spec:E})}catch(T){u("TBW080",`External editor mount error for column '${n.field}': ${T}`,e.grid.id)}else a.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:i,spec:E,context:r}}))}}function si(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 li(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 ai(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const di="(Blank)";function ci(e){if(e instanceof Date)return e.getTime();const t=Number(e);if(!isNaN(t))return t;return new Date(e).getTime()}function hi(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(di):!o.some(t=>e.includes(t)))}if("in"===t.operator){const e=t.value;return!!Array.isArray(e)&&(0===o.length?e.includes(di):o.some(t=>e.includes(t)))}}if("notIn"===t.operator)return null==r||""===r?!Array.isArray(t.value)||!t.value.includes(di):Array.isArray(t.value)&&!t.value.includes(r);if("in"===t.operator)return null==r||""===r?Array.isArray(t.value)&&t.value.includes(di):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 ci(r)<ci(t.value);case"lessThanOrEqual":return ci(r)<=ci(t.value);case"greaterThan":return ci(r)>ci(t.value);case"greaterThanOrEqual":return ci(r)>=ci(t.value);case"between":return ci(r)>=ci(t.value)&&ci(r)<=ci(t.valueTo);default:return!0}}(e,t,i,n?.get(t.field)))):e}function ui(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(di),[...n].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t)))}function gi(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(di),n.set(r,[...o].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t))));return n}const pi="__tbw_expander";function fi(e){return e.field===pi}function wi(e){return!0===e.meta?.utility}function mi(e){return e?e.toISOString().split("T")[0]:""}function bi(e){return e?"string"==typeof e?e:"number"==typeof e?mi(new Date(e)):"":""}function vi(e,t,i,n,r,o){const{field:s,column:l}=t,a=function(e){if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-filter-item-height");if(t&&t.trim()){const e=parseFloat(t);if(!isNaN(e)&&e>0)return e}}return 28}(e),d=e=>{if(null==e)return"(Blank)";if(l.format&&!l.filterValue){const t=l.format(e,void 0);if(t)return t}return String(e)};i=i.slice().sort((e,t)=>d(e).localeCompare(d(t)));const c=document.createElement("div");c.className="tbw-filter-search";const h=document.createElement("input");h.type="text",h.placeholder="Search...",h.className="tbw-filter-search-input",h.value=o.get(s)??"",c.appendChild(h),e.appendChild(c);const u=document.createElement("div");u.className="tbw-filter-actions";const g=document.createElement("label");g.className="tbw-filter-value-item",g.style.padding="0",g.style.margin="0";const p=document.createElement("input");p.type="checkbox",p.className="tbw-filter-checkbox";const f=document.createElement("span");f.textContent="Select All",g.appendChild(p),g.appendChild(f),u.appendChild(g);const w=new Map;i.forEach(e=>{const t=null==e?"__null__":String(e);w.set(t,!n.has(e))});const m=()=>{const e=[...w.values()],t=e.every(e=>e),i=e.every(e=>!e);p.checked=t,p.indeterminate=!t&&!i};p.addEventListener("change",()=>{const e=p.checked;for(const t of w.keys())w.set(t,e);m(),R()}),m(),e.appendChild(u);const b=document.createElement("div");b.className="tbw-filter-values";const v=document.createElement("div");v.className="tbw-filter-values-spacer",b.appendChild(v);const y=document.createElement("div");y.className="tbw-filter-values-content",b.appendChild(y);let C=[];const x=(e,t)=>{const i=d(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=w.get(n)??!0,o.dataset.value=n,o.addEventListener("change",()=>{w.set(n,o.checked),m()});const s=document.createElement("span");return s.textContent=i,r.appendChild(o),r.appendChild(s),r},R=()=>{const e=C.length,t=b.clientHeight,i=b.scrollTop;if(v.style.height=e*a+"px",e<=50/3)return y.innerHTML="",y.style.transform="translateY(0px)",void C.forEach((e,t)=>{y.appendChild(x(e,t))});const n=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:a,overscan:3});y.style.transform=`translateY(${n.offsetY}px)`,y.innerHTML="";for(let r=n.start;r<n.end;r++)y.appendChild(x(C[r],r-n.start))},E=e=>{const t=r.caseSensitive??!1,n=t?e:e.toLowerCase();if(C=i.filter(i=>{const r=d(i),o=t?r:r.toLowerCase();return!e||o.includes(n)}),C.sort((e,t)=>{const i=null==e?"__null__":String(e),n=null==t?"__null__":String(t),r=w.get(i)??!0;return r!==(w.get(n)??!0)?r?-1:1:d(e).localeCompare(d(t))}),0===C.length){v.style.height="0px",y.innerHTML="";const e=document.createElement("div");return e.className="tbw-filter-no-match",e.textContent="No matching values",void y.appendChild(e)}R()};let S;b.addEventListener("scroll",()=>{C.length>0&&R()},{passive:!0}),E(h.value),e.appendChild(b),h.addEventListener("input",()=>{clearTimeout(S),S=setTimeout(()=>{o.set(s,h.value),E(h.value)},r.debounceMs??150)});const _=document.createElement("div");_.className="tbw-filter-buttons";const A=document.createElement("button");A.className="tbw-filter-apply-btn",A.textContent="Apply",A.addEventListener("click",()=>{const e=[];for(const[t,n]of w)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)}),_.appendChild(A);const k=document.createElement("button");k.className="tbw-filter-clear-btn",k.textContent="Clear Filter",k.addEventListener("click",()=>{t.clearFilter()}),_.appendChild(k),e.appendChild(_)}function yi(e,t){if("number"==typeof e)return e;if("string"==typeof e){const i=parseFloat(e);return isNaN(i)?t:i}return t}class Ci extends Ct{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;computeSelected(){const e={},t=[];for(const[i,n]of this.filters)if("set"===n.type)if("in"===n.operator&&Array.isArray(n.value))e[i]=n.value;else if("notIn"===n.operator){const e=this.grid.effectiveConfig?.columns?.find(e=>e.field===i);t.push({field:i,filterValue:e?.filterValue})}if(t.length>0){const i=gi(this.sourceRows,t);for(const{field:n}of t){const t=this.excludedValues.get(n),r=i.get(n)??[];e[n]=t?r.filter(e=>!t.has(e)):r}}return e}syncExcludedValues(e,t){if(t)if("set"===t.type&&"notIn"===t.operator&&Array.isArray(t.value))this.excludedValues.set(e,new Set(t.value));else if("set"===t.type&&"in"===t.operator&&Array.isArray(t.value)){const i=this.sourceRows;if(!i||0===i.length)return void this.excludedValues.delete(e);const n=t.value,r=new Set(n.map(e=>null==e?di:e)),o=this.getUniqueValues(e),s=new Set(o.filter(e=>!r.has(e)));this.excludedValues.set(e,s)}else"set"===t.type&&this.excludedValues.delete(e);else 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=hi([...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(wi(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),r?e.setAttribute("aria-description","Filtered"):e.removeAttribute("aria-description"),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"),e.setAttribute("aria-description","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,i,n){if(null===i)this.filters.delete(e),this.syncExcludedValues(e,null);else{const t={...i,field:e};this.filters.set(e,t),this.syncExcludedValues(e,t)}if(this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,!n?.silent){this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.();const n=this.grid.effectiveConfig?.columns?.find(t=>t.field===e)?.header??e;t(this.gridElement,null===i?`Filter cleared from ${n}`:`Filter applied on ${n}`)}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,t){this.filters.clear(),this.excludedValues.clear();for(const i of e)this.filters.set(i.field,i),this.syncExcludedValues(i.field,i);this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,t?.silent||(this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.()),this.emitPluginEvent("filter-applied",{filters:[...this.filters.values()]}),this.requestRender()}clearAllFilters(e){this.filters.clear(),this.excludedValues.clear(),this.searchText.clear(),this.applyFiltersInternal(e?.silent),e?.silent||t(this.gridElement,"All filters cleared")}clearFieldFilter(e,i){if(this.filters.delete(e),this.excludedValues.delete(e),this.searchText.delete(e),this.applyFiltersInternal(i?.silent),!i?.silent){const i=this.grid.effectiveConfig?.columns?.find(t=>t.field===e)?.header??e;t(this.gridElement,`Filter cleared from ${i}`)}}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 ui(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=ui(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){const r=this.filters.get(e);if("in"===r?.operator&&"set"===r.type&&Array.isArray(r.value)&&!this.excludedValues.has(e)){const t=r.value,i=new Set(t.map(e=>null==e?di:e)),o=new Set(n.filter(e=>!i.has(e)));this.excludedValues.set(e,o)}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,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 a=!1;if(this.config.filterPanelRenderer&&(this.config.filterPanelRenderer(i,l),a=i.children.length>0),!a&&t.type){const e=this.grid.effectiveConfig.typeDefaults?.[t.type];e?.filterPanelRenderer&&(e.filterPanelRenderer(i,l),a=i.children.length>0)}if(!a){const e=t.type;"number"===e?function(e,t,i,n){const{field:r,column:o}=t,s=o.filterParams,l=o.editorParams,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=yi(s?.min??l?.min,d),u=yi(s?.max??l?.max,c),g=s?.step??l?.step??1,p=n.get(r);let f=h,w=u;const m="blank"===p?.operator;"between"===p?.operator?(f=yi(p.value,h),w=yi(p.valueTo,u)):"greaterThanOrEqual"===p?.operator?f=yi(p.value,h):"lessThanOrEqual"===p?.operator&&(w=yi(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 R=document.createElement("div");R.className="tbw-filter-range-group";const E=document.createElement("label");E.textContent="Max",E.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),R.appendChild(E),R.appendChild(S),b.appendChild(R),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 M=document.createElement("input");M.type="range",M.className="tbw-filter-range-thumb tbw-filter-range-thumb-max",M.min=String(h),M.max=String(u),M.step=String(g),M.value=String(w),_.appendChild(A),_.appendChild(k),_.appendChild(T),_.appendChild(M),e.appendChild(_);const L=document.createElement("label");L.className="tbw-filter-blank-option";const I=document.createElement("input");I.type="checkbox",I.className="tbw-filter-blank-checkbox",I.checked=m;const P=document.createTextNode("Blank");L.appendChild(I),L.appendChild(P);const H=e=>{C.disabled=e,S.disabled=e,T.disabled=e,M.disabled=e,b.classList.toggle("tbw-filter-disabled",e),_.classList.toggle("tbw-filter-disabled",e)};H(m),I.addEventListener("change",()=>{H(I.checked)}),e.appendChild(L);const D=()=>{const e=parseFloat(T.value),t=parseFloat(M.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(M.value));T.value=String(e),C.value=String(e),D()}),M.addEventListener("input",()=>{const e=Math.max(parseFloat(M.value),parseFloat(T.value));M.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))),M.value=String(e),D()}),D();const z=document.createElement("div");z.className="tbw-filter-buttons";const F=document.createElement("button");F.className="tbw-filter-apply-btn",F.textContent="Apply",F.addEventListener("click",()=>{if(I.checked)return void t.applyTextFilter("blank","");const e=parseFloat(C.value),i=parseFloat(S.value);t.applyTextFilter("between",e,i)}),z.appendChild(F);const O=document.createElement("button");O.className="tbw-filter-clear-btn",O.textContent="Clear Filter",O.addEventListener("click",()=>{t.clearFilter()}),z.appendChild(O),e.appendChild(z)}(i,l,n,this.filters):"date"===e?function(e,t,i,n){const{field:r,column:o}=t,s=o.filterParams,l=o.editorParams,a=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())),d=a.length>0?new Date(Math.min(...a.map(e=>e.getTime()))):null,c=a.length>0?new Date(Math.max(...a.map(e=>e.getTime()))):null,h=bi(s?.min)||bi(l?.min)||mi(d),u=bi(s?.max)||bi(l?.max)||mi(c),g=n.get(r);let p="",f="";const w="blank"===g?.operator;"between"===g?.operator?(p=bi(g.value)||"",f=bi(g.valueTo)||""):"greaterThanOrEqual"===g?.operator?p=bi(g.value)||"":"lessThanOrEqual"===g?.operator&&(f=bi(g.value)||"");const m=document.createElement("div");m.className="tbw-filter-date-range";const b=document.createElement("div");b.className="tbw-filter-date-group";const v=document.createElement("label");v.textContent="From",v.className="tbw-filter-range-label";const y=document.createElement("input");y.type="date",y.className="tbw-filter-date-input",h&&(y.min=h),u&&(y.max=u),y.value=p,b.appendChild(v),b.appendChild(y),m.appendChild(b);const C=document.createElement("span");C.className="tbw-filter-range-separator",C.textContent="–",m.appendChild(C);const x=document.createElement("div");x.className="tbw-filter-date-group";const R=document.createElement("label");R.textContent="To",R.className="tbw-filter-range-label";const E=document.createElement("input");E.type="date",E.className="tbw-filter-date-input",h&&(E.min=h),u&&(E.max=u),E.value=f,x.appendChild(R),x.appendChild(E),m.appendChild(x),e.appendChild(m);const S=document.createElement("label");S.className="tbw-filter-blank-option";const _=document.createElement("input");_.type="checkbox",_.className="tbw-filter-blank-checkbox",_.checked=w;const A=document.createTextNode("Show only blank");S.appendChild(_),S.appendChild(A);const k=e=>{y.disabled=e,E.disabled=e,m.classList.toggle("tbw-filter-disabled",e)};k(w),_.addEventListener("change",()=>{k(_.checked)}),e.appendChild(S);const T=document.createElement("div");T.className="tbw-filter-buttons";const M=document.createElement("button");M.className="tbw-filter-apply-btn",M.textContent="Apply",M.addEventListener("click",()=>{if(_.checked)return void t.applyTextFilter("blank","");const e=y.value,i=E.value;e&&i?t.applyTextFilter("between",e,i):e?t.applyTextFilter("greaterThanOrEqual",e):i?t.applyTextFilter("lessThanOrEqual",i):t.clearFilter()}),T.appendChild(M);const L=document.createElement("button");L.className="tbw-filter-clear-btn",L.textContent="Clear Filter",L.addEventListener("click",()=>{t.clearFilter()}),T.appendChild(L),e.appendChild(T)}(i,l,n,this.filters):vi(i,l,n,o,{caseSensitive:this.config.caseSensitive,debounceMs:this.config.debounceMs},this.searchText)}}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===Ci.supportsAnchorPositioning&&(Ci.supportsAnchorPositioning=CSS.supports("anchor-name","--test")),Ci.supportsAnchorPositioning}positionPanel(e,t){const i=t.closest(".cell")??t;if(i.style.anchorName="--tbw-filter-anchor",this.panelAnchorElement=i,Ci.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"))})}applySetFilter(e,t,i){if(this.excludedValues.set(e,new Set(t)),0===t.length)this.filters.delete(e);else{const n=this.filters.get(e);if("in"===n?.operator){const n=this.getUniqueValues(e),r=new Set(t),o=n.filter(e=>!r.has(e));this.filters.set(e,{field:e,type:"set",operator:"in",value:o,...void 0!==i&&{valueTo:i}})}else 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(e){this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null;const t=[...this.filters.values()];if(this.config.filterHandler){this.gridElement.setAttribute("aria-busy","true");const i=this.config.filterHandler(t,this.sourceRows),n=i=>{this.gridElement.removeAttribute("aria-busy"),this.cachedResult=i,this.grid.rows=i,e||(this.emit("filter-change",{filters:t,filteredRowCount:i.length,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.()),this.emitPluginEvent("filter-applied",{filters:t}),this.requestRender()};return void(i&&"function"==typeof i.then?i.then(n):n(i))}e||(this.emit("filter-change",{filters:t,filteredRowCount:0,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.()),this.emitPluginEvent("filter-applied",{filters:t}),this.requestRender()}getColumnState(e){if(!this.config.trackColumnState)return;const t=this.filters.get(e);return t?{filter:{type:t.type,operator:t.operator,value:t.value,valueTo:t.valueTo}}:void 0}applyColumnState(e,t){if(!this.config.trackColumnState)return;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 xi(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Ri(e){return e.map(e=>e.id?e:(e.header||h("TBW113",'ColumnGroupDefinition requires either an "id" or a "header" to generate an id from.'),{...e,id:xi(e.header)}))}function Ei(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}function Si(e,t){const i=e.columns[0],n=e.columns[e.columns.length-1],r=i?t.findIndex(e=>e.field===i.field):-1,o=n?t.findIndex(e=>e.field===n.field):-1;return-1!==r&&-1!==o?[r,o]:null}function _i(e,t){const i=new Set,n=[];for(const r of e){if(String(r.id).startsWith("__implicit__"))continue;const e=Si(r,t);e&&n.push(e)}for(const r of e){if(!String(r.id).startsWith("__implicit__"))continue;const e=Si(r,t);if(!e)continue;const[o,s]=e;n.some(([e,t])=>o>=e&&s<=t)&&i.add(String(r.id))}return i}const Ai={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]},ki=new Map,Ti={register(e,t){ki.set(e,t)},unregister(e){ki.delete(e)},get(e){if(void 0!==e)return"function"==typeof e?e:ki.get(e)??Ai[e]},run(e,t,i,n){const r=this.get(e);return r?r(t,i,n):void 0},has:e=>ki.has(e)||e in Ai,list:()=>[...Object.keys(Ai),...ki.keys()]},Mi={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};Ti.register.bind(Ti),Ti.unregister.bind(Ti);const Li=Ti.get.bind(Ti),Ii=Ti.run.bind(Ti);function Pi({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}Ti.list.bind(Ti);function Hi(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}function Di(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 zi extends Ct{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#pt(){return this.grid}get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,animation:"slide"}}attach(e){super.attach(e),this.parseLightDomDetail()}parseLightDomDetail(){const e=this.gridElement;if(!e)return;const t=e.querySelector("tbw-grid-detail");if(!t)return;const i=this.#pt.__frameworkAdapter;if(i?.parseDetailElement){const e=i.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)=>T(M(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.#ft(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)}#ft(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:zi.DEFAULT_DETAIL_HEIGHT}toggleAndEmit(e,t){this.expandedRows=Hi(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(fi)}(t);if(i)return t;const n=(r=this.name,{field:pi,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.#wt())}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusCol,i=this.grid._focusRow,n=this.visibleColumns[t];if(!n||!fi(n))return;const r=this.rows[i];return r?(e.preventDefault(),this.toggleAndEmit(r,i),this.requestRenderWithFocus(),!0):void 0}afterRender(){this.#wt()}onScrollRender(){this.config.detailRenderer&&0!==this.expandedRows.size&&this.#wt()}#wt(){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.#pt.__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=Di(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.#ft(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=Hi(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.#pt;"function"==typeof e.refreshColumns?e.refreshColumns():this.requestRender()}}}function Fi(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 qi(e,t){return e.find(e=>e.field===t)?.direction}function Ni(e){return e.pinned??e.sticky??e.meta?.pinned??e.meta?.sticky}function Gi(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 $i(e,t){const i=Ni(e);return!!i&&"left"===Gi(i,t)}function Wi(e,t){const i=Ni(e);return!!i&&"right"===Gi(i,t)}function Bi(e){return e.some(e=>null!=Ni(e))}function Vi(e,t){const i=Array.from(e.querySelectorAll(".header-row .cell"));if(!i.length)return;const n=ee(e);let r=0;for(const s of t)if($i(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(Wi(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 Ki(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 Ui="canMoveColumn";function ji(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=en(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 Yi(e){const t=document.createElement("div");return t.className=`tbw-aggregation-rows tbw-aggregation-rows-${e}`,t.setAttribute("role","presentation"),t}function Xi(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?Zi(t,o,i,n):Qi(t,o,i,n),e.appendChild(t)}}function Zi(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}=Ji(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 Qi(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}=Ji(t,r,n);i.textContent=null!=o?s?s(o,r.field,r):String(o):"",e.appendChild(i)}}function Ji(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=Li(o.aggFunc);e&&(n=e(i,t.field,t)),r=o.formatter}else{const e=Li(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 en(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 tn(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 nn=function(e){return Mi[e]??Mi.sum};function rn(e,t){return[...e,t].join("|")}function on(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=sn(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=rn([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 sn(e,t,i,n,r,o,s){const l=[];if(0===t.length){const t=ln(e,i,n,r),a=an(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=ln(g,i,n,r),a=an(t);let h;c&&(h=sn(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 ln(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=nn(i.aggFunc),l=n.length>0?s(n):null;r[rn([o],i.field)]=l}return r}function an(e){let t=0;for(const i of Object.values(e))t+=i??0;return t}const dn=["sum","avg","count","min","max","first","last"];function cn(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(hn("Options",()=>function(e,t){const{config:i,callbacks:n,signal:r}=t,o=document.createElement("div");return o.className="tbw-pivot-options",o.appendChild(fn("Enable Pivot View",e,e=>{n.onTogglePivot(e)},r)),o.appendChild(fn("Show Row Totals",i.showTotals??!0,e=>{n.onOptionChange("showTotals",e)},r)),o.appendChild(fn("Show Grand Total",i.showGrandTotal??!0,e=>{n.onOptionChange("showGrandTotal",e)},r)),o}(i,o))),s.appendChild(hn("Row Groups",()=>un("rowGroups",o))),s.appendChild(hn("Column Groups",()=>un("columnGroups",o))),s.appendChild(hn("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(pn(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(hn("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 hn(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 un(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(gn(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 gn(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 pn(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 dn){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 fn(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 wn extends Ct{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:wn.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=on(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=rn([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(wn.PANEL_ID)||this.grid.toggleToolPanelSection(wn.PANEL_ID)}hidePanel(){this.grid.closeToolPanel()}togglePanel(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(wn.PANEL_ID)}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(wn.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 cn(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 mn="tbw-print-isolation-style";async function bn(e,t={}){const{orientation:i="landscape"}=t,n=e.id;document.querySelectorAll(`#${CSS.escape(n)}`).length>1&&u("TBW093",`Multiple elements found with id="${n}". Print isolation may not work correctly. Ensure each grid has a unique ID.`,n,"print"),document.getElementById(mn)?.remove();const r=function(e,t){const i=document.createElement("style");return i.id=mn,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(mn)?.remove(),e()};window.addEventListener("afterprint",t),window.print(),setTimeout(()=>{window.removeEventListener("afterprint",t),document.getElementById(mn)?.remove(),e()},5e3)})}const vn={button:!1,orientation:"landscape",warnThreshold:500,maxRows:0,includeTitle:!0,includeTimestamp:!0,title:"",isolate:!1};function yn(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 Cn="__tbw_row_drag";function xn(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 Rn(e){const t=xn(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function En(e){return e.map(Rn)}function Sn(e,t,i){return i.some(i=>function(e,t,i){const n=xn(i);return e>=n.startRow&&e<=n.endRow&&t>=n.startCol&&t<=n.endCol}(e,t,i))}function _n(e){const t=[],i=xn(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 An(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function kn(e,t){const i=xn(e),n=xn(t);return i.startRow===n.startRow&&i.startCol===n.startCol&&i.endRow===n.endRow&&i.endCol===n.endCol}const Tn="__tbw_checkbox";function Mn(e,t){return Math.floor(e/t)}async function Ln(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 In(e,t,i){const n=Mn(e,t),r=i.get(n);if(!r)return;return r[e%t]}function Pn(e,t,i){return void 0!==e.id?String(e.id):i?`${i}-${t}`:String(t)}function Hn(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}function Dn(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=Pn(l,s,i),d=l[r];if(Array.isArray(d)&&d.length>0){o.add(a);const e=Dn(d,t,a,n+1);for(const t of e)o.add(t)}}return o}function zn(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=Pn(l,s,n);if(a===t)return[a];const d=l[o];if(Array.isArray(d)&&d.length>0){const e=zn(d,t,i,a,r+1);if(e)return[a,...e]}}return null}function Fn(e,t,i,n){const r=zn(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 qn(e,t,i){const n=[...e.undoStack,t];for(;n.length>i;)n.shift();return{undoStack:n,redoStack:[]}}function Nn(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 Gn(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 $n(e){const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}class Wn extends Ct{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),this.gridElement.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:Wn.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(Wn.PANEL_ID)||this.grid.toggleToolPanelSection(Wn.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(Wn.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(Wn.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&&$n(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&&$n(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=di,e.BaseGridPlugin=Ct,e.ClipboardPlugin=class extends Ct{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.#mt(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#bt(e.target),!0)}#bt(e){const t=this.#vt();if(t&&0===t.ranges.length){const t=this.#yt(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()}#mt(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const i=kt(t,this.config),n=this.#vt(),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.#Ct(g)}#Ct(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??Tt)(e,this.grid)}#vt(){const e=this.grid?.query("getSelection");return e?.[0]}#xt(e){const t=this.#vt();let i,n;if(e?.columns)i=St(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=St(this.visibleColumns.slice(n,r+1))}else i=St(this.columns);if(e?.rowIndices)n=_t(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}}#Rt(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):At(t)});l.push(t.join(n))}return l.join(r)}#yt(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.#xt(e);return 0===t.length||0===i.length?"":this.#Rt(t,i,e)}async copy(e){const{columns:t,rows:i}=this.#xt(e);if(0===t.length||0===i.length)return"";const n=this.#Rt(t,i,e);return await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){u("TBW100",`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?kt(e,this.config):null}getLastCopied(){return this.lastCopied}},e.ColumnVirtualizationPlugin=class extends Ct{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=Lt(t),this.columnOffsets=It(t),this.totalWidth=Pt(t),this.endCol=t.length-1}detach(){this.#Et(),this.columnWidths=[],this.columnOffsets=[],this.originalColumns=[],this.isVirtualized=!1,this.startCol=0,this.endCol=0,this.scrollLeft=0,this.totalWidth=0}#Et(){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=Lt(e),this.columnOffsets=It(e),this.totalWidth=Pt(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=Ht(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,i=this.gridElement;i&&(i.scrollLeft=t)}getColumnOffset(e){return this.columnOffsets[e]??0}getTotalWidth(){return this.totalWidth}},e.ContextMenuPlugin=Bt,e.DEFAULT_ANIMATION_CONFIG=n,e.DEFAULT_GRID_ICONS=o,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",DATA_CHANGE:"data-change"},e.DataGridElement=yt,e.EditingPlugin=class extends Ct{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>!0===e||"function"==typeof e},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'},{property:"nullable",level:"column",description:'the "nullable" column property (allows null values)'}],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#St(){return"grid"===this.config.mode}#_t(e,t){const i=this.#pt.effectiveConfig?.rowEditable;if(i&&!i(t))return!1;const{editable:n}=e;return"function"==typeof n?n(t):!0===n}#At(e){return!0===e.editable||"function"==typeof e.editable}#kt=-1;#Tt;#Mt;#Lt=-1;#It=new Map;#Pt=new Set;#Ht=new Map;#Dt=!1;#zt=-1;#Ft;#Ot=!1;#qt=!1;#Nt=!1;#Gt=null;#$t=new ei;#Wt;get#pt(){return this.grid}attach(e){super.attach(e);const t=this.disconnectSignal,i=this.#pt;if(this.#Ft=new Yt((e,t,i)=>{this.#Bt(e,t,i)}),this.#Wt={grid:i,isGridMode:this.#St,config:this.config,editingCells:this.#Pt,editorValueCallbacks:this.#Ht,isEditSessionActive:()=>-1!==this.#kt,commitCellValue:(e,t,i,n)=>this.#Vt(e,t,i,n),exitRowEdit:(e,t)=>this.#Kt(e,t)},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}),Object.defineProperty(e,"_changedRowIdSet",{get:()=>this.#$t.changedRowIds,configurable:!0}),e.resetChangedRows=e=>this.resetChangedRows(e),e.beginBulkEdit=(e,t)=>{t&&this.beginCellEdit(e,t)},document.addEventListener("keydown",e=>{if(!this.#St&&"Escape"===e.key&&-1!==this.#kt){if(ri(this.config,e))return;this.#Kt(this.#kt,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",e=>{if(this.#St)return;if(-1===this.#kt)return;const t=i.findRenderedRowElement?.(this.#kt);if(!t)return;if((e.composedPath&&e.composedPath()||[]).includes(t))return;const n=e.target;n&&!this.gridElement.contains(n)&&this.grid.containsFocus?.(n)||ri(this.config,e)||queueMicrotask(()=>{-1!==this.#kt&&this.#Kt(this.#kt,!1)})},{signal:t}),this.config.focusTrap&&this.gridElement.addEventListener("focusout",e=>{if(this.#St)return;if(-1===this.#kt)return;const t=e.relatedTarget;t&&this.grid.containsFocus?.(t)||t&&this.gridElement.contains(t)||queueMicrotask(()=>{-1!==this.#kt&&this.#Ut()})},{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.#Ht.get(i);n&&n(t.newValue)},{signal:t}),this.config.dirtyTracking){const e=e=>{const t=e.detail,i=t?.action;if(!i)return;const n=this.rows[i.rowIndex];if(!n)return;const r=this.grid.getRowId(n);if(!r)return;const o=this.#$t.isRowDirty(r,n);this.emit("dirty-change",{rowId:r,row:n,original:this.#$t.getOriginalRow(r),type:o?"modified":"pristine"})};this.gridElement.addEventListener("undo",e,{signal:t}),this.gridElement.addEventListener("redo",e,{signal:t}),this.on("row-inserted",e=>{const t=this.grid.getRowId(e.row);null!=t&&this.markAsNew(String(t))})}this.#St&&(i._isGridEditMode=!0,this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",e=>{const t=e.target;if(t!==this.gridElement&&t.matches(ti)){if(this.#qt)return t.blur(),void this.gridElement.focus();const e=i._focusRow,n=i._focusCol,r=this.#Gt;if(!r||r.rowIndex!==e||r.colIndex!==n){const t=i._visibleColumns?.[n],r=i._rows?.[e];if(t?.field&&r){const i=t.field;this.#Gt={rowIndex:e,colIndex:n,field:i,value:r[i]}}}this.#Ot=!0}},{signal:t}),this.gridElement.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.gridElement.contains(t)||this.grid.containsFocus?.(t))&&t.matches(ti)||(this.#Ot=!1,this.#Gt=null)},{signal:t}),this.gridElement.addEventListener("keydown",e=>{if("Escape"===e.key&&this.#Ot){if(ri(this.config,e))return void queueMicrotask(()=>{if(this.#Ot){this.#jt();const e=document.activeElement;e&&this.gridElement.contains(e)&&(e.blur(),this.gridElement.focus()),this.#Ot=!1,this.#qt=!0}});this.#jt();const t=document.activeElement;t&&this.gridElement.contains(t)&&(t.blur(),this.gridElement.focus()),this.#Ot=!1,this.#qt=!0,e.preventDefault(),e.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",e=>{e.target.matches(ti)&&(this.#qt=!1)},{signal:t}))}detach(){this.#pt._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#kt=-1,this.#Tt=void 0,this.#Mt=void 0,this.#Lt=-1,this.#It.clear(),this.#$t.clear(),this.#Pt.clear(),this.#Ht.clear(),this.#Ot=!1,this.#qt=!1,this.#Gt=null,this.#Nt=!1,super.detach()}handleQuery(e){if("isEditing"===e.type)return this.#St||-1!==this.#kt}onCellClick(e){if(this.#St)return!1;const t=this.#pt,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=>this.#At(e));if(!o)return!1;const s=t._rows[r],l=t.effectiveConfig?.rowEditable;return!(s&&l&&!l(s))&&(e.originalEvent.stopPropagation(),this.beginBulkEdit(r),!0)}onKeyDown(e){const t=this.#pt;if("Escape"===e.key){if(this.#St&&this.#Ot){this.#jt();const e=document.activeElement;return e&&this.gridElement.contains(e)&&(e.blur(),this.gridElement.focus()),this.#Ot=!1,this.#qt=!0,this.requestAfterRender(),!0}if(-1!==this.#kt&&!this.#St)return ri(this.config,e)||this.#Kt(this.#kt,!0),!0}if(this.#St&&!this.#Ot&&("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key))return!1;if(this.#St&&this.#Ot&&("ArrowUp"===e.key||"ArrowDown"===e.key))return!0;if(("ArrowUp"===e.key||"ArrowDown"===e.key)&&-1!==this.#kt&&!this.#St){if(ri(this.config,e))return!0;const i=t._rows.length-1,n=this.#kt;return this.#Kt(n,!1),"ArrowDown"===e.key?t._focusRow=Math.min(i,t._focusRow+1):t._focusRow=Math.max(0,t._focusRow-1),e.preventDefault(),fe(t),this.requestAfterRender(),!0}if("Tab"===e.key&&(-1!==this.#kt||this.#St)){if(e.preventDefault(),this.#Nt)return this.#Kt(this.#kt,!1),!0;const t=!e.shiftKey;return this.#Yt(t),!0}if(" "===e.key||"Spacebar"===e.key){if(-1!==this.#kt)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&&o&&this.#_t(r,o)&&"boolean"===r.type){const t=r.field;if(ii(t)){const n=!o[t];return this.#Vt(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.#St&&!this.#Ot)return this.#Ut(),!0;if(-1!==this.#kt)return!!ri(this.config,e);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=>this.#At(e)),o=t._rows[n],s=t.effectiveConfig?.rowEditable,l=o&&s&&!s(o);if(i&&!l){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.#kt||this.#St)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],o=t._rows[i];if(r&&o&&this.#_t(r,o)&&r.field)return e.preventDefault(),this.beginCellEdit(i,r.field),!0}return!1}return!1}processColumns(e){const t=this.#pt,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}processRows(e){const t=this.#pt;if(this.config.dirtyTracking&&t.getRowId&&this.#$t.capture(e,e=>{try{return t.getRowId?.(e)}catch{return}}),-1===this.#kt||this.#St)return e;const i=this.#Tt,n=this.#Mt;if(!i||!n)return e;const r=[...e];let o=-1;for(let s=0;s<r.length;s++)try{if(t.getRowId?.(r[s])===i){o=s;break}}catch{}return-1===o?(setTimeout(()=>this.cancelActiveRowEdit(),0),r):(r[o]=n,this.#kt!==o&&this.#Xt(this.#kt,o),r)}afterRender(){const e=this.#pt;if(-1!==this.#kt&&this.#Mt&&!this.#St&&e._rows[this.#kt]!==this.#Mt){const t=e._rows.indexOf(this.#Mt);if(-1===t)return void setTimeout(()=>this.cancelActiveRowEdit(),0);this.#Xt(this.#kt,t)}if(this.#Dt&&(this.#Dt=!1,this.#Zt(e)),-1!==this.#zt){const t=this.#zt;this.#zt=-1,e.animateRow?.(t,"change")}const t=this.#$t.drainCapturedFlag();if(null!=t&&this.emit("baselines-captured",{count:t}),!this.#St&&0!==this.#Pt.size)for(const i of this.#Pt){const[t,n]=i.split(":"),r=parseInt(t,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.#Qt(a,r,d,o,l,!0)}}afterCellRender(e){const{row:t,rowIndex:i,column:n,colIndex:r,cellElement:o}=e,s=this.#_t(n,t);if(s)o.removeAttribute("aria-readonly");else if(o.setAttribute("aria-readonly","true"),this.#St&&o.classList.contains("editing")){o.classList.remove("editing");const e=t[n.field];o.textContent=null==e?"":String(e)}this.#St&&s&&(o.classList.contains("editing")||this.#Qt(t,i,n,r,o,!0,e.rowElement))}afterRowRender(e){if(!this.config.dirtyTracking)return;const t=this.#pt,i=t.getRowId?.(e.row);if(!i)return;const{isNew:n,isCommittedDirty:r,hasBaseline:o}=this.#$t.getRowDirtyState(i,e.row),s=e.rowElement;if(s.classList.toggle("tbw-row-dirty",r),s.classList.toggle("tbw-row-new",n),o){const t=s.querySelectorAll(".cell[data-field]");for(let n=0;n<t.length;n++){const r=t[n],o=r.getAttribute("data-field");o&&r.classList.toggle("tbw-cell-dirty",this.#$t.isCellDirty(i,e.row,o))}}else{const e=s.querySelectorAll(".tbw-cell-dirty");for(let t=0;t<e.length;t++)e[t].classList.remove("tbw-cell-dirty")}}onScrollRender(){this.afterRender()}get changedRows(){return this.#$t.getChangedRows(e=>this.grid.getRow(e))}get changedRowIds(){return this.#$t.getChangedRowIds()}get activeEditRow(){return this.#kt}get activeEditCol(){return this.#Lt}isRowEditing(e){return this.#kt===e}isCellEditing(e,t){return this.#Pt.has(`${e}:${t}`)}isRowChanged(e){const t=this.#pt,i=t._rows[e];if(!i)return!1;try{const e=t.getRowId?.(i);return!!e&&this.#$t.isRowChanged(e)}catch{return!1}}isRowChangedById(e){return this.#$t.isRowChanged(e)}isDirty(e){if(!this.config.dirtyTracking)return!1;if(this.#$t.newRowIds.has(e))return!0;const t=this.grid.getRow(e);return!!t&&this.#$t.isRowDirty(e,t)}isPristine(e){return!this.isDirty(e)}get dirty(){if(!this.config.dirtyTracking)return!1;const e=this.#pt;return this.#$t.hasAnyDirty(t=>e._getRowEntry(t)?.row)}get pristine(){return!this.dirty}markAsPristine(e){if(!this.config.dirtyTracking)return;const t=this.grid.getRow(e);t&&(this.#$t.markPristine(e,t),this.emit("dirty-change",{rowId:e,row:t,original:t,type:"pristine"}))}markAsNew(e){if(!this.config.dirtyTracking)return;this.#$t.markNew(e);const t=this.grid.getRow(e);this.emit("dirty-change",{rowId:e,row:t,original:void 0,type:"new"})}markAsDirty(e){if(!this.config.dirtyTracking)return;const t=this.grid.getRow(e);t&&(this.#$t.markDirty(e),this.emit("dirty-change",{rowId:e,row:t,original:this.#$t.getOriginalRow(e),type:"modified"}))}markAllPristine(){if(!this.config.dirtyTracking)return;const e=this.#pt;this.#$t.markAllPristine(t=>e._getRowEntry(t)?.row)}getOriginalRow(e){if(this.config.dirtyTracking)return this.#$t.getOriginalRow(e)}hasBaseline(e){return!!this.config.dirtyTracking&&this.#$t.hasBaseline(e)}getDirtyRows(){if(!this.config.dirtyTracking)return[];const e=this.#pt;return this.#$t.getDirtyRows(t=>e._getRowEntry(t)?.row)}get dirtyRowIds(){if(!this.config.dirtyTracking)return[];const e=this.#pt;return this.#$t.getDirtyRowIds(t=>e._getRowEntry(t)?.row)}revertRow(e){if(!this.config.dirtyTracking)return;const t=this.grid.getRow(e);t&&this.#$t.revertRow(e,t)&&(this.emit("dirty-change",{rowId:e,row:t,original:this.#$t.getOriginalRow(e),type:"reverted"}),this.requestRender())}revertAll(){if(!this.config.dirtyTracking)return;const e=this.#pt;this.#$t.revertAll(t=>e._getRowEntry(t)?.row),this.requestRender()}setInvalid(e,t,i=""){this.#Ft.setInvalid(e,t,i)}clearInvalid(e,t){this.#Ft.clearInvalid(e,t)}clearRowInvalid(e){this.#Ft.clearRowInvalid(e)}clearAllInvalid(){this.#Ft.clearAllInvalid()}isCellInvalid(e,t){return this.#Ft.isCellInvalid(e,t)}getInvalidMessage(e,t){return this.#Ft.getInvalidMessage(e,t)}hasInvalidCells(e){return this.#Ft.hasInvalidCells(e)}getInvalidFields(e){return this.#Ft.getInvalidFields(e)}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#$t.changedRowIds.clear(),this.#$t.committedDirtyRowIds.clear(),this.#Jt(),e||this.emit("changed-rows-reset",{rows:t,ids:i});const n=this.#pt;n._rowPool?.forEach(e=>e.classList.remove("changed"))}beginCellEdit(e,t){const i=this.#pt,n=i._visibleColumns.findIndex(e=>e.field===t);if(-1===n)return;const r=i._visibleColumns[n],o=i._rows[e];if(!r||!o||!this.#_t(r,o))return;const s=i.findRenderedRowElement?.(e),l=s?.querySelector(`.cell[data-col="${n}"]`);l&&(this.#Nt=!0,this.#ei(e,n,l))}beginBulkEdit(e){const t=this.#pt;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return;const i=t._columns?.some(e=>this.#At(e));if(!i)return;const n=t.findRenderedRowElement?.(e);if(!n)return;const r=t._rows[e],o=t.effectiveConfig?.rowEditable;r&&o&&!o(r)||(this.#Nt=!1,this.#ti(e,r),Array.from(n.children).forEach((i,n)=>{const o=t._visibleColumns[n];if(o&&this.#_t(o,r)){const t=i;t.classList.contains("editing")||this.#Qt(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(ti);try{t?.focus({preventScroll:!0})}catch{}}},0))}commitActiveRowEdit(){-1!==this.#kt&&this.#Kt(this.#kt,!1)}cancelActiveRowEdit(){-1!==this.#kt&&this.#Kt(this.#kt,!0)}#Bt(e,t,i){const n=this.#pt,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.#Ft.getInvalidMessage(e,t);i&&a.setAttribute("title",i)}else a.removeAttribute("data-invalid"),a.removeAttribute("title")}#Xt(e,t){this.#kt=t;const i=new Set,n=`${e}:`;for(const s of this.#Pt)s.startsWith(n)?i.add(`${t}:${s.substring(n.length)}`):i.add(s);this.#Pt.clear();for(const s of i)this.#Pt.add(s);const r=this.#It.get(e);void 0!==r&&(this.#It.delete(e),this.#It.set(t,r));const o=[];for(const[s,l]of this.#Ht)s.startsWith(n)&&(o.push([`${t}:${s.substring(n.length)}`,l]),this.#Ht.delete(s));for(const[s,l]of o)this.#Ht.set(s,l);this.#Jt()}#ei(e,t,i){const n=this.#pt,r=n._rows[e],o=n._visibleColumns[t];r&&o&&this.#_t(o,r)&&(i.classList.contains("editing")||(this.#kt!==e&&this.#ti(e,r),this.#Lt=t,this.#Qt(r,e,o,t,i,!1)))}#jt(){const e=this.#Gt;if(!e)return;const t=this.#pt,i=t._rows?.[e.rowIndex];i&&(i[e.field]=e.value);const n=`${e.rowIndex}:${e.field}`,r=this.#Ht.get(n);if(r&&r(e.value),this.emit("cell-cancel",{rowIndex:e.rowIndex,colIndex:e.colIndex,field:e.field,previousValue:e.value}),i){let e;try{e=this.grid.getRowId(i)}catch{}e&&(this.config.dirtyTracking?this.#$t.isRowDirty(e,i)||(this.#$t.changedRowIds.delete(e),this.emit("dirty-change",{rowId:e,row:i,original:this.#$t.getOriginalRow(e),type:"reverted"})):this.#$t.changedRowIds.delete(e))}this.requestRender(),this.#Gt=null}#Ut(){const e=this.#pt,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(ti);e&&(this.#qt=!1,e.focus(),this.#Ot=!0,e instanceof HTMLInputElement&&("text"===e.type||"number"===e.type)&&e.select())}}#Yt(e){const t=this.#pt,i=t._rows,n=this.#St?t._focusRow:this.#kt,r=i[n],o=t._visibleColumns.map((e,t)=>r&&this.#_t(e,r)?t:-1).filter(e=>e>=0);if(0===o.length)return;const s=o.indexOf(t._focusCol)+(e?1:-1);if(s>=0&&s<o.length){t._focusCol=o[s];const e=t.findRenderedRowElement?.(n),i=e?.querySelector(`.cell[data-col="${o[s]}"]`);if(i?.classList.contains("editing")){const e=i.querySelector(ti);e?.focus({preventScroll:!0})}return void fe(t,{forceHorizontalScroll:!0})}const l=n+(e?1:-1);if(l>=0&&l<i.length){const r=i[l],o=t._visibleColumns.map((e,t)=>r&&this.#_t(e,r)?t:-1).filter(e=>e>=0);if(0===o.length)return;this.#St?(t._focusRow=l,t._focusCol=e?o[0]:o[o.length-1],fe(t,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const e=t.findRenderedRowElement?.(l),i=e?.querySelector(`.cell[data-col="${t._focusCol}"]`);if(i?.classList.contains("editing")){const e=i.querySelector(ti);e?.focus({preventScroll:!0})}},0)):(this.#Kt(n,!1),t._focusRow=l,t._focusCol=e?o[0]:o[o.length-1],this.beginBulkEdit(l),fe(t,{forceHorizontalScroll:!0}))}}#Jt(){const e=this.#pt;e._activeEditRows=this.#kt,e._rowEditSnapshots=this.#It}#ti(e,t){if(this.#kt!==e){-1!==this.#kt&&this.#Kt(this.#kt,!1),this.#It.set(e,{...t}),this.#kt=e,this.#Mt=t;const i=this.#pt;try{this.#Tt=i.getRowId?.(t)??void 0}catch{this.#Tt=void 0}this.#Jt(),this.#St||this.emit("edit-open",{rowIndex:e,rowId:this.#Tt??"",row:t})}}#Kt(e,t){if(this.#kt!==e)return;const i=this.#pt,n=this.#It.get(e),r=i.findRenderedRowElement?.(e);let o=this.#Tt;const s=o?i._getRowEntry(o):void 0,l=s?.row??this.#Mt??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=jt(o,r,i);i!==n&&this.#Vt(e,r,n,l)}})}if(t||this.#St||!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.#$t.changedRowIds.delete(o),this.#$t.committedDirtyRowIds.delete(o),this.clearRowInvalid(o));else if(!t&&l){const t=function(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}(n,l),i=o?this.#$t.changedRowIds.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.#$t.changedRowIds.delete(o),this.#$t.committedDirtyRowIds.delete(o),this.clearRowInvalid(o))):r||(o&&this.config.dirtyTracking&&(this.#$t.isRowDirty(o,l)?this.#$t.committedDirtyRowIds.add(o):this.#$t.committedDirtyRowIds.delete(o)),t&&this.isAnimationEnabled&&(this.#zt=e))}this.#It.delete(e),this.#kt=-1,this.#Tt=void 0,this.#Mt=void 0,this.#Lt=-1,this.#Nt=!1,this.#Jt();for(const a of this.#Pt)a.startsWith(`${e}:`)&&this.#Pt.delete(a);for(const a of this.#Ht.keys())a.startsWith(`${e}:`)&&this.#Ht.delete(a);this.#Dt=!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.#Zt(i),this.#Dt=!1),!this.#St&&l&&this.emit("edit-close",{rowIndex:e,rowId:o??"",row:l,reverted:t})}#Vt(e,t,i,n){const r=t.field;if(!ii(r))return;const o=n[r];if(o===i)return;const s=this.#pt;let l;try{l=this.grid.getRowId(n)}catch{}const a=!l||!this.#$t.changedRowIds.has(l),d=l?e=>this.grid.updateRow(l,e,"cascade"):ni;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;if(l&&!c&&this.isCellInvalid(l,r)&&this.clearInvalid(l,r),n[r]=i,l&&this.#$t.changedRowIds.add(l),this.#Jt(),this.config.dirtyTracking&&l){const e=this.#$t.isRowDirty(l,n);this.emit("dirty-change",{rowId:l,row:n,original:this.#$t.getOriginalRow(l),type:e?"modified":"pristine"})}this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:r,oldValue:o,newValue:i});const u=s.findRenderedRowElement?.(e);u&&u.classList.add("changed")}#Qt(e,t,i,n,r,o,s){oi(this.#Wt,e,t,i,n,r,o,s)}#Zt(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 Ct{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=St(this.columns,t?.columns,i.onlyVisible);let o;if(t?.rowIndices)o=_t(this.rows,t.rowIndices);else if(i.onlySelected){const e=this.getSelectionState();o=e?.selected?.size?_t(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 si(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)),si(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){li(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">${ai(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=ai(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`;li(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`;li(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=Ci,e.FitModeEnum=i,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=xt,e.GridDataAttrs=Rt,e.GridElement=yt,e.GridSelectors=Et,e.GroupingColumnsPlugin=class extends Ct{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;#ii=new Set;#ni=[];#ri=new Map;attach(e){super.attach(e),this.gridElement.addEventListener("column-move",this.#oi,{signal:this.disconnectSignal})}detach(){this.groups=[],this.isActive=!1,this.#ii.clear(),this.#ni=[],this.#ri.clear()}#oi=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.#si(r,n))return t.preventDefault(),void this.#li(i);this.#ai(n)};#ai(e){this.#ii.clear();const t=this.#di(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.#ii.add(n);break}}}#di(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}#si(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}#li(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.#ci()}#ci(){let e;if(this.#ni.length>0)e=this.#ni.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 t=this.grid?.getColumnOrder();if(t&&t.length>0){const i=new Map(t.map((e,t)=>[e,t]));for(const t of e)t.fields.sort((e,t)=>(i.get(e)??1/0)-(i.get(t)??1/0))}return e}static detect(e,t){const i=t?.features?.groupingColumns;if(i&&"object"==typeof i&&Array.isArray(i.columnGroups)&&i.columnGroups.length>0)return!0;if(t?.columnGroups&&Array.isArray(t.columnGroups)&&t.columnGroups.length>0)return!0;const n=t?.columns;return!!Array.isArray(n)&&function(e){return e.some(e=>null!=e.group)}(n)}processColumns(e){const t=this.config?.columnGroups,i=this.grid?.gridConfig?.columnGroups;let n,r;if(t&&Array.isArray(t)&&t.length>0?(i&&Array.isArray(i)&&i.length>0&&this.warn("TBW114","columnGroups defined in both gridConfig and groupingColumns feature config. Using feature config (higher precedence)."),n=t):i&&Array.isArray(i)&&i.length>0&&(n=i),n&&n.length>0){const t=Ri(n);this.#ni=t,this.#ri.clear();for(const e of t)e.renderer&&this.#ri.set(e.id,e.renderer);const i=new Map;for(const e of t)for(const t of e.children)i.set(t,{id:e.id,label:e.header});r=e.map(e=>{const t=i.get(e.field);return t&&!e.group?{...e,group:t}:e})}else this.#ni=[],this.#ri.clear(),r=[...e];const o=Ei(r);if(0===o.length)return this.isActive=!1,this.groups=[],r;if(this.#ri.size>0)for(const s of o){const e=this.#ri.get(s.id);e&&(s.renderer=e)}this.isActive=!0,this.groups=o,this.#ii.clear();for(const s of o){const e=s.columns[s.columns.length-1];e?.field&&this.#ii.add(e.field)}return r}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=Ei(i);if(0===n.length)return;if(this.#ri.size>0)for(const l of n){const e=this.#ri.get(l.id);e&&(l.renderer=e)}this.#ii.clear();const r=_i(n,i);for(let l=0;l<n.length;l++){const e=n[l];if(String(e.id).startsWith("__implicit__")&&r.has(String(e.id)))continue;const t=e.columns[e.columns.length-1];t?.field&&l<n.length-1&&this.#ii.add(t.field)}const o=function(e,t,i){if(0===e.length)return null;const n=document.createElement("div");n.className="header-group-row",n.setAttribute("role","row");const r=_i(e,t);for(const o of e){const e=String(o.id),s=e.startsWith("__implicit__");if(s&&r.has(e))continue;const l=Si(o,t);if(!l)continue;const[a,d]=l,c=d-a+1,h=s?"":o.label||o.id,u=document.createElement("div");u.className="cell header-group-cell",s&&u.classList.add("implicit-group"),u.setAttribute("data-group",e),u.style.gridColumn=`${a+1} / span ${c}`;const g=!s&&(o.renderer||i)||void 0;if(g&&!s){const t=g({id:e,label:String(h),columns:o.columns,firstIndex:a,isImplicit:!1});t instanceof HTMLElement?u.appendChild(t):"string"==typeof t?u.innerHTML=t:u.textContent=h}else u.textContent=h;n.appendChild(u)}return n}(n,i,this.config.groupHeaderRenderer);if(o){o.classList.toggle("no-borders",!this.config.showGroupBorders);const t=e.querySelector(".header-row");t?e.insertBefore(o,t):e.appendChild(o)}const s=e.querySelector(".header-row");s&&(s.classList.toggle("no-group-borders",!this.config.showGroupBorders),function(e,t,i){if(!t.length||!e)return;const n=_i(t,i),r=new Map;for(const s of t)if(!String(s.id).startsWith("__implicit__")||!n.has(String(s.id)))for(const e of s.columns)e.field&&r.set(e.field,s.id);const o=Array.from(e.querySelectorAll(".cell[data-field]"));o.forEach(e=>{const t=e.getAttribute("data-field")||"",i=r.get(t);i&&(e.classList.add("grouped"),e.getAttribute("data-group")||e.setAttribute("data-group",i))});for(const s of t){if(String(s.id).startsWith("__implicit__")&&n.has(String(s.id)))continue;const e=s.columns[s.columns.length-1],t=o.find(t=>t.getAttribute("data-field")===e.field);t&&t.classList.add("group-end")}}(s,n,i))}afterCellRender(e){this.isActive&&this.config.showGroupBorders&&e.cellElement.classList.toggle("group-end",this.#ii.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 Ct{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=Pi({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=Pi({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=Ii(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"),fi(o))return a.setAttribute("data-field",o.field),void t.appendChild(a);if(d){const e=r[o.field];if(e){const t=Ii(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=Ii(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=zi,e.MultiSortPlugin=class extends Ct{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;get#pt(){return this.grid}clearCoreSortState(){this.#pt._sortState=null}detach(){this.sortModel=[],this.cachedSortResult=null}processRows(e){if(0===this.sortModel.length)return this.cachedSortResult=null,[...e];const t=this.#pt;if(!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??Fi)(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 i=this.columns.find(t=>t.field===e.field);if(!i?.sortable)return!1;const n=e.originalEvent.shiftKey,r=this.config.maxSortColumns??3;if(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,n,r),this.clearCoreSortState(),this.emit("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),this.grid?.requestStateChange?.(),this.sortModel.length>0){const e=this.sortModel.map(e=>{const t=this.columns.find(t=>t.field===e.field);return`${t?.header??e.field} ${"asc"===e.direction?"ascending":"descending"}`});t(this.gridElement,`Sorted by ${e.join(", then ")}`)}else t(this.gridElement,"Sort cleared");return!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=qi(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){if(this.sortModel=[...e],this.clearCoreSortState(),this.emit("sort-change",{sortModel:[...e]}),this.requestRender(),this.grid?.requestStateChange?.(),e.length>0){const i=e.map(e=>{const t=this.columns.find(t=>t.field===e.field);return`${t?.header??e.field} ${"asc"===e.direction?"ascending":"descending"}`});t(this.gridElement,`Sorted by ${i.join(", then ")}`)}}clearSort(){this.sortModel=[],this.clearCoreSortState(),this.emit("sort-change",{sortModel:[]}),this.requestRender(),this.grid?.requestStateChange?.(),t(this.gridElement,"Sort cleared")}getSortIndex(e){return Oi(this.sortModel,e)}getSortDirection(e){return qi(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 Ct{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:Ui,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;#hi=[];detach(){this.leftOffsets.clear(),this.rightOffsets.clear(),this.isApplied=!1,this.#hi=[]}static detect(e,t){const i=t?.columns;return!!Array.isArray(i)&&Bi(i)}processColumns(e){const t=[...e];if(this.isApplied=Bi(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=Ni(o);e?"left"===Gi(e,t)?i.push(o):r.push(o):n.push(o)}return[...i,...n,...r]}(t,i?ee(i):"ltr")}afterRender(){if(!this.isApplied)return;const e=this.gridElement,t=[...this.columns];if(!Bi(t))return Ki(e),void(this.isApplied=!1);queueMicrotask(()=>{Vi(e,t)})}handleQuery(e){switch(e.type){case Ui:return null==Ni(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!=Ni(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.gridElement;if(t){0===this.#hi.length&&(this.#hi=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.#hi.indexOf(e);if(s>=0){let e=o.length;for(let t=0;t<o.length;t++){if(Ni(o[t]))continue;if(this.#hi.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!=Ni(e))||(this.#hi=[]),r.columns=o}}refreshStickyOffsets(){const e=[...this.columns];Vi(this.gridElement,e)}getLeftPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>$i(e,t))}([...this.columns],ee(this.gridElement))}getRightPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>Wi(e,t))}([...this.columns],ee(this.gridElement))}clearStickyPositions(){Ki(this.gridElement)}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.gridElement.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 Ct{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=tn(this.sourceRows,this.columns,this.gridElement,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=Yi("top");const i=e.querySelector(".header");i&&i.nextSibling?t.insertBefore(this.topAggregationContainer,i.nextSibling):t.appendChild(this.topAggregationContainer)}Xi(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=ji(this.config,r);this.infoBarElement.replaceWith(e),this.infoBarElement=e}else this.infoBarElement=ji(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=Yi("bottom")),this.footerWrapper.appendChild(this.bottomAggregationContainer),Xi(this.bottomAggregationContainer,l,this.visibleColumns,this.sourceRows,this.config.fullWidth)),d&&(this.infoBarElement=ji(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 tn(this.rows,this.columns,this.gridElement,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=wn,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=vt,e.PrintPlugin=class extends Ct{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}}}";#ui=!1;#gi=null;#pi=null;#fi=null;#wi=null;#mi=null;#bi=null;get#pt(){return this.grid}isPrinting(){return this.#ui}async print(e){if(this.#ui)return void this.warn("TBW090","Print already in progress");const t=this.gridElement;if(!t)return void this.warn("TBW091","Grid not available");const i={...vn,...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.#ui=!0;const s=performance.now();this.emit("print-start",{rowCount:r,limitApplied:o,originalRowCount:n});try{const e=this.#pt;this.#pi={bypassThreshold:e._virtualization?.bypassThreshold??24},this.#vi(),o&&(this.#fi=this.sourceRows,this.grid.rows=this.sourceRows.slice(0,r),await new Promise(e=>setTimeout(e,50))),(i.includeTitle||i.includeTimestamp)&&this.#yi(i),await this.#Ci(),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.#xi(i):await this.#Ri(),this.emit("print-complete",{success:!0,rowCount:r,duration:Math.round(performance.now()-s)})}catch(l){p("TBW092",`Print failed: ${l}`,this.gridElement?.id,this.name),this.emit("print-complete",{success:!1,rowCount:0,duration:Math.round(performance.now()-s)})}finally{this.#Ei(),this.#ui=!1}}#yi(e){const t=this.gridElement;if(t){if(this.#wi=document.createElement("div"),this.#wi.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.#wi.appendChild(i)}if(e.includeTimestamp){const e=document.createElement("div");e.className="tbw-print-header-timestamp",e.textContent=`Printed: ${(new Date).toLocaleString()}`,this.#wi.appendChild(e)}t.insertBefore(this.#wi,t.firstChild),this.#mi=document.createElement("div"),this.#mi.className="tbw-print-footer",this.#mi.textContent=`Page generated from ${window.location.hostname}`,t.appendChild(this.#mi)}}async#Ci(){const e=this.#pt;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#Ri(){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#xi(e){const t=this.gridElement;t&&await bn(t,{orientation:e.orientation})}#vi(){const e=this.columns;if(e){this.#gi=new Map;for(const t of e)t.printHidden&&t.field&&(this.#gi.set(t.field,!t.hidden),this.grid.setColumnVisible(t.field,!1))}}#Si(){if(this.#gi){for(const[e,t]of this.#gi)this.grid.setColumnVisible(e,t);this.#gi=null}}#Ei(){const e=this.gridElement;if(!e)return;this.#Si(),e.classList.remove("print-portrait","print-landscape"),null!==this.#bi&&(e.style.transform="",e.style.transformOrigin="",e.style.width="",this.#bi=null),this.#wi&&(this.#wi.remove(),this.#wi=null),this.#mi&&(this.#mi.remove(),this.#mi=null);const t=this.#pt;this.#pi&&t._virtualization&&(t._virtualization.bypassThreshold=this.#pi.bypassThreshold,t.refreshVirtualWindow(!0),this.#pi=null),null!==this.#fi&&(this.grid.rows=this.#fi,this.#fi=null)}afterRender(){this.config?.button&&!this.#_i&&(this.#Ai(),this.#_i=!0)}#_i=!1;#Ai(){const e=this.#pt;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=Cn,e.RenderPhase=K,e.ReorderPlugin=class extends Ct{name="reorderColumns";aliases=["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;get#pt(){return this.grid}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),this.gridElement.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=yn(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.#pt,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,fe(this.#pt),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=yn(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;t.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),"function"==typeof this.grid.forceLayout?this.grid.forceLayout().then(()=>{this.animateFLIP(t)}):requestAnimationFrame(()=>{this.animateFLIP(t)})}else"fade"===t?this.animateFade(()=>this.grid.setColumnOrder(e)):this.grid.setColumnOrder(e);this.grid.requestStateChange?.()}},e.ResponsivePlugin=class extends Ct{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] .data-grid-row>.cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .data-grid-row>.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"}]};#X;#ki=!1;#Ti;#Mi=!1;#Li=0;#Ii=new Set;#Pi=new Set;#Hi=null;#Di=[];get#pt(){return this.grid}isResponsive(){return this.#ki}setResponsive(e){e!==this.#ki&&(this.#ki=e,this.#zi(),this.emit("responsive-change",{isResponsive:e,width:this.#Li,breakpoint:this.config.breakpoint??0}),this.requestRender())}setBreakpoint(e){this.config.breakpoint=e,this.#Fi(this.#Li)}setCardRenderer(e){this.config.cardRenderer=e,this.#ki&&this.requestRender()}getWidth(){return this.#Li}getActiveBreakpoint(){return this.#Hi}attach(e){super.attach(e),this.#Oi(),this.#qi(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#Di=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#X=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#Li=t,clearTimeout(this.#Ti),this.#Ti=setTimeout(()=>{this.#Fi(t)},this.config.debounceMs??100)}),this.#X.observe(this.gridElement)}#Oi(){const e=this.gridElement;if(!e)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const i=this.#pt.__frameworkAdapter;if(i?.parseResponsiveCardElement){const e=i.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?.parseResponsiveCardElement||(a.cardRenderer=e=>{const t=T(M(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})}#qi(e){if(this.#Ii.clear(),this.#Pi.clear(),e)for(const t of e)"string"==typeof t?this.#Ii.add(t):t.showValue?this.#Pi.add(t.field):this.#Ii.add(t.field)}detach(){this.#X?.disconnect(),this.#X=void 0,clearTimeout(this.#Ti),this.#Ti=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#ki}afterRender(){this.#Ni();if(!(this.#Di.length>0?null!==this.#Hi:this.#ki))return;const e=this.#Ii.size>0,t=this.#Pi.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.#Ii.has(e)?(n.setAttribute("data-responsive-hidden",""),n.removeAttribute("data-responsive-value-only")):this.#Pi.has(e)?(n.setAttribute("data-responsive-value-only",""),n.removeAttribute("data-responsive-hidden")):(n.removeAttribute("data-responsive-hidden"),n.removeAttribute("data-responsive-value-only")))}}#Fi(e){if(this.#Di.length>0)return void this.#Gi(e);const t=this.config.breakpoint??0;0!==t||this.#Mi||(this.#Mi=!0,this.warn("TBW110","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.#ki&&(this.#ki=i,this.#zi(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#Gi(e){let t=null;for(const i of this.#Di)e<=i.maxWidth&&(t=i);if(t!==this.#Hi){this.#Hi=t,t?.hiddenColumns?this.#qi(t.hiddenColumns):this.#qi(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#ki&&(this.#ki=i,this.#zi()),this.emit("responsive-change",{isResponsive:this.#ki,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#$i;#zi(){this.gridElement.toggleAttribute("data-responsive",this.#ki);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.#pt;if(this.#ki){t._virtualization&&(this.#$i=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.#$i&&this.#$i>0&&t._virtualization&&(t._virtualization.rowHeight=this.#$i,this.#$i=void 0),this.#Wi=void 0,this.#Bi=void 0,this.#Vi=void 0}}renderRow(e,t,i){if(!this.#ki||!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;return t.style.height="auto"===r||void 0===r?"auto":`${this.#Ki()}px`,t.appendChild(n),!0}onKeyDown(e){if(!this.#ki)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(),fe(this.#pt),!0;if(this.grid._focusRow<t)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),fe(this.#pt),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),fe(this.#pt),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=i,e.preventDefault(),fe(this.#pt),!0;break;case"ArrowRight":if(this.grid._focusRow<t)return this.grid._focusRow+=1,e.preventDefault(),fe(this.#pt),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),fe(this.#pt),!0}return!1}#Wi;#Bi;#Vi;#Ki(){if(this.#Wi&&this.#Wi>0)return this.#Wi;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#Ui(){return this.#Bi&&this.#Bi>0?this.#Bi:this.#$i??28}#ji(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}#Yi(){let e=0,t=0;for(const i of this.rows)i.__isGroupRow?e++:t++;return{groupCount:e,cardCount:t}}getExtraHeight(){if(!this.#ki||!this.config.cardRenderer)return 0;if(!this.#ji())return 0;const e=this.#$i??28,t=this.#Ui(),i=this.#Ki(),{groupCount:n,cardCount:r}=this.#Yi();return n*Math.max(0,t-e)+r*Math.max(0,i-e)}getExtraHeightBefore(e){if(!this.#ki||!this.config.cardRenderer)return 0;if(!this.#ji())return 0;const t=this.#$i??28,i=this.#Ui(),n=this.#Ki(),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.#ki&&this.config.cardRenderer)return e.__isGroupRow?this.#Ui():this.#Ki()}#Xi(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#Zi=!1;#Ni(){if(!this.#ki||!this.config.cardRenderer)return;let e=!1;const t=this.#pt,i=this.#ji(),n=this.#Xi();if(n!==this.#Vi&&(this.#Vi=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.#Bi&&(this.#Bi=i,e=!0)}}const r=this.gridElement.querySelector(".data-grid-row.responsive-card");if(r){const n=r.getBoundingClientRect().height;n>0&&n!==this.#Wi&&(this.#Wi=n,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=n))}e&&!this.#Zi&&(this.#Zi=!0,queueMicrotask(()=>{this.#Zi=!1,this.grid&&this.#ki&&this.#pt.refreshVirtualWindow?.(!0,!0)}))}},e.RowReorderPlugin=class extends Ct{name="reorderRows";aliases=["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;get#pt(){return this.grid}attach(e){super.attach(e),this.setupDelegatedDragListeners()}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:Cn,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(){}onKeyDown(e){if(!this.config.enableKeyboard)return;if(!e.ctrlKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key)return;const t=this.#pt,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)}setupDelegatedDragListeners(){const e=this.gridElement;if(!e)return;const t=this.disconnectSignal;e.addEventListener("dragstart",e=>{const t=e,i=t.target.closest(".dg-row-drag-handle");if(!i)return;const n=i.closest(".data-grid-row");if(!n)return;const r=this.getRowIndex(n);r<0||(this.isDragging=!0,this.draggedRowIndex=r,t.dataTransfer&&(t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",String(r))),n.classList.add("dragging"))},{signal:t}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.clearDragClasses()},{signal:t}),e.addEventListener("dragover",e=>{const t=e;if(!this.isDragging||null===this.draggedRowIndex)return;const i=t.target.closest(".data-grid-row");if(!i)return;t.preventDefault();const n=this.getRowIndex(i);if(n<0||n===this.draggedRowIndex)return;const r=i.getBoundingClientRect(),o=r.top+r.height/2,s=t.clientY<o;this.dropRowIndex=s?n:n+1,i.classList.add("drop-target"),i.classList.toggle("drop-before",s),i.classList.toggle("drop-after",!s)},{signal:t}),e.addEventListener("dragleave",e=>{const t=e.target.closest(".data-grid-row");t&&t.classList.remove("drop-target","drop-before","drop-after")},{signal:t}),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")}},{signal:t})}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.#pt,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),fe(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.#pt;r._rows=i,r._focusRow=e,r._focusCol=this.lastFocusCol,r.refreshVirtualWindow(!0),fe(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 Ct{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;pendingRowKeyUpdate=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.pendingRowKeyUpdate=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&&wi(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.#Qi()),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.#Qi()),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=An(this.cellAnchor,{row:t,col:i}),n=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(n&&kn(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&&kn(this.ranges[0],e))return!1;this.ranges=[e],this.activeRange=e,this.cellAnchor={row:t,col:i}}return this.emit("selection-change",this.#Qi()),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.#Qi()),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.#Qi()),this.requestAfterRender()}),!1;if("row"===t){const t=!1!==this.config.multiSelect;if("ArrowUp"===e.key||"ArrowDown"===e.key||"PageUp"===e.key||"PageDown"===e.key||(e.ctrlKey||e.metaKey)&&("Home"===e.key||"End"===e.key)){const i=e.shiftKey&&t;return i&&null===this.anchor&&(this.anchor=this.grid._focusRow),this.explicitSelection=!0,this.pendingRowKeyUpdate={shiftKey:i},queueMicrotask(()=>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&&wi(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&&kn(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.#Qi()),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&&wi(i)){const e=this.visibleColumns.findIndex(e=>!wi(e));e>=0&&(t=e)}const n=An(this.cellAnchor,{row:e.rowIndex,col:t}),r=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return r&&kn(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.#Qi()),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===Tn))return e;const t=this.#Ji(),i=e.findIndex(fi),n=i>=0?i+1:0;return[...e.slice(0,n),t,...e.slice(n)]}return e}#Ji(){return{field:Tn,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}}}#en(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const t=e.closest(".cell"),i=t?Q(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}}#tn(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.#Qi()))))}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.#Qi()))}}}#in(){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"),e.setAttribute("aria-selected","false"),i&&e.removeAttribute("data-selectable")}),"row"===t&&(J(e),n.forEach(e=>{const t=Q(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"),e.setAttribute("aria-selected","true")))}),this.config.checkbox&&this.#en(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){J(e);const t=this.ranges.map(xn),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&&wi(r))return;i(t,n)&&(e.classList.add("selected"),e.setAttribute("aria-selected","true"),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.pendingRowKeyUpdate&&"row"===i){const{shiftKey:e}=this.pendingRowKeyUpdate;this.pendingRowKeyUpdate=null;const t=this.grid._focusRow;if(e&&null!==this.anchor){this.selected.clear();const e=Math.min(this.anchor,t),i=Math.max(this.anchor,t);for(let t=e;t<=i;t++)this.isRowSelectable(t)&&this.selected.add(t)}else this.isRowSelectable(t)?(this.selected.clear(),this.selected.add(t),this.anchor=t):this.selected.clear();this.lastSelected=t,this.emit("selection-change",this.#Qi())}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=An(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.#Qi())}this.#tn(i),this.gridElement.setAttribute("data-selection-mode",i),t&&t.classList.toggle("selecting",this.isDragging),this.#in()}onScrollRender(){this.isSelectionEnabled()&&this.#in()}getSelection(){return{mode:this.config.mode,ranges:this.#Qi().ranges,anchor:this.cellAnchor}}getSelectedCells(){return function(e){const t=new Map;for(const i of e)for(const e of _n(i))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return Sn(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.#Qi()),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.#Qi()),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.#Qi()),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:En(this.ranges)}),this.requestAfterRender()}#Qi(){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:En(t.ranges)}:{mode:e,ranges:[]}}(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}},e.ServerSidePlugin=class extends Ct{name="serverSide";get defaultConfig(){return{pageSize:100,cacheBlockSize:100,maxConcurrentRequests:2}}dataSource=null;totalRowCount=0;loadedBlocks=new Map;loadingBlocks=new Set;lastRequestId=0;scrollDebounceTimer;managedRows=[];detach(){this.dataSource=null,this.totalRowCount=0,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedRows=[],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=Mn(e,i),r=Mn(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),Ln(this.dataSource,r,t,{}).then(e=>{this.loadedBlocks.set(r,e.rows),this.totalRowCount=e.totalRowCount,this.loadingBlocks.delete(r);const i=r*t;for(let t=0;t<e.rows.length;t++)i+t<this.managedRows.length&&(this.managedRows[i+t]=e.rows[t]);this.requestVirtualRefresh(),this.loadRequiredBlocks()}).catch(()=>{this.loadingBlocks.delete(r)})}}processRows(e){if(!this.dataSource)return[...e];const t=this.config.cacheBlockSize??100;for(;this.managedRows.length<this.totalRowCount;){const e=this.managedRows.length;this.managedRows.push({__loading:!0,__index:e})}this.managedRows.length=this.totalRowCount;for(let i=0;i<this.totalRowCount;i++){const e=In(i,t,this.loadedBlocks);e&&(this.managedRows[i]=e)}return this.managedRows}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(),this.managedRows=[];Ln(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.managedRows=[],this.requestRender())}purgeCache(){this.loadedBlocks.clear(),this.managedRows=[]}getTotalRowCount(){return this.totalRowCount}isRowLoaded(e){const t=Mn(e,this.config.cacheBlockSize??100);return this.loadedBlocks.has(t)}getLoadedBlockCount(){return this.loadedBlocks.size}},e.TreePlugin=class extends Ct{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=Dn(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=Hn(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=Hn(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.gridElement?.querySelector(".rows");if(!e)return;const t=this.animationStyle,i=!1!==t&&this.keysToAnimate.size>0,n="fade"===t?"tbw-tree-fade-in":"tbw-tree-slide-in";for(const r of e.querySelectorAll(".data-grid-row")){const e=r.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,o=this.flattenedRows[t];o?.hasChildren&&r.setAttribute("aria-expanded",String(o.isExpanded)),i&&o?.key&&this.keysToAnimate.has(o.key)&&(r.classList.add(n),r.addEventListener("animationend",()=>r.classList.remove(n),{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=Hn(this.expandedKeys,e),this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}expandAll(){this.expandedKeys=Dn(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=Fn(this.rows,e,this.config,this.expandedKeys),this.requestRender()}},e.UndoRedoPlugin=class extends Ct{static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];#nn=!1;#rn=null;#on(e,t){const i=this.rows[e.rowIndex];if(i){try{const n=this.grid.getRowId(i);if(n)return void this.grid.updateRow(n,{[e.field]:t})}catch{}i[e.field]=t}}#sn(e){const t=this.grid,i=t._visibleColumns?.findIndex(t=>t.field===e.field)??-1;if(i<0)return;t._focusRow=e.rowIndex,t._focusCol=i;const n=t.findRenderedRowElement?.(e.rowIndex);if(!n)return;const r=n.querySelector(`.cell[data-col="${i}"]`);if(r?.classList.contains("editing")){const e=r.querySelector(re);e?.focus({preventScroll:!0})}}#ln(e,t){if(this.#nn=!0,"compound"===e.type){const i="undo"===t?[...e.actions].reverse():e.actions;for(const e of i)this.#on(e,"undo"===t?e.oldValue:e.newValue)}else this.#on(e,"undo"===t?e.oldValue:e.newValue);this.#nn=!1}#an(e){const t="compound"===e.type?e.actions[e.actions.length-1]:e;t&&this.#sn(t)}attach(e){super.attach(e),this.on("cell-edit-committed",e=>{this.#nn||this.recordEdit(e.rowIndex,e.field,e.oldValue,e.newValue)})}detach(){this.undoStack=[],this.redoStack=[],this.#rn=null}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){e.preventDefault();const t=Nn({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#ln(t.action,"undo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.emit("undo",{action:t.action,type:"undo"}),this.#an(t.action),this.requestRenderWithFocus()),!0}if(i){e.preventDefault();const t=Gn({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#ln(t.action,"redo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.emit("redo",{action:t.action,type:"redo"}),this.#an(t.action),this.requestRenderWithFocus()),!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);if(this.#rn)return void this.#rn.push(r);const o=qn({undoStack:this.undoStack,redoStack:this.redoStack},r,this.config.maxHistorySize??100);this.undoStack=o.undoStack,this.redoStack=o.redoStack}beginTransaction(){this.#rn&&h("TBW111","Transaction already in progress. Call endTransaction() first."),this.#rn=[]}endTransaction(){const e=this.#rn;if(e||h("TBW112","No transaction in progress. Call beginTransaction() first."),this.#rn=null,0===e.length)return;const t=1===e.length?e[0]:{type:"compound",actions:e,timestamp:Date.now()};const i=qn({undoStack:this.undoStack,redoStack:this.redoStack},t,this.config.maxHistorySize??100);this.undoStack=i.undoStack,this.redoStack=i.redoStack}undo(){const e=Nn({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#ln(e.action,"undo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.#an(e.action),this.requestRenderWithFocus()),e.action}redo(){const e=Gn({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#ln(e.action,"redo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.#an(e.action),this.requestRenderWithFocus()),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,this.#rn=null}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}},e.VisibilityPlugin=Wn,e.builtInSort=D,e.createGrid=function(e){const t=document.createElement("tbw-grid");return e&&(t.gridConfig=e),t},e.defaultComparator=H,e.defaultEditorFor=Ut,e.defaultPasteHandler=Tt,e.getUniqueValuesBatch=gi,e.printGridIsolated=bn,e.queryGrid=function(e,t,i){let n=document,r=!1;return"boolean"==typeof t?r=t:t&&(n=t,r=!!i),r?customElements.whenDefined(yt.tagName).then(()=>n.querySelector(e)):n.querySelector(e)},e.resolveColumnGroupDefs=Ri,e.setFeatureResolver=function(e){ye=e},e.slugifyHeader=xi,Object.defineProperty(e,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";function t(e,t){const i=e.querySelector?.(".tbw-sr-only");i&&(i.textContent="",requestAnimationFrame(()=>{i.textContent=t}))}const i={STRETCH:"stretch",FIXED:"fixed"},r={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>',o={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:n,filterActive:n,print:"🖨️"};function s(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}const l="TBW041",a="TBW061",d="TBW062";function c(e,t,i,r){return`${s(i,r)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}function h(e,t,i,r){throw new Error(c(e,t,i,r))}function u(e,t,i,r){console.warn(c(e,t,i,r))}function g(e,t,i,r){console.debug(c(e,t,i,r))}function p(e,t,i,r){console.error(c(e,t,i,r))}function f(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,r=t.renderer||t.viewRenderer;i&&!r&&(t.viewRenderer=i,e.renderer&&(t.renderer=i)),e.editor&&!t.editor&&(t.editor=e.editor)}else i[e.field]={...e}});const r=e.map(e=>{const t=i[e.field];if(!t)return e;const r={...e};t.header&&!r.header&&(r.header=t.header),t.type&&!r.type&&(r.type=t.type),r.sortable=e.sortable||t.sortable,!0!==e.resizable&&!0!==t.resizable||(r.resizable=!0),r.editable=e.editable||t.editable,null!=t.width&&null==r.width&&(r.width=t.width),null!=t.minWidth&&null==r.minWidth&&(r.minWidth=t.minWidth),t.__viewTemplate&&(r.__viewTemplate=t.__viewTemplate),t.__editorTemplate&&(r.__editorTemplate=t.__editorTemplate),t.__headerTemplate&&(r.__headerTemplate=t.__headerTemplate);const n=t.renderer||t.viewRenderer,o=r.renderer||r.viewRenderer;return n&&!o&&(r.viewRenderer=n,t.renderer&&(r.renderer=n)),t.editor&&!r.editor&&(r.editor=t.editor),delete i[e.field],r});return Object.keys(i).forEach(e=>r.push(i[e])),r}function w(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 m(e){const t=e.effectiveConfig?.fitMode||e.fitMode||i.STRETCH;if(t!==i.STRETCH&&t!==i.FIXED)return;if(e.__didInitialAutoSize)return;if(!e.isConnected)return;const r=Array.from(e._headerRowEl?.children||[]);if(!r.length)return;let n=!1;e._visibleColumns.forEach((t,i)=>{if(t.width)return;const o=r[i];let s=o?o.scrollWidth:0;for(const r of e._rowPool){const e=r.children[i];if(e){const t=e.scrollWidth;t>s&&(s=t)}}s>0&&(t.width=s+2,t.__autoSized=!0,n=!0)}),n&&y(e),e.__didInitialAutoSize=!0}const b=/^(?:\d+(?:\.\d+)?(?:px|%|fr|em|rem|ch|vw|vh|vmin|vmax)|calc\(.+\)|min-content|max-content|minmax\(.+\)|fit-content\(.+\)|auto)$/i;function v(e,t){return"number"==typeof e?`${e}px`:(b.test(e)||u("TBW050",`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 y(e){const t=e.effectiveConfig?.fitMode||e.fitMode||i.STRETCH;e._gridTemplate=t===i.STRETCH?e._visibleColumns.map(e=>{if(null!=e.width)return v(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?v(e.width,e.field):"max-content").join(" "),e.style.setProperty("--tbw-column-template",e._gridTemplate)}const C=/{{\s*([^}]+)\s*}}/g,x="__DG_EMPTY__",R=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,E=/__(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 S=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"]),_=/^on\w+$/i,A=new Set(["href","src","action","formaction","data","srcdoc","xlink:href","poster","srcset"]),k=/^\s*(javascript|vbscript|data|blob):/i;function T(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 r of i){const e=r.tagName.toLowerCase();if(S.has(e)){t.push(r);continue}if("svg"===e||"http://www.w3.org/2000/svg"===r.namespaceURI){if(Array.from(r.attributes).some(e=>_.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(r);continue}}const i=[];for(const t of r.attributes){const e=t.name.toLowerCase();_.test(e)?i.push(t.name):(A.has(e)&&k.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&i.push(t.name)}i.forEach(e=>r.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}function M(e,t){if(!e||-1===e.indexOf("{{"))return e;const i=[],r=e.replace(C,(e,r)=>{const n=function(e,t){if(e=(e||"").trim(),!e)return x;if(L.test(e))return x;if("value"===e)return null==t.value?x:String(t.value);if(e.startsWith("row.")&&!/[()?]/.test(e)&&!e.includes(":")){const i=e.slice(4),r=t.row?t.row[i]:void 0;return null==r?x:String(r)}if(e.length>80)return x;if(!R.test(e)||E.test(e))return x;const i=e.match(/\./g);if(i&&i.length>1)return x;try{const i=new Function("value","row",`return (${e});`)(t.value,t.row),r=null==i?"":String(i);return L.test(r)?x:r||x}catch{return x}}(r,t);return i.push({expr:r.trim(),result:n}),n}),n=(o=r)?o.replace(new RegExp(x,"g"),"").replace(/Reflect\.[^<>{}\s]+|\bProxy\b|ownKeys\([^)]*\)/g,""):o;var o;const s=i.length&&i.every(e=>""===e.result||e.result===x);return L.test(e)||s?"":n}const L=/Reflect|Proxy|ownKeys/;function I(e){if(L.test(e.textContent||"")){for(const t of e.childNodes)t.nodeType===Node.TEXT_NODE&&L.test(t.textContent||"")&&(t.textContent="");L.test(e.textContent||"")&&(e.textContent="")}}function P(e){const t=L.test(e),i=i=>{if(t)return"";return M(e,i)};return i.__blocked=t,i}function H(e,t){return null==e&&null==t?0:null==e?-1:null==t||e>t?1:e<t?-1:0}function D(e,t,i){const r=i.find(e=>e.field===t.field),n=r?.sortComparator??H,{field:o,direction:s}=t;return[...e].sort((e,t)=>n(e[o],t[o],e,t)*s)}function F(e,i,r,n){e._rows=i,e.__rowRenderEpoch++,e._rowPool.forEach(e=>e.__epoch=-1),B(e),e.refreshVirtualWindow(!0),e.dispatchEvent(new CustomEvent("sort-change",{detail:{field:r.field,direction:n}})),t(e,`Sorted by ${r.header??r.field}, ${1===n?"ascending":"descending"}`),e.requestStateChange?.()}function z(e,i){if(e._sortState&&e._sortState.field===i.field)if(1===e._sortState.direction)q(e,i,-1);else{e._sortState=null,e.__rowRenderEpoch++,e._rowPool.forEach(e=>e.__epoch=-1),e._rows=e.__originalOrder.slice(),B(e);const r=e._headerRowEl?.querySelectorAll('[role="columnheader"].sortable');r?.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:i.field,direction:0}})),t(e,"Sort cleared"),e.requestStateChange?.()}else e._sortState||(e.__originalOrder=e._rows.slice()),q(e,i,1)}function q(e,t,i){e._sortState={field:t.field,direction:i};const r={field:t.field,direction:i},n=e._columns,o=(e.effectiveConfig?.sortHandler??D)(e._rows,r,n);o&&"function"==typeof o.then?o.then(r=>{F(e,r,t,i)}):F(e,o,t,i)}function O(e,t){return!1!==e.effectiveConfig?.sortable&&!0===t.sortable}function N(e,t){return!1!==e.effectiveConfig?.resizable&&!1!==t.resizable}function G(e,t){const i=document.createElement("span");w(i,"sort-indicator");const r=e._sortState?.field===t.field?e._sortState.direction:0,n={...o,...e.icons};return function(e,t){"string"==typeof t?e.textContent=t:t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}(i,1===r?n.sortAsc:-1===r?n.sortDesc:n.sortNone),i}function $(e,t,i){const r=document.createElement("div");return r.className="resize-handle",r.setAttribute("aria-hidden","true"),r.addEventListener("mousedown",r=>{r.stopPropagation(),r.preventDefault(),e._resizeController.start(r,t,i)}),r.addEventListener("dblclick",i=>{i.stopPropagation(),i.preventDefault(),e._resizeController.resetColumn(t)}),r}function W(e,t,i,r){r.classList.add("sortable"),r.tabIndex=0;const n=e._sortState?.field===t.field?e._sortState.direction:0;r.setAttribute("aria-sort",0===n?"none":1===n?"ascending":"descending"),r.addEventListener("click",i=>{e._resizeController?.isResizing||e._dispatchHeaderClick?.(i,t,r)||z(e,t)}),r.addEventListener("keydown",i=>{if("Enter"===i.key||" "===i.key){if(i.preventDefault(),e._dispatchHeaderClick?.(i,t,r))return;z(e,t)}})}function B(e){e._headerRowEl=e.findHeaderRow();const t=e._headerRowEl;t&&(t.innerHTML="",e._visibleColumns.forEach((i,r)=>{const n=document.createElement("div");n.className="cell",w(n,"header-cell"),n.setAttribute("role","columnheader"),n.setAttribute("aria-colindex",String(r+1)),n.setAttribute("data-field",i.field),n.setAttribute("data-col",String(r)),i.type&&n.setAttribute("data-type",i.type);const o=i.header??i.field,s=e._sortState?.field===i.field?e._sortState.direction:0,l=1===s?"asc":-1===s?"desc":null;if(i.headerRenderer){const t={column:i,value:o,sortState:l,filterActive:!1,cellEl:n,renderSortIcon:()=>O(e,i)?G(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=T(t);i.firstChild;)e.appendChild(i.firstChild)}else t instanceof Node&&e.appendChild(t)}(n,s),O(e,i)&&W(e,i,0,n),N(e,i)&&(n.classList.add("resizable"),n.appendChild($(e,r,n)))}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=T(s):s instanceof Node&&l.appendChild(s),n.appendChild(l),O(e,i)&&(W(e,i,0,n),n.appendChild(G(e,i))),N(e,i)&&(n.classList.add("resizable"),n.appendChild($(e,r,n)))}else if(i.__headerTemplate)Array.from(i.__headerTemplate.childNodes).forEach(e=>n.appendChild(e.cloneNode(!0))),O(e,i)&&(W(e,i,0,n),n.appendChild(G(e,i))),N(e,i)&&(n.classList.add("resizable"),n.appendChild($(e,r,n)));else{const t=document.createElement("span");t.textContent=o,n.appendChild(t),O(e,i)&&(W(e,i,0,n),n.appendChild(G(e,i))),N(e,i)&&(n.classList.add("resizable"),n.appendChild($(e,r,n)))}t.appendChild(n)}),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")))}function V(e,t){const i=e[0]||{},r=Object.keys(i).map(e=>{const t=i[e],r=null==(n=t)?"string":"number"==typeof n?"number":"boolean"==typeof n?"boolean":n instanceof Date||"string"==typeof n&&/\d{4}-\d{2}-\d{2}/.test(n)&&!isNaN(Date.parse(n))?"date":"string";var n;return{field:e,header:e.charAt(0).toUpperCase()+e.slice(1),type:r}}),n={};return r.forEach(e=>{n[e.field]=e.type||"string"}),{columns:r,typeMap:n}}var K=(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))(K||{});class U{#e;#t=0;#i=0;#r=null;#n=null;#o=null;#s=!1;constructor(e){this.#e=e}requestPhase(e,t){e>this.#t&&(this.#t=e),0===this.#i&&(this.#l(),this.#i=requestAnimationFrame(()=>this.#a()))}whenReady(){return this.#r?this.#r:Promise.resolve()}setInitialReadyResolver(e){this.#o=e}cancel(){0!==this.#i&&(cancelAnimationFrame(this.#i),this.#i=0),this.#t=0,this.#n&&(this.#n(),this.#n=null,this.#r=null)}get isPending(){return 0!==this.#t}get pendingPhase(){return this.#t}#l(){this.#r||(this.#r=new Promise(e=>{this.#n=e}))}#a(){if(this.#i=0,!this.#e._schedulerIsConnected)return this.#t=0,void(this.#n&&(this.#n(),this.#n=null,this.#r=null));const e=this.#t;this.#t=0,e>=5&&this.#e._schedulerMergeConfig(),e>=4&&this.#e._schedulerProcessRows(),e>=5&&(this.#e._schedulerProcessColumns(),this.#e._schedulerUpdateTemplate()),e>=3&&this.#e._schedulerRenderHeader(),e>=2&&this.#e.refreshVirtualWindow(!0,!0),e>=1&&this.#e._schedulerAfterRender(),!this.#s&&this.#o&&(this.#s=!0,this.#o()),this.#n&&(this.#n(),this.#n=null,this.#r=null)}}class j{#d;#c;#h;#u;#g;#p={};#f={};#w=!0;#m=[];#b;#v;#y;#C;#e;#x;constructor(e){this.#e=e}get original(){return this.#p}get effective(){return this.#f}get columns(){return this.#f.columns??[]}set columns(e){this.#f.columns=e}get lightDomColumnsCache(){return this.#u}set lightDomColumnsCache(e){this.#u=e}get originalColumnNodes(){return this.#g}set originalColumnNodes(e){this.#g=e}get lightDomTitle(){return this.#x}set lightDomTitle(e){this.#x=e}get initialColumnState(){return this.#C}set initialColumnState(e){this.#C=e}get sourcesChanged(){return this.#w}markSourcesChanged(){this.#w=!0}setGridConfig(e){this.#d=e,this.#w=!0,this.#u=void 0}getGridConfig(){return this.#d}setColumns(e){this.#c=e,this.#w=!0}getColumns(){return this.#c}setFitMode(e){this.#h=e,this.#w=!0}getFitMode(){return this.#h}merge(){const e=(this.#f.columns?.length??0)>0;if(!this.#w&&e)return;const t=this.#R();this.#w=!1,this.#p=t,Object.freeze(this.#p),this.#p.columns&&Object.freeze(this.#p.columns),this.#f=this.#E(this.#p),this.#S()}#E(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}#S(){const e=this.#f;if(this.#_(),"number"==typeof e.rowHeight&&e.rowHeight>0&&(this.#e._virtualization.rowHeight=e.rowHeight),"fixed"===e.fitMode){this.columns.forEach(e=>{null==e.width&&(e.width=80)})}this.#e._applyAnimationConfig(e)}#_(){const e=this.#f.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))}}#R(){const e=this.#d?{...this.#d}:{},t=Array.isArray(e.columns)?[...e.columns]:[],i=(this.#u??[]).map(e=>({...e}));let r=f(t,i);this.#c&&this.#c.length&&(r=f(this.#c,i));const n=this.#e.sourceRows;if(0===r.length&&n.length){r=V(n).columns}return r.length&&(r.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)}),r.forEach(e=>{e.__viewTemplate&&!e.__compiledView&&(e.__compiledView=P(e.__viewTemplate.innerHTML)),e.__editorTemplate&&!e.__compiledEditor&&(e.__compiledEditor=P(e.__editorTemplate.innerHTML))}),e.columns=r),this.#h&&(e.fitMode=this.#h),e.fitMode||(e.fitMode="stretch"),this.#A(e),e.columnState&&!this.#C&&(this.#C=e.columnState),e}#A(e){e.shell=e.shell?{...e.shell}:{},e.shell.header=e.shell.header?{...e.shell.header}:{};const t=this.#e._shellState.lightDomTitle;t&&(this.#x=t),this.#x&&!e.shell.header.title&&(e.shell.header.title=this.#x);const i=this.#e._shellState.lightDomHeaderContent;i?.length>0&&(e.shell.header.lightDomContent=i),this.#e._shellState.hasToolButtonsContainer&&(e.shell.header.hasToolButtonsContainer=!0);const r=this.#e._shellState.toolPanels;if(r.size>0){const t=Array.from(r.values());t.sort((e,t)=>(e.order??100)-(t.order??100)),e.shell.toolPanels=t}const n=this.#e._shellState.headerContents;if(n.size>0){const t=Array.from(n.values());t.sort((e,t)=>(e.order??100)-(t.order??100)),e.shell.headerContents=t}const o=this.#e._shellState.toolbarContents,s=Array.from(o.values()),l=this.#d?.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.#k();return{columns:t.map((t,r)=>{const n={field:t.field,order:r,visible:!t.hidden},o=t;void 0!==o.__renderedWidth?n.width=o.__renderedWidth:void 0!==t.width&&(n.width="string"==typeof t.width?parseFloat(t.width):t.width);const s=i.get(t.field);s&&(n.sort=s);for(const i of e)if(i.getColumnState){const e=i.getColumnState(t.field);e&&Object.assign(n,e)}return n})}}applyState(e,t){if(!e.columns||0===e.columns.length)return;const i=this.columns,r=new Map(e.columns.map(e=>[e.field,e])),n=i.map(e=>{const t=r.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});n.sort((e,t)=>(r.get(e.field)?.order??1/0)-(r.get(t.field)?.order??1/0)),this.columns=n;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.#e._sortState={field:e.field,direction:"asc"===e.sort.direction?1:-1})}else this.#e._sortState=null;for(const s of t)if(s.applyColumnState)for(const t of e.columns)s.applyColumnState(t.field,t)}resetState(e){this.#C=void 0,this.#e._sortState=null,this.#f=this.#E(this.#p),this.#S();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)}#k(){const e=new Map,t=this.#e._sortState;return t&&e.set(t.field,{direction:1===t.direction?"asc":"desc",priority:0}),e}requestStateChange(e){this.#v&&clearTimeout(this.#v),this.#v=setTimeout(()=>{this.#v=void 0;const t=this.collectState(e);this.#e._emit("column-state-change",t)},100)}setColumnVisible(e,t){const i=this.columns,r=i.find(t=>t.field===e);if(!r)return!1;if(!t&&r.lockVisible)return!1;if(!t){if(0===i.filter(t=>!t.hidden&&t.field!==e).length)return!1}return!!r.hidden!=!t&&(r.hidden=!t,this.#e._emit("column-visibility",{field:e,visible:t,visibleColumns:i.filter(e=>!e.hidden).map(e=>e.field)}),this.#e._clearRowPool(),this.#e._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.#e._emit("column-visibility",{visibleColumns:e.map(e=>e.field)}),this.#e._clearRowPool(),this.#e._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 r of e){const e=t.get(r);e&&(i.push(e),t.delete(r))}for(const r of t.values())i.push(r);this.columns=i,B(this.#e),y(this.#e),this.#e._requestSchedulerPhase(K.VIRTUALIZATION,"configManager")}parseLightDomColumns(e){this.#u||(this.#g=Array.from(e.querySelectorAll("tbw-grid-column")),this.#u=this.#g.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,r={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")},n=e.getAttribute("width");if(n){const e=parseFloat(n);!isNaN(e)&&/^\d+(\.\d+)?$/.test(n.trim())?r.width=e:r.width=n}const o=e.getAttribute("minWidth")||e.getAttribute("min-width");if(o){const e=parseFloat(o);isNaN(e)||(r.minWidth=e)}e.hasAttribute("resizable")&&(r.resizable=!0),e.hasAttribute("sizable")&&(r.resizable=!0);const s=e.getAttribute("editor"),l=e.getAttribute("renderer");s&&(r.__editorName=s),l&&(r.__rendererName=l);const a=e.getAttribute("options");a&&(r.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&&(r.__viewTemplate=d),c&&(r.__editorTemplate=c),h&&(r.__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&&(r.viewRenderer=e)}const w=c??e,m=g.find(e=>e.canHandle(w));if(m){const e=m.createEditor(w);e&&(r.editor=e)}return r}).filter(e=>!!e)}(e):[])}clearLightDomCache(){this.#u=void 0}#T=new Map;registerLightDomHandler(e,t){this.#T.set(e.toLowerCase(),t)}unregisterLightDomHandler(e){this.#T.delete(e.toLowerCase())}observeLightDOM(e){this.#b&&this.#b.disconnect();const t=new Set,i=()=>{this.#y=void 0;for(const e of t){const t=this.#T.get(e);t?.()}t.clear()};this.#b=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.#T.has(i)&&t.add(i)}if("attributes"===i.type&&i.target.nodeType===Node.ELEMENT_NODE){const e=i.target.tagName.toLowerCase();this.#T.has(e)&&t.add(e)}}t.size>0&&!this.#y&&(this.#y=setTimeout(i,0))}),this.#b.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["title","field","header","width","hidden","id","icon","tooltip","order"]})}onChange(e){this.#m.push(e)}notifyChange(){for(const e of this.#m)e()}dispose(){this.#b?.disconnect(),this.#m=[],this.#v&&clearTimeout(this.#v),this.#y&&(clearTimeout(this.#y),this.#y=void 0)}}function Y(){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 X(e){return`<span role="checkbox" aria-checked="${e}" aria-label="${e}">${e?"🗹":"☐"}</span>`}function Z(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 Q(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 r=i.parentElement;if(!r)return-1;const n=r.querySelectorAll(":scope > .data-grid-row");for(let o=0;o<n.length;o++)if(n[o]===i)return o;return-1}function J(e){e&&e.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function ee(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 te(e){return"rtl"===ee(e)}function ie(e,t){const i=t.renderer||t.viewRenderer;if(i)return i;if(!t.type)return;const r=e.__frameworkAdapter;if(r?.getTypeDefault){const e=r.getTypeDefault(t.type);if(e?.renderer)return e.renderer}}function re(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 ne='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function oe(e){return(e.__editingCellCount??0)>0}function se(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing");e.querySelectorAll(".cell.editing").forEach(e=>e.classList.remove("editing"))}const le=document.createElement("template");le.innerHTML='<div class="cell" role="gridcell" part="cell"></div>';const ae=document.createElement("template");function de(){return le.content.firstElementChild.cloneNode(!0)}function ce(){return ae.content.firstElementChild.cloneNode(!0)}function he(e){e.__cellDisplayCache=void 0,e.__cellCacheEpoch=void 0,e.__hasSpecialColumns=void 0}function ue(e,t,i,r){const n=t.children,o=e._visibleColumns,s=o.length,l=n.length,c=s<l?s:l,h=e._focusRow,g=e._focusCol,p=e._hasAfterCellRenderHook?.()??!1;let f=e.__hasSpecialColumns;if(void 0===f){f=!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||i.cellClass||"date"===i.type||"boolean"===i.type||i.type&&t?.getTypeDefault?.(i.type)?.renderer||i.type&&t?.getTypeDefault?.(i.type)?.format){f=!0;break}}e.__hasSpecialColumns=f}const w=String(r);if(f){for(let s=0;s<c;s++){if(o[s].externalView){if(!n[s].querySelector("[data-external-view]"))return void ge(e,t,i,r)}}for(let s=0;s<c;s++){const l=o[s],c=n[s];c.getAttribute("data-row")!==w&&c.setAttribute("data-row",w);const f=c.classList.contains("editing");if(!f){const e=h===r&&g===s;e!==c.classList.contains("cell-focus")&&(c.classList.toggle("cell-focus",e),c.setAttribute("aria-selected",String(e)))}const b=l.cellClass;if(b){const t=c.getAttribute("data-dynamic-classes");t&&t.split(" ").forEach(e=>e&&c.classList.remove(e));try{const e=b(i[l.field],i,l),t="string"==typeof e?e.split(/\s+/):e;if(t&&t.length>0){const e=t.filter(e=>e&&"string"==typeof e);e.forEach(e=>c.classList.add(e)),c.setAttribute("data-dynamic-classes",e.join(" "))}else c.removeAttribute("data-dynamic-classes")}catch(m){u(a,`cellClass callback error for column '${l.field}': ${m}`,e.id),c.removeAttribute("data-dynamic-classes")}}if(f)continue;const v=ie(e,l);if(v){const n=i[l.field],o=v({row:i,value:n,field:l.field,column:l,cellEl:c});"string"==typeof o?(e.__frameworkAdapter?.releaseCell?.(c),c.innerHTML=T(o)):o instanceof Node?o.parentElement!==c&&(e.__frameworkAdapter?.releaseCell?.(c),c.innerHTML="",c.appendChild(o)):null==o&&(e.__frameworkAdapter?.releaseCell?.(c),c.textContent=null==n?"":String(n)),p&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:s,value:n,cellElement:c,rowElement:t});continue}if(l.__compiledView){const n=i[l.field],o=l.__compiledView({row:i,value:n,field:l.field,column:l});l.__compiledView.__blocked?c.textContent="":(c.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(c),c.innerHTML=T(o),I(c)),p&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:s,value:n,cellElement:c,rowElement:t});continue}if(l.__viewTemplate){const n=i[l.field],o=l.__viewTemplate.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(o)?c.textContent="":(c.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(c),c.innerHTML=T(M(o,{row:i,value:n})),I(c)),p&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:s,value:n,cellElement:c,rowElement:t});continue}if(l.externalView)continue;const y=i[l.field];let C;const x=re(e,l);if(x){try{const e=x(y,i);C=null==e?"":String(e)}catch(m){u(d,`Format error in column '${l.field}': ${m}`,e.id),C=null==y?"":String(y)}c.textContent=C}else"date"===l.type?(C=Z(y),c.textContent=C):"boolean"===l.type?c.innerHTML=X(!!y):(C=null==y?"":String(y),c.textContent=C);p&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:s,value:y,cellElement:c,rowElement:t})}}else for(let a=0;a<c;a++){const s=n[a];if(s.classList.contains("editing"))continue;s.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(s);const l=o[a],d=i[l.field];s.textContent=null==d?"":String(d),s.getAttribute("data-row")!==w&&s.setAttribute("data-row",w);const c=h===r&&g===a;c!==s.classList.contains("cell-focus")&&(s.classList.toggle("cell-focus",c),s.setAttribute("aria-selected",String(c))),p&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:a,value:d,cellElement:s,rowElement:t})}}function ge(e,t,i,r){t.classList.remove("tbw-row-loading"),t.removeAttribute("aria-busy");const n=e.__frameworkAdapter;if(n?.releaseCell){const e=t.children;for(let t=e.length-1;t>=0;t--)n.releaseCell(e[t])}t.innerHTML="";const o=e._visibleColumns,s=o.length,l=e._focusRow,c=e._focusCol,h=e._hasAfterCellRenderHook?.()??!1,g=document.createDocumentFragment();for(let f=0;f<s;f++){const n=o[f],s=de();s.setAttribute("aria-colindex",String(f+1)),s.setAttribute("data-col",String(f)),s.setAttribute("data-row",String(r)),s.setAttribute("data-field",n.field),s.setAttribute("data-header",n.header??n.field),n.type&&s.setAttribute("data-type",n.type);let w=i[n.field];const m=re(e,n);if(m)try{w=m(w,i)}catch(p){u(d,`Format error in column '${n.field}': ${p}`,e.id)}const b=n.__compiledView,v=n.__viewTemplate,y=ie(e,n),C=n.externalView;let x=!1;if(y){const e=y({row:i,value:w,field:n.field,column:n,cellEl:s});"string"==typeof e?(s.innerHTML=T(e),x=!0):e instanceof Node?e.parentElement!==s&&(s.textContent="",s.appendChild(e)):null==e&&(s.textContent=null==w?"":String(w))}else if(C){const t=C,r=document.createElement("div");r.setAttribute("data-external-view",""),r.setAttribute("data-field",n.field),s.appendChild(r);const o={row:i,value:w,field:n.field,column:n};if(t.mount)try{t.mount({placeholder:r,context:o,spec:t})}catch(p){u("TBW063",`External view mount error for column '${n.field}': ${p}`,e.id)}else queueMicrotask(()=>{try{e.dispatchEvent(new CustomEvent("mount-external-view",{bubbles:!0,composed:!0,detail:{placeholder:r,spec:t,context:o}}))}catch(p){u("TBW064",`External view event dispatch error for column '${n.field}': ${p}`,e.id)}});r.setAttribute("data-mounted","")}else if(b){const e=b({row:i,value:w,field:n.field,column:n}),t=b.__blocked;s.innerHTML=t?"":T(e),x=!0,t&&(s.textContent="",s.setAttribute("data-blocked-template",""))}else if(v){const e=v.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(e)?(s.textContent="",s.setAttribute("data-blocked-template","")):(s.innerHTML=T(M(e,{row:i,value:w})),x=!0)}else m?s.textContent=null==w?"":String(w):"date"===n.type?s.textContent=Z(w):"boolean"===n.type?s.innerHTML=X(!!w):s.textContent=null==w?"":String(w);if(x){I(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="");("function"==typeof n.editable?n.editable(i):n.editable)?s.tabIndex=0:"boolean"===n.type&&(s.hasAttribute("tabindex")||(s.tabIndex=0)),l===r&&c===f?(s.classList.add("cell-focus"),s.setAttribute("aria-selected","true")):s.setAttribute("aria-selected","false");const R=n.cellClass;if(R)try{const e=R(i[n.field],i,n),t="string"==typeof e?e.split(/\s+/):e;if(t&&t.length>0){let e="";for(const i of t)i&&"string"==typeof i&&(s.classList.add(i),e+=(e?" ":"")+i);s.setAttribute("data-dynamic-classes",e)}}catch(p){u(a,`cellClass callback error for column '${n.field}': ${p}`,e.id)}h&&e._afterCellRender?.({row:i,rowIndex:r,column:n,colIndex:f,value:w,cellElement:s,rowElement:t}),g.appendChild(s)}t.appendChild(g)}function pe(e,t,i){if(t.target?.closest(".resize-handle"))return;const r=Q(i.querySelector(".cell[data-row]"));if(r<0)return;const n=e._rows[r];if(!n)return;if(e._dispatchRowClick?.(t,r,n,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,r,i,o))return;const n=e._focusRow!==r||e._focusCol!==i;if(e._focusRow=r,e._focusCol=i,o.classList.contains("editing")){n&&(J(e._bodyEl??e),o.classList.add("cell-focus"));const i=t.target,r=o.contains(i)&&i.matches(ne)?i:o.querySelector(ne);try{r?.focus({preventScroll:!0})}catch{}return}fe(e)}}}function fe(e,t){if(e._virtualization?.enabled){const{rowHeight:t,container:i,viewportEl:r}=e._virtualization,n=i,o=r?.clientHeight??n?.clientHeight??0;if(n&&o>0){const i=e._focusRow*t;i<n.scrollTop?n.scrollTop=i:i+t>n.scrollTop+o&&(n.scrollTop=i-o+t)}}const i=void 0!==e._activeEditRows&&-1!==e._activeEditRows||!!e._isGridEditMode;i||e.refreshVirtualWindow(!1),J(e._bodyEl),Array.from(e._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(e=>{e.setAttribute("aria-selected","false")});const r=e._focusRow,n=e._virtualization.start??0,o=e._virtualization.end??e._rows.length;if(r>=n&&r<o){const o=e._bodyEl.querySelectorAll(".data-grid-row")[r-n];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 r=e.querySelector(".tbw-scroll-area");if(r&&s&&(!i||t?.forceHorizontalScroll))if(t?.forceScrollLeft)r.scrollLeft=0;else if(t?.forceScrollRight)r.scrollLeft=r.scrollWidth-r.clientWidth;else{const t=e._getHorizontalScrollOffsets?.(o??void 0,s)??{left:0,right:0};if(!t.skipScroll){const e=s.getBoundingClientRect(),i=r.getBoundingClientRect(),n=e.left-i.left+r.scrollLeft,o=n+e.width,l=r.scrollLeft+t.left,a=r.scrollLeft+r.clientWidth-t.right;n<l?r.scrollLeft=n-t.left:o>a&&(r.scrollLeft=o-r.clientWidth+t.right)}}if(i&&s.classList.contains("editing")){const e=s.querySelector(ne);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 i||document.activeElement!==e&&e.focus({preventScroll:!0})}}}ae.innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const we=new WeakMap;function me(e,t){const i=Q(t),r=function(e){if(!e)return-1;const t=e.getAttribute("data-col");return t?parseInt(t,10):-1}(t);if(i<0||r<0)return;e._focusRow=i,e._focusCol=r,J(e._bodyEl),t.classList.add("cell-focus"),t.setAttribute("aria-selected","true");const n=t.closest("tbw-grid");n&&document.activeElement!==n&&n.focus({preventScroll:!0})}function be(e,t,i,r){let n=null;const o=i.composedPath?.();if(n=o&&o.length>0?o[0]:i.target,n&&!t.contains(n)){const e=document.elementFromPoint(i.clientX,i.clientY);e&&(n=e)}const s=n?.closest?.("[data-col]"),l=n?.closest?.(".data-grid-row"),a=n?.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:r,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 ve(e,t,i,r){t.addEventListener("keydown",t=>function(e,t){if(e._dispatchKeyDown?.(t))return;const i=e._rows.length-1,r=e._visibleColumns.length-1,n=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)||n&&"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=r):e._focusCol<r?e._focusCol+=1:("function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow<i&&(e._focusRow+=1,e._focusCol=0)),void fe(e);case"ArrowDown":n&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=Math.min(i,e._focusRow+1),t.preventDefault();break;case"ArrowUp":n&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=Math.max(0,e._focusRow-1),t.preventDefault();break;case"ArrowRight":{const i=te(e);e._focusCol=i?Math.max(0,e._focusCol-1):Math.min(r,e._focusCol+1),t.preventDefault();break}case"ArrowLeft":{const i=te(e);e._focusCol=i?Math.min(r,e._focusCol+1):Math.max(0,e._focusCol-1),t.preventDefault();break}case"Home":return t.ctrlKey||t.metaKey?(n&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=0,e._focusCol=0):e._focusCol=0,t.preventDefault(),void fe(e,{forceScrollLeft:!0});case"End":return t.ctrlKey||t.metaKey?(n&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=i,e._focusCol=r):e._focusCol=r,t.preventDefault(),void fe(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,r=e._focusCol,n=e._visibleColumns[r],o=e._rows[i],s=n?.field??"",l=s&&o?o[s]:void 0,a=e.querySelector(`[data-row="${i}"][data-col="${r}"]`),d=new CustomEvent("cell-activate",{cancelable:!0,detail:{rowIndex:i,colIndex:r,column:n,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:r}});if(e.dispatchEvent(c),d.defaultPrevented||c.defaultPrevented)return void t.preventDefault();break}default:return}fe(e)}}(e,t),{signal:r}),i.addEventListener("mousedown",t=>function(e,t,i){const r=be(e,t,i,"mousedown");e._dispatchCellMouseDown?.(r)&&we.set(e,!0)}(e,i,t),{signal:r}),document.addEventListener("mousemove",t=>function(e,t,i){if(!we.get(e))return;const r=be(e,t,i,"mousemove");e._dispatchCellMouseMove?.(r)}(e,i,t),{signal:r}),document.addEventListener("mouseup",t=>function(e,t,i){if(!we.get(e))return;const r=be(e,t,i,"mouseup");e._dispatchCellMouseUp?.(r),we.set(e,!1)}(e,i,t),{signal:r})}let ye;class Ce{#e;#M=new Set;#L=new Map;constructor(e){this.#e=e}focusCell(e,t){const i=this.#e,r=i._rows.length-1;if(r<0)return;let n;if("string"==typeof t){if(n=i._visibleColumns.findIndex(e=>e.field===t),n<0)return}else n=t;const o=i._visibleColumns.length-1;o<0||(i._focusRow=Math.max(0,Math.min(e,r)),i._focusCol=Math.max(0,Math.min(n,o)),fe(i))}get focusedCell(){const e=this.#e;if(0===e._rows.length||0===e._visibleColumns.length)return null;const t=e._visibleColumns[e._focusCol];return{rowIndex:e._focusRow,colIndex:e._focusCol,field:t?.field??""}}scrollToRow(e,t){const i=this.#e._virtualization;if(!i.enabled)return;const r=i.container;if(!r)return;const n=this.#e._rows.length;if(0===n)return;const o=Math.max(0,Math.min(e,n-1)),s=t?.align??"nearest",l=t?.behavior??"instant";let a,d;const c=i.positionCache;i.variableHeights&&c&&c.length>o?(a=c[o].offset,d=c[o].height):(a=o*i.rowHeight,d=i.rowHeight);const h=i.viewportEl?.clientHeight??r.clientHeight??0;if(h<=0)return;const u=r.scrollTop,g=a+d,p=u+h;let f;switch(s){case"start":f=a;break;case"center":f=a-h/2+d/2;break;case"end":f=g-h;break;default:if(a>=u&&g<=p)return;f=a<u?a:g-h}f=Math.max(0,f),"smooth"===l?r.scrollTo({top:f,behavior:"smooth"}):r.scrollTop=f}scrollToRowById(e,t){const i=this.#e._getRowEntry(e);i&&this.scrollToRow(i.index,t)}registerExternalFocusContainer(e){if(this.#M.has(e))return;this.#M.add(e);const t=new AbortController,i=t.signal,r=this.#e;e.addEventListener("focusin",()=>{r.dataset.hasFocus=""},{signal:i}),e.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&this.containsFocus(t)||delete r.dataset.hasFocus},{signal:i}),this.#L.set(e,()=>t.abort())}unregisterExternalFocusContainer(e){this.#M.delete(e);const t=this.#L.get(e);t&&(t(),this.#L.delete(e))}containsFocus(e){const t=e??document.activeElement;return!!t&&(!!this.#e.contains(t)||this.isInExternalFocusContainer(t))}isInExternalFocusContainer(e){for(const t of this.#M)if(t.contains(e))return!0;return!1}destroy(){for(const e of this.#L.values())e();this.#L.clear(),this.#M.clear()}}const xe="function"==typeof requestIdleCallback;function Re(e){xe?cancelIdleCallback(e):clearTimeout(e)}function Ee(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)}function Se(e){let t=null,i=null,r=null,n=null;const o=r=>{if(!t)return;const n=r.clientX-t.startX,o=Math.max(40,t.startWidth+n),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!==r&&(document.documentElement.style.cursor=r,r=null),null!==n&&(document.body.style.userSelect=n,n=null),t=null,i&&e.requestStateChange&&e.requestStateChange()};return{get isResizing(){return null!==t||s},start(i,s,a){i.preventDefault();const d=e._headerRowEl??e.findHeaderRow?.();d&&function(t,i){const r=i.querySelectorAll(".cell");for(let n=0;n<e._visibleColumns.length;n++){if(n===t)continue;const i=e._visibleColumns[n];if(null==i.width&&!i.__userResized){const e=r[n],t=e?.getBoundingClientRect().width;t&&(i.width=Math.round(t),i.__userResized=!0,i.__renderedWidth=i.width)}}}(s,d);const c=e._visibleColumns[s],h="number"==typeof c?.width?c.width:void 0,u=c?.__renderedWidth??h??a.getBoundingClientRect().width;t={startX:i.clientX,colIndex:s,startWidth:u},window.addEventListener("mousemove",o),window.addEventListener("mouseup",l),null===r&&(r=document.documentElement.style.cursor),document.documentElement.style.cursor="e-resize",null===n&&(n=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 _e="data-animating",Ae={change:"--tbw-row-change-duration",insert:"--tbw-row-insert-duration",remove:"--tbw-row-remove-duration"},ke={change:500,insert:300,remove:200};function Te(e,t){const i=Ae[t],r=getComputedStyle(e).getPropertyValue(i);if(r){const e=function(e){const t=e.trim().toLowerCase();return t.endsWith("ms")?parseFloat(t):t.endsWith("s")?1e3*parseFloat(t):parseFloat(t)}(r);if(!isNaN(e)&&e>0)return e}return ke[t]}function Me(e,t,i){if(t<0)return Promise.resolve(!1);const r=e.findRenderedRowElement?.(t);return r?new Promise(e=>{!function(e,t,i){e.removeAttribute(_e),e.offsetWidth,e.setAttribute(_e,t);const r=Te(e,t);setTimeout(()=>{"remove"!==t&&e.removeAttribute(_e),i?.()},r)}(r,i,()=>e(!0))}):Promise.resolve(!1)}function Le(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}function Ie(e,t,i){const r=Le(e,i);return void 0===r&&h("TBW040",'Cannot determine row ID. Configure getRowId in gridConfig or ensure rows have an "id" property.',t),r}class Pe{#e;constructor(e){this.#e=e}resolveRowId(e){return Ie(e,this.#e.id,this.#e.effectiveConfig?.getRowId)}getRow(e){return this.#e._getRowEntry(e)?.row}getRowEntry(e){return this.#e._getRowEntry(e)}updateRow(e,t,i="api"){const r=this.#e,n=r._getRowEntry(e);n||h(l,`Row with ID "${e}" not found. Ensure the row exists and getRowId is correctly configured.`,r.id);const{row:o,index:s}=n,a=[];for(const[l,d]of Object.entries(t)){const e=o[l];e!==d&&(a.push({field:l,oldValue:e,newValue:d}),o[l]=d)}for(const{field:l,oldValue:d,newValue:c}of a)r.dispatchEvent(new CustomEvent("cell-change",{detail:{row:o,rowId:e,rowIndex:s,field:l,oldValue:d,newValue:c,changes:t,source:i},bubbles:!0,composed:!0}));a.length>0&&(he(r),r._requestSchedulerPhase(K.VIRTUALIZATION,"updateRow"),r._emitDataChange())}updateRows(e,t="api"){const i=this.#e;let r=!1;for(const{id:n,changes:o}of e){const e=i._getRowEntry(n);e||h(l,`Row with ID "${n}" not found. Ensure the row exists and getRowId is correctly configured.`,i.id);const{row:s,index:a}=e;for(const[l,d]of Object.entries(o)){const e=s[l];e!==d&&(r=!0,s[l]=d,i.dispatchEvent(new CustomEvent("cell-change",{detail:{row:s,rowId:n,rowIndex:a,field:l,oldValue:e,newValue:d,changes:o,source:t},bubbles:!0,composed:!0})))}}r&&(he(i),i._requestSchedulerPhase(K.VIRTUALIZATION,"updateRows"),i._emitDataChange())}async insertRow(e,t,i=!0){const r=this.#e,n=Math.max(0,Math.min(e,r._rows.length));r.sourceRows=[...r.sourceRows,t];const o=[...r._rows];o.splice(n,0,t),r._rows=o,r._sortState&&(r.__originalOrder=[...r.__originalOrder,t]),he(r),r._rebuildRowIdMap(),r.__rowRenderEpoch++;for(const s of r._rowPool)s.__epoch=-1;r.refreshVirtualWindow(!0),r._emitPluginEvent("row-inserted",{row:t,index:n}),r._emitDataChange(),i&&(await new Promise(e=>requestAnimationFrame(()=>e())),await Me(r,n,"insert"))}async removeRow(e,t=!0){const i=this.#e,r=i._rows[e];if(!r)return;t&&await Me(i,e,"remove");const n=i._rows.indexOf(r);if(n<0)return r;const o=[...i._rows];o.splice(n,1),i._rows=o;const s=i.sourceRows.indexOf(r);if(s>=0){const e=[...i.sourceRows];e.splice(s,1),i.sourceRows=e}if(i._sortState){const e=i.__originalOrder.indexOf(r);if(e>=0){const t=[...i.__originalOrder];t.splice(e,1),i.__originalOrder=t}}he(i),i._rebuildRowIdMap(),i.__rowRenderEpoch++;for(const l of i._rowPool)l.__epoch=-1;return i.refreshVirtualWindow(!0),i._emitDataChange(),t&&requestAnimationFrame(()=>{i.querySelectorAll('[data-animating="remove"]').forEach(e=>{e.removeAttribute("data-animating")})}),r}async applyTransaction(e,t=!0){const i=this.#e,r={added:[],updated:[],removed:[]};if(e.remove?.length)for(const{id:l}of e.remove){const e=i._getRowEntry(l);if(!e)continue;const{row:n}=e;if(t){const e=i._rows.indexOf(n);e>=0&&await Me(i,e,"remove")}const o=i._rows.indexOf(n);if(o<0){r.removed.push(n);continue}const s=[...i._rows];s.splice(o,1),i._rows=s;const a=i.sourceRows.indexOf(n);if(a>=0){const e=[...i.sourceRows];e.splice(a,1),i.sourceRows=e}if(i._sortState){const e=i.__originalOrder.indexOf(n);if(e>=0){const t=[...i.__originalOrder];t.splice(e,1),i.__originalOrder=t}}r.removed.push(n)}const n=new Set(e.remove?.map(e=>e.id));if(e.update?.length)for(const{id:l,changes:a}of e.update){if(n.has(l))continue;const e=i._getRowEntry(l);if(!e)continue;const{row:t,index:o}=e;let s=!1;for(const[r,n]of Object.entries(a)){const e=t[r];e!==n&&(s=!0,t[r]=n,i.dispatchEvent(new CustomEvent("cell-change",{detail:{row:t,rowId:l,rowIndex:o,field:r,oldValue:e,newValue:n,changes:a,source:"api"},bubbles:!0,composed:!0})))}s&&r.updated.push(t)}if(e.add?.length)for(const l of e.add){i.sourceRows=[...i.sourceRows,l];const e=[...i._rows];e.push(l),i._rows=e,i._sortState&&(i.__originalOrder=[...i.__originalOrder,l]),r.added.push(l)}const o=r.added.length>0||r.removed.length>0,s=r.updated.length>0;if(o){he(i),i._rebuildRowIdMap(),i.__rowRenderEpoch++;for(const e of i._rowPool)e.__epoch=-1;i.refreshVirtualWindow(!0)}else s&&(he(i),i._requestSchedulerPhase(K.VIRTUALIZATION,"applyTransaction"));if((o||s)&&i._emitDataChange(),t&&r.added.length>0){await new Promise(e=>requestAnimationFrame(()=>e()));for(const e of r.added){const t=i._rows.indexOf(e);t>=0&&await Me(i,t,"insert")}}if(t&&r.updated.length>0)for(const l of r.updated){const e=i._rows.indexOf(l);e>=0&&await Me(i,e,"change")}return t&&r.removed.length>0&&requestAnimationFrame(()=>{i.querySelectorAll('[data-animating="remove"]').forEach(e=>{e.removeAttribute("data-animating")})}),r}#I=null;#P=[];#H=null;applyTransactionAsync(e){return this.#I||(this.#I={add:[],update:[],remove:[]}),e.add&&this.#I.add.push(...e.add),e.update&&this.#I.update.push(...e.update),e.remove&&this.#I.remove.push(...e.remove),new Promise(e=>{this.#P.push(e),null===this.#H&&(this.#H=requestAnimationFrame(()=>{this.#H=null;const e=this.#I,t=this.#P;this.#I=null,this.#P=[],this.applyTransaction(e,!1).then(e=>{for(const i of t)i(e)})}))})}}function He(e,t,i){const r=document.createElement(e);if(t)for(const n in t){const e=t[n];null!=e&&r.setAttribute(n,e)}return r}function De(e,t){const i=document.createElement("div");if(e&&(i.className=e),t)for(const r in t){const e=t[r];null!=e&&i.setAttribute(r,e)}return i}function Fe(e,t,i){const r=document.createElement("button");if(e&&(r.className=e),t)for(const n in t){const e=t[n];null!=e&&r.setAttribute(n,e)}return r}const ze=document.createElement("template");function qe(){return ze.content.cloneNode(!0)}function Oe(e){const t=document.createDocumentFragment(),i=De(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=De("tbw-grid-content");e.appendChild(qe()),i.appendChild(e)}return t.appendChild(i),t}function Ne(e){return e?"string"==typeof e?e:e.outerHTML:""}function Ge(e){return!!e?.header?.title||(!!e?.header?.toolbarContents?.length||(!!e?.toolPanels?.length||(!!e?.headerContents?.length||(!!e?.header?.lightDomContent?.length||!!e?.header?.hasToolButtonsContainer))))}function $e(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 r=i.querySelectorAll("tbw-grid-header-content");r.length>0&&0===t.lightDomHeaderContent.length&&(t.lightDomHeaderContent=Array.from(r)),i.style.display="none"}function We(e,t,i){const r=e.querySelector(":scope > tbw-grid-tool-buttons");if(!r)return;t.hasToolButtonsContainer=!0;const n="light-dom-toolbar-content";if(t.lightDomToolbarContentIds.has(n))return;const o={id:n,order:0,render:e=>{for(;r.firstChild;)e.appendChild(r.firstChild);return()=>{for(;e.firstChild;)r.appendChild(e.firstChild)}}};t.toolbarContents.set(n,o),t.lightDomToolbarContentIds.add(n),r.style.display="none"}function Be(e,t,i){e.querySelectorAll(":scope > tbw-grid-tool-panel").forEach(e=>{const r=e,n=r.getAttribute("id"),o=r.getAttribute("title");if(!n||!o)return void u("TBW070",`Tool panel missing required id or title attribute: id="${n??""}", title="${o??""}"`);const s=r.getAttribute("icon")??void 0,l=r.getAttribute("tooltip")??void 0,a=parseInt(r.getAttribute("order")??"100",10);let d;const c=i?.(r);if(c)d=c;else{const e=r.innerHTML.trim();d=t=>{const i=document.createElement("div");return i.innerHTML=e,t.appendChild(i),()=>i.remove()}}const h=t.toolPanels.get(n);if(h){if(c){h.render=d,h.order=a,h.icon=s,h.tooltip=l;const e=t.panelCleanups.get(n);e&&(e(),t.panelCleanups.delete(n))}return}const g={id:n,title:o,icon:s,tooltip:l,order:a,render:d};t.toolPanels.set(n,g),t.lightDomToolPanelIds.add(n),r.style.display="none"})}function Ve(e,t,i){const r=t?.header?.toolbarContents??[],n=[...i.toolbarContents.values()],o=new Set(r.map(e=>e.id)),s=[...r];for(const l of n)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 r=l.render(t);r&&i.toolbarContentCleanups.set(l.id,r)}}function Ke(e,t){const i=t.lightDomHeaderContent.length>0&&!t.lightDomContentMoved,r=t.headerContents.size>0;if(!i&&!r)return;const n=e.querySelector(".tbw-shell-content");if(!n)return;if(i){for(const e of t.lightDomHeaderContent)e.style.display="",n.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=n.querySelector(`[data-header-content="${s.id}"]`);i||(i=document.createElement("div"),i.setAttribute("data-header-content",s.id),n.appendChild(i));const r=s.render(i);r&&t.headerContentCleanups.set(s.id,r)}}function Ue(e,t,i){if(t.isPanelOpen)for(const[r,n]of t.toolPanels){const i=t.expandedSections.has(r),o=e.querySelector(`[data-section="${r}"]`),s=o?.querySelector(".tbw-accordion-content");if(!o||!s)continue;o.classList.toggle("expanded",i);const l=o.querySelector(".tbw-accordion-header");if(l&&l.setAttribute("aria-expanded",String(i)),i){if(0===s.children.length){const e=n.render(s);e&&t.panelCleanups.set(r,e)}}else{const e=t.panelCleanups.get(r);e&&(e(),t.panelCleanups.delete(r)),s.innerHTML=""}}}function je(e,t){const i=e.querySelector("[data-panel-toggle]");i&&(i.classList.toggle("active",t.isPanelOpen),i.setAttribute("aria-pressed",String(t.isPanelOpen)))}function Ye(e,t){const i=e.querySelector(".tbw-tool-panel");i&&(i.classList.toggle("open",t.isPanelOpen),t.isPanelOpen||(i.style.width=""))}function Xe(e){for(const t of e.toolbarContentCleanups.values())t();e.toolbarContentCleanups.clear();for(const t of e.panelCleanups.values())t();e.panelCleanups.clear();for(const t of e.headerContentCleanups.values())t();e.headerContentCleanups.clear(),e.lightDomContentMoved=!1}function Ze(e,t,i){const r=e.querySelector(`[data-section="${t}"]`);r&&r.classList.toggle("expanded",i)}function Qe(e,t,i,r){const n=Ge(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 o of l){e.querySelectorAll(`:scope > ${o}`).forEach(e=>s.push(e))}e.replaceChildren();for(const o of s)e.appendChild(o);if(n){const n=Ne(r?.toolPanel??o.toolPanel),s=Ne(r?.expand??o.expand);Ne(r?.collapse??o.collapse);const l=[...t?.header?.toolbarContents??[]].sort((e,t)=>(e.order??0)-(t.order??0)),a=[...t?.toolPanels??[]].sort((e,t)=>(e.order??100)-(t.order??100)),d={title:t?.header?.title??void 0,hasPanels:a.length>0,isPanelOpen:i.isPanelOpen,toolPanelIcon:n,configButtons:l.map(e=>({id:e.id,hasElement:!1,hasRender:!!e.render})),apiButtons:[]},c={position:t?.toolPanel?.position??"right",isPanelOpen:i.isPanelOpen,expandIcon:s,panels:a.map(e=>({id:e.id,title:e.title,icon:Ne(e.icon),isExpanded:i.expandedSections.has(e.id)}))},h=Oe({hasShell:!0,shellHeader:function(e){const t=De("tbw-shell-header",{part:"shell-header",role:"presentation"});if(e.title){const i=De("tbw-shell-title");i.textContent=e.title,t.appendChild(i)}const i=De("tbw-shell-content",{part:"shell-content",role:"presentation","data-light-dom-header-content":""});t.appendChild(i);const r=De("tbw-shell-toolbar",{part:"shell-toolbar",role:"presentation"});for(const n of e.configButtons)n.hasRender&&r.appendChild(De("tbw-toolbar-content-slot",{"data-toolbar-content":n.id}));for(const n of e.apiButtons)n.hasRender&&r.appendChild(De("tbw-toolbar-content-slot",{"data-toolbar-content":n.id}));if((e.configButtons.some(e=>e.hasRender)||e.apiButtons.some(e=>e.hasRender))&&e.hasPanels&&r.appendChild(De("tbw-toolbar-separator")),e.hasPanels){const t=Fe(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,r.appendChild(t)}return t.appendChild(r),t}(d),shellBody:function(e){const t=De("tbw-shell-body"),i=e.panels.length>0,r=1===e.panels.length,n=De("tbw-grid-content");n.appendChild(qe());let o=null;if(i){o=He("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(De("tbw-tool-panel-resize",{"data-resize-handle":"","data-handle-position":t,"aria-hidden":"true"}));const i=De("tbw-tool-panel-content",{role:"presentation"}),n=De("tbw-accordion");for(const o of e.panels){const t=De(`tbw-accordion-section${o.isExpanded?" expanded":""}${r?" single":""}`,{"data-section":o.id}),i=Fe("tbw-accordion-header",{"aria-expanded":String(o.isExpanded),"aria-controls":`tbw-section-${o.id}`});if(r&&i.setAttribute("aria-disabled","true"),o.icon){const e=He("span",{class:"tbw-accordion-icon"});e.innerHTML=o.icon,i.appendChild(e)}const s=He("span",{class:"tbw-accordion-title"});if(s.textContent=o.title,i.appendChild(s),!r){const t=He("span",{class:"tbw-accordion-chevron"});t.innerHTML=e.expandIcon,i.appendChild(t)}t.appendChild(i),t.appendChild(De("tbw-accordion-content",{id:`tbw-section-${o.id}`,role:"presentation"})),n.appendChild(t)}i.appendChild(n),o.appendChild(i)}return"left"===e.position&&o?(t.appendChild(o),t.appendChild(n)):(t.appendChild(n),o&&t.appendChild(o)),t}(c)});e.appendChild(h)}else{const t=Oe({hasShell:!1});e.appendChild(t)}return n}ze.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 <div class="tbw-sr-only" aria-live="polite" aria-atomic="true"></div>\n';const Je="tbw-grid-styles";let et="";const tt=new Map;function it(){const e=function(){let e=document.getElementById(Je);return e||(e=document.createElement("style"),e.id=Je,e.setAttribute("data-tbw-grid","true"),document.head.appendChild(e)),e}(),t=Array.from(tt.values()).join("\n");e.textContent=`${et}\n\n/* Plugin Styles */\n${t}`}async function rt(e){if(et)return;if("string"==typeof e&&e.length>0)return et=e,void it();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){u("TBW120",`Failed to extract grid.css from document stylesheets: ${e}`)}return null}();t?(et=t,it()):"undefined"!=typeof process&&"test"===process.env?.NODE_ENV||u("TBW121",`Could not find grid.css in document.styleSheets. Grid styling will not work. Available stylesheets: ${Array.from(document.styleSheets).map(e=>e.href||"(inline)").join(", ")}`)}function nt(e){e.startY=null,e.startX=null,e.lastY=null,e.lastX=null,e.lastTime=null,e.locked=!1}function ot(e){e.momentumRaf&&(cancelAnimationFrame(e.momentumRaf),e.momentumRaf=0)}function st(e,t){(Math.abs(e.velocityY)>.1||Math.abs(e.velocityX)>.1)&&function(e,t){const i=.95,r=.01,n=()=>{e.velocityY*=i,e.velocityX*=i;const o=16*e.velocityY,s=16*e.velocityX;Math.abs(e.velocityY)>r&&(t.fauxScrollbar.scrollTop+=o),Math.abs(e.velocityX)>r&&t.scrollArea&&(t.scrollArea.scrollLeft+=s),Math.abs(e.velocityY)>r||Math.abs(e.velocityX)>r?e.momentumRaf=requestAnimationFrame(n):e.momentumRaf=0};e.momentumRaf=requestAnimationFrame(n)}(e,t),nt(e)}function lt(e,t,i,r){e.addEventListener("pointerdown",i=>{"touch"===i.pointerType&&null===t.activePointerId&&(t.activePointerId=i.pointerId,e.setPointerCapture(i.pointerId),function(e,t,i){ot(i),i.startY=t,i.startX=e,i.lastY=t,i.lastX=e,i.lastTime=performance.now(),i.velocityY=0,i.velocityX=0,i.locked=!1}(i.clientX,i.clientY,t))},{passive:!0,signal:r}),e.addEventListener("pointermove",e=>{if(e.pointerId!==t.activePointerId)return;const r=function(e,t,i,r){if(null===i.lastY||null===i.lastX)return!1;const n=performance.now(),o=i.lastY-t,s=i.lastX-e;if(null!==i.lastTime){const e=n-i.lastTime;e>0&&(i.velocityY=o/e,i.velocityX=s/e)}if(i.lastY=t,i.lastX=e,i.lastTime=n,i.locked)return r.fauxScrollbar.scrollTop+=o,r.scrollArea&&(r.scrollArea.scrollLeft+=s),!0;const l=null!==i.startY?Math.abs(i.startY-t):0,a=null!==i.startX?Math.abs(i.startX-e):0;if(l<3&&a<3)return!1;const d=l>=a,{scrollHeight:c,clientHeight:h}=r.fauxScrollbar,u=c-h>0;let g=!1;if(r.scrollArea){const{scrollWidth:e,clientWidth:t}=r.scrollArea;g=e-t>0}return!!(d&&u||!d&&g)&&(i.locked=!0,r.fauxScrollbar.scrollTop+=o,r.scrollArea&&(r.scrollArea.scrollLeft+=s),!0)}(e.clientX,e.clientY,t,i);r&&e.preventDefault()},{passive:!1,signal:r}),e.addEventListener("pointerup",e=>{e.pointerId===t.activePointerId&&(t.activePointerId=null,st(t,i))},{passive:!0,signal:r}),e.addEventListener("pointercancel",e=>{e.pointerId===t.activePointerId&&(t.activePointerId=null,nt(t))},{passive:!0,signal:r}),e.addEventListener("lostpointercapture",e=>{e.pointerId===t.activePointerId&&(t.activePointerId=null,nt(t))},{passive:!0,signal:r})}const at=[{property:"editable",pluginName:"editing",level:"column",description:'the "editable" column property',isUsed:e=>!0===e||"function"==typeof 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}],dt=[{property:"rowEditable",pluginName:"editing",level:"config",description:'the "rowEditable" config property',isUsed:e=>"function"==typeof e},{property:"columnGroups",pluginName:"groupingColumns",level:"config",description:'the "columnGroups" config property',isUsed:e=>Array.isArray(e)&&e.length>0}];function ct(e){return`import { ${ht(e)}Plugin } from '@toolbox-web/grid/plugins/${t=e,t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}';`;var t}function ht(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ut(e,t){return e.some(e=>e.name===t)}function gt(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 pt(e,t,i){const r=gt(t,i);return"string"==typeof r?e.byKey.get(r):r&&"object"==typeof r?e.byRef.get(r):void 0}function ft(e,t,i){if(t<0||t>=e.length)return;const r=e[t],n=i-r.height;if(0!==n){r.height=i,r.measured=!0;for(let i=t+1;i<e.length;i++)e[i].offset+=n}}function wt(e,t){if(0===e.length)return-1;if(t<=0)return 0;let i=0,r=e.length-1;for(;i<=r;){const n=Math.floor((i+r)/2),o=e[n],s=o.offset+o.height;if(t<o.offset)r=n-1;else{if(!(t>=s))return n;i=n+1}}return Math.max(0,Math.min(i,e.length-1))}function mt(e,t){const{positionCache:i,heightCache:r,rows:n,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>=n.length)return;const h=n[c],u=l?.(h,c);if(void 0!==u){const e=i[c];return void((!e.measured||Math.abs(e.height-u)>1)&&(ft(i,c,u),d=!0))}const g=e.offsetHeight;if(g>0){const e=i[c];(!e.measured||Math.abs(e.height-g)>1)&&(ft(i,c,g),function(e,t,i,r){const n=gt(t,r);"string"==typeof n?e.byKey.set(n,i):n&&"object"==typeof n&&e.byRef.set(n,i)}(r,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,r=0;for(const n of e)n.measured&&(i+=n.height,r++);return r>0?i/r:t}(i,e.defaultHeight):0;return{hasChanges:d,measuredCount:c,averageHeight:h}}class bt{#e;state;constructor(e,t){this.#e=e,this.state={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,...t}}updateCachedGeometry(){const e=this.state,t=e.container,i=e.viewportEl??t;i&&(e.cachedViewportHeight=i.clientHeight),t&&(e.cachedFauxHeight=t.clientHeight);const r=e.scrollAreaEl;r&&(e.cachedScrollAreaHeight=r.clientHeight)}calculateTotalSpacerHeight(e,t=!1){const i=this.state;let r,n,o;if(t){const e=i.container??this.#e._hostElement,t=i.viewportEl??e,s=i.scrollAreaEl;r=e?.clientHeight??0,n=t?.clientHeight??0,o=s?s.clientHeight:r,i.cachedFauxHeight=r,i.cachedViewportHeight=n,i.cachedScrollAreaHeight=o}else r=i.cachedFauxHeight,n=i.cachedViewportHeight,o=i.cachedScrollAreaHeight||r;const s=o-n,l=Math.max(0,r-o);let a,d=0;return 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.#e._getPluginExtraHeight()),a+s+d+l}initializePositionCache(){const e=this.state;if(!e.variableHeights)return;const t=this.#e,i=t._rows,r=e.rowHeight||28,n=t.effectiveConfig?.rowHeight,o=t.effectiveConfig?.getRowId,s=o?e=>o(e):void 0;e.positionCache=function(e,t,i,r,n){const o=new Array(e.length);let s=0;for(let l=0;l<e.length;l++){const a=e[l];let d=n?.(a,l),c=void 0!==d;void 0===d&&(d=pt(t,a,r.rowId),c=void 0!==d),void 0===d&&(d=i,c=!1),o[l]={offset:s,height:d,measured:c},s+=d}return o}(i,e.heightCache,r,{rowId:s},(e,i)=>{const r=t._getPluginRowHeight(e,i);if(void 0!==r)return r;if(n){const t=n(e,i);if(void 0!==t&&t>0)return t}});const l=function(e,t,i,r){let n=0,o=0;for(let s=0;s<e.length;s++){const i=e[s];if(i.measured){const e=r?.(t[s],s);void 0===e&&(o+=i.height,n++)}}return{measuredCount:n,averageHeight:n>0?o/n:i}}(e.positionCache,i,r,(e,i)=>t._getPluginRowHeight(e,i));e.measuredCount=l.measuredCount,l.measuredCount>0&&(e.averageHeight=l.averageHeight)}invalidateRowHeight(e,t){const i=this.state;if(!i.variableHeights)return;if(!i.positionCache)return;const r=this.#e._rows;if(e<0||e>=r.length)return;const n=r[e];let o=t;void 0===o&&(o=this.#e._getPluginRowHeight(n,e)),void 0===o&&(o=i.rowHeight);const s=i.positionCache[e];if(s&&!(Math.abs(s.height-o)<1)&&(ft(i.positionCache,e,o),i.totalHeightEl)){const e=this.calculateTotalSpacerHeight(r.length);i.totalHeightEl.style.height=`${e}px`}}measureRenderedRowHeights(e,t){const i=this.state;if(!i.variableHeights)return;if(!i.positionCache)return;const r=this.#e,n=r._bodyEl;if(!n)return;const o=n.querySelectorAll(".data-grid-row"),s=r.effectiveConfig?.getRowId,l=r._rows,a=mt({positionCache:i.positionCache,heightCache:i.heightCache,rows:l,defaultHeight:i.rowHeight,start:e,end:t,getPluginHeight:(e,t)=>r._getPluginRowHeight(e,t),getRowId:s?e=>s(e):void 0},o);if(a.hasChanges&&(i.measuredCount=a.measuredCount,i.averageHeight=a.averageHeight,i.totalHeightEl)){const e=this.calculateTotalSpacerHeight(l.length);i.totalHeightEl.style.height=`${e}px`}}refreshVirtualWindow(e=!1,t=!1){const i=this.state,r=this.#e,n=r._bodyEl;if(!n)return!1;const o=r._rows.length;if(!i.enabled)return r._renderVisibleRows(0,o),t||r._afterPluginRender(),!0;if(o<=i.bypassThreshold)return i.start=0,i.end=o,e&&(n.style.transform="translateY(0px)"),r._renderVisibleRows(0,o,r.__rowRenderEpoch),e&&i.variableHeights&&this.initializePositionCache(),e&&i.totalHeightEl&&(i.totalHeightEl.style.height=`${this.calculateTotalSpacerHeight(o,!0)}px`),r._updateAriaCounts(o,r._visibleColumns.length),t||r._afterPluginRender(),!0;const s=i.container,l=i.viewportEl??s,a=e?i.cachedViewportHeight=l.clientHeight:i.cachedViewportHeight||(i.cachedViewportHeight=l.clientHeight),d=i.rowHeight,c=s.scrollTop;let h;e&&i.variableHeights&&this.initializePositionCache();const u=i.positionCache;if(i.variableHeights&&u&&u.length>0)h=wt(u,c),-1===h&&(h=0);else{h=Math.floor(c/d);let e=0;const t=10;for(;e<t;){const t=r._getPluginExtraHeightBefore(h),i=Math.floor((c-t)/d);if(i>=h||i<0)break;h=i,e++}}h-=h%2,h<0&&(h=0);const g=r._adjustPluginVirtualStart(h,c,d);let p;if(void 0!==g&&g<h&&(h=g,h-=h%2,h<0&&(h=0)),i.variableHeights&&u&&u.length>0){const e=a+3*d;let t=0;for(p=h;p<o&&t<e;)t+=u[p].height,p++;const i=Math.ceil(a/d)+3;p-h<i&&(p=Math.min(h+i,o))}else{p=h+(Math.ceil(a/d)+3)}p>o&&(p=o);const f=i.start,w=i.end;if(!e&&h===f&&p===w)return!1;i.start=h,i.end=p;const m=e?i.cachedFauxHeight=s.clientHeight:i.cachedFauxHeight||(i.cachedFauxHeight=s.clientHeight);if(e){const e=i.scrollAreaEl;e&&(i.cachedScrollAreaHeight=e.clientHeight)}if(0===m&&a>0)return r._requestSchedulerPhase(K.VIRTUALIZATION,"stale-refs-retry"),!1;if(e&&i.totalHeightEl){const e=this.calculateTotalSpacerHeight(o);i.totalHeightEl.style.height=`${e}px`}let b;if(i.variableHeights&&u&&u[h])b=u[h].offset;else{b=h*d+r._getPluginExtraHeightBefore(h)}const v=-(c-b);return n.style.transform=`translateY(${v}px)`,r._renderVisibleRows(h,p,r.__rowRenderEpoch),e&&i.variableHeights&&this.measureRenderedRowHeights(h,p),r._updateAriaCounts(o,r._visibleColumns.length),e&&!t&&(r._afterPluginRender(),queueMicrotask(()=>{if(!i.totalHeightEl)return;const e=this.calculateTotalSpacerHeight(o);0===i.cachedFauxHeight&&i.cachedViewportHeight>0||(i.totalHeightEl.style.height=`${e}px`)})),!0}}class vt{constructor(e){this.grid=e}plugins=[];getPlugins(){return this.plugins}pluginMap=new Map;cellRenderers=new Map;headerRenderers=new Map;cellEditors=new Map;_hasAfterCellRender=!1;_hasAfterRowRender=!1;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,i){const r=e.name,n=e.constructor.dependencies??[];for(const o of n){const e=o.name,n=o.required??!0,s=o.reason;if(!t.some(t=>t.name===e)){const t=s??`${ht(r)}Plugin requires ${ht(e)}Plugin`,o=ct(e);n?h("TBW020",`Plugin dependency error:\n\n${t}.\n\n → Add the plugin to your gridConfig.plugins array BEFORE ${ht(r)}Plugin:\n ${o}\n plugins: [new ${ht(e)}Plugin(), new ${ht(r)}Plugin()]`,i):g("TBW021",`${ht(r)}Plugin: Optional "${e}" plugin not found. Some features may be unavailable.`,i)}}}(e,this.plugins,this.grid.getAttribute("id")??void 0),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),this.#D();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(vt.deprecationWarned.has(t))return;if(!Y())return;const i="function"==typeof e.getExtraHeight||"function"==typeof e.getExtraHeightBefore,r="function"==typeof e.getRowHeight;i&&!r&&(vt.deprecationWarned.add(t),u("TBW023",`"${e.name}" uses getExtraHeight() / getExtraHeightBefore() which are deprecated and will be removed in v2.0.\n → Migrate to getRowHeight(row, index) for better variable row height support.`,this.grid.getAttribute("id")??void 0))}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(),this._hasAfterCellRender=!1,this._hasAfterRowRender=!1}getPlugin(e){return this.pluginMap.get(e)}getPluginByName(e){return this.plugins.find(t=>t.name===e||t.aliases?.includes(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._hasAfterCellRender}afterRowRender(e){for(const t of this.plugins)t.afterRowRender?.(e)}hasAfterRowRenderHook(){return this._hasAfterRowRender}#D(){this._hasAfterCellRender=this.plugins.some(e=>"function"==typeof e.afterCellRender),this._hasAfterRowRender=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 r=i.getRowHeight(e,t);if(void 0!==r)return r}}hasRowHeightPlugin(){for(const e of this.plugins)if("function"==typeof e.getRowHeight)return!0;return!1}adjustVirtualStart(e,t,i){let r=e;for(const n of this.plugins)if("function"==typeof n.adjustVirtualStart){const o=n.adjustVirtualStart(e,t,i);o<r&&(r=o)}return r}renderRow(e,t,i){for(const r of this.plugins)if(r.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 r of i){const i=r.handleQuery?.(e)??r.onPluginQuery?.(e);void 0!==i&&t.push(i)}return t}for(const r of this.plugins){const i=r.handleQuery?.(e)??r.onPluginQuery?.(e);void 0!==i&&t.push(i)}return t}subscribe(e,t,i){let r=this.eventListeners.get(t);r||(r=new Map,this.eventListeners.set(t,r)),r.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 n of i.values())try{n(t)}catch(r){p("TBW024",`Error in plugin event handler for "${e}": ${r}`,this.grid.getAttribute("id")??void 0)}}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,r=0,n=!1;for(const o of this.plugins){const s=o.getHorizontalScrollOffsets?.(e,t);s&&(i+=s.left,r+=s.right,s.skipScroll&&(n=!0))}return{left:i,right:r,skipScroll:n}}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 yt extends HTMLElement{static tagName="tbw-grid";static version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";static#F=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#z(){return this}#q=!1;#r;#n;#O=[];get#f(){return this.#N?.effective??{}}#G=!1;#$=!1;#W={rows:!1,columns:!1,gridConfig:!1,fitMode:!1};#B;#V=0;#K=null;#U=!1;#j=!1;#Y=0;#X;#Z={startY:null,startX:null,lastY:null,lastX:null,lastTime:null,velocityY:0,velocityX:0,momentumRaf:0,locked:!1,activePointerId:null};#Q;#J;#ee;#te;#ie={scrollTop:0,scrollLeft:0,scrollHeight:0,scrollWidth:0,clientHeight:0,clientWidth:0};#re;#ne;#oe;#se;#le;#ae;get _pluginManager(){return this.#re}#de=!1;#ce;#he;#C;#N;#ue=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,apiHeaderContentIds:new Set,isPanelOpen:!1,expandedSections:new Set,headerContentCleanups:new Map,panelCleanups:new Map,toolbarContentCleanups:new Map,lightDomContentMoved:!1}}();#ge;#pe;#fe;#we=!1;#me=new Set;#be=new Map;#ve;#ye=new Map;_rows=[];#Ce=[];get _columns(){return this.#f.columns??[]}set _columns(e){this.#f.columns=e,this.#xe=void 0}#xe;get _visibleColumns(){return this.#xe??=this._columns.filter(e=>!e.hidden)}_headerRowEl;_bodyEl;_rowPool=[];_resizeController;get _virtualization(){return this.#se.state}set _virtualization(e){Object.assign(this.#se.state,e)}_focusRow=0;_focusCol=0;_restoreFocusAfterRender=!1;_sortState=null;_gridTemplate="";__rowRenderEpoch=0;__didInitialAutoSize=!1;get __lightDomColumnsCache(){return this.#N?.lightDomColumnsCache}set __lightDomColumnsCache(e){this.#N&&(this.#N.lightDomColumnsCache=e)}get __originalColumnNodes(){return this.#N?.originalColumnNodes}set __originalColumnNodes(e){this.#N&&(this.#N.originalColumnNodes=e)}__originalOrder=[];__frameworkAdapter;__rowsBodyEl=null;get rows(){return this._rows}set rows(e){const t=this.#O;this.#O=e,t!==e&&this.#Re("rows")}get sourceRows(){return this.#O}set sourceRows(e){this.#O=e}get columns(){return[...this._columns]}set columns(e){const t=this.#N?.getColumns();this.#N?.setColumns(e),t!==e&&this.#Re("columns")}get gridConfig(){return this.#f}set gridConfig(e){e&&this.__frameworkAdapter?.processConfig&&(e=this.__frameworkAdapter.processConfig(e));const t=this.#N?.getGridConfig();this.#N?.setGridConfig(e),t!==e&&(this.#N.clearLightDomCache(),this.#Re("gridConfig"))}get fitMode(){return this.#f.fitMode??"stretch"}set fitMode(e){const t=this.#N?.getFitMode();this.#N?.setFitMode(e),t!==e&&this.#Re("fitMode")}get loading(){return this.#we}set loading(e){const t=this.#we;this.#we=e,e?this.setAttribute("loading",""):this.removeAttribute("loading"),t!==e&&this.#Ee()}setRowLoading(e,t){const i=this.#me.has(e);t?this.#me.add(e):this.#me.delete(e),i!==t&&this.#Se(e,t)}setCellLoading(e,t,i){let r=this.#be.get(e);const n=r?.has(t)??!1;i?(r||(r=new Set,this.#be.set(e,r)),r.add(t)):(r?.delete(t),0===r?.size&&this.#be.delete(e)),n!==i&&this.#_e(e,t,i)}isRowLoading(e){return this.#me.has(e)}isCellLoading(e,t){return this.#be.get(e)?.has(t)??!1}clearAllLoading(){this.loading=!1;for(const e of this.#me)this.#Se(e,!1);this.#me.clear();for(const[e,t]of this.#be)for(const i of t)this.#_e(e,i,!1);this.#be.clear()}get effectiveConfig(){return this.#f}get disconnectSignal(){return this.#Q||(this.#Q=new AbortController),this.#Q.signal}constructor(){super(),this.#Ae(),this.#r=new Promise(e=>this.#n=e),this.#se=new bt(this),this.#le=new Ce(this),this.#ae=new Pe(this),this.#B=new U(this),this.#B.setInitialReadyResolver(()=>this.#n?.()),this.#ge=function(e,t){let i=!1;const r={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 u("TBW071","No tool panels registered",t.id);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._renderRoot;je(i,e),Ye(i,e),Ue(i,e,t._accordionIcons),t._emit("tool-panel-open",{sections:r.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._renderRoot;je(i,e),Ye(i,e),t._emit("tool-panel-close",{})},toggleToolPanel(){e.isPanelOpen?r.closeToolPanel():r.openToolPanel()},toggleToolPanelSection(i){const r=e.toolPanels.get(i);if(!r)return void u("TBW072",`Tool panel section "${i}" not found`,t.id);if(1===e.toolPanels.size)return;const n=t._renderRoot,o=e.expandedSections.has(i);if(o){const t=e.panelCleanups.get(i);t&&(t(),e.panelCleanups.delete(i)),r.onClose?.(),e.expandedSections.delete(i),Ze(n,i,!1)}else{for(const[t,r]of e.toolPanels)if(t!==i&&e.expandedSections.has(t)){const i=e.panelCleanups.get(t);i&&(i(),e.panelCleanups.delete(t)),r.onClose?.(),e.expandedSections.delete(t),Ze(n,t,!1);const o=n.querySelector(`[data-section="${t}"] .tbw-accordion-content`);o&&(o.innerHTML="")}e.expandedSections.add(i),Ze(n,i,!0),function(e,t,i){const r=t.toolPanels.get(i);if(!r?.render)return;const n=e.querySelector(`[data-section="${i}"] .tbw-accordion-content`);if(!n)return;const o=r.render(n);o&&t.panelCleanups.set(i,o)}(n,e,i)}t._emit("tool-panel-section-toggle",{id:i,expanded:!o})},getToolPanels:()=>[...e.toolPanels.values()],registerToolPanel(r){e.toolPanels.has(r.id)?u("TBW073",`Tool panel "${r.id}" already registered`,t.id):(e.toolPanels.set(r.id,r),i&&t.refreshShellHeader?.())},unregisterToolPanel(r){if(e.expandedSections.has(r)){const t=e.panelCleanups.get(r);t&&(t(),e.panelCleanups.delete(r)),e.expandedSections.delete(r)}e.toolPanels.delete(r),i&&t.refreshShellHeader?.()},getHeaderContents:()=>[...e.headerContents.values()],registerHeaderContent(r){e.headerContents.has(r.id)?u("TBW074",`Header content "${r.id}" already registered`,t.id):(e.headerContents.set(r.id,r),i&&Ke(t._renderRoot,e))},unregisterHeaderContent(i){const r=e.headerContentCleanups.get(i);r&&(r(),e.headerContentCleanups.delete(i));const n=e.headerContents.get(i);n?.onDestroy?.(),e.headerContents.delete(i);const o=t._renderRoot.querySelector(`[data-header-content="${i}"]`);o?.remove()},getToolbarContents:()=>[...e.toolbarContents.values()].sort((e,t)=>(e.order??0)-(t.order??0)),registerToolbarContent(r){e.toolbarContents.has(r.id)?u("TBW075",`Toolbar content "${r.id}" already registered`,t.id):(e.toolbarContents.set(r.id,r),i&&t.refreshShellHeader?.())},unregisterToolbarContent(r){const n=e.toolbarContentCleanups.get(r);n&&(n(),e.toolbarContentCleanups.delete(r));const o=e.toolbarContents.get(r);o?.onDestroy&&o.onDestroy(),e.toolbarContents.delete(r),i&&t.refreshShellHeader?.()}};return r}(this.#ue,this),this.#N=new j(this)}async#Ae(){await rt('@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: 2px;--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;touch-action:none}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);touch-action:none}tbw-grid .faux-vscroll-spacer{width:1px}tbw-grid .tbw-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}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-hit-area, 18px) / 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 .header-group-row>.header-group-cell.sticky-left,tbw-grid .header-group-row>.header-group-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-hit-area, 18px) / -2);width:var(--tbw-resize-hit-area, 18px);height:100%;cursor:e-resize;-webkit-user-select:none;user-select:none;touch-action:none;z-index:20;background:transparent}tbw-grid .resize-handle:before{content:"";position:absolute;top:0;left:50%;transform:translate(-50%);width:var(--tbw-resize-handle-width);height:100%;background:var(--tbw-resize-handle-color);border-radius:var(--tbw-resize-handle-border-radius);transition:background .12s ease}tbw-grid .resize-handle:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);width:var(--tbw-resize-handle-width);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:before{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;touch-action:none}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:var(--tbw-z-layer-toolpanel, 31);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.#re?.getPlugin(e)}getPluginByName(e){return this.#re?.getPluginByName(e)}requestRender(){this.#B.requestPhase(K.ROWS,"plugin:requestRender")}requestColumnsRender(){this.#B.requestPhase(K.COLUMNS,"plugin:requestColumnsRender")}requestRenderWithFocus(){this._restoreFocusAfterRender=!0,this.#B.requestPhase(K.ROWS,"plugin:requestRenderWithFocus")}updateTemplate(){y(this)}requestAfterRender(){this.#B.requestPhase(K.STYLE,"plugin:requestAfterRender")}requestVirtualRefresh(){this._virtualization.start=-1,this.refreshVirtualWindow(!1)}#ke(){this.#re=new vt(this);const e=this.#f?.plugins,t=Array.isArray(e)?e:[],i=this.#f?.features;let r=[];i&&ye&&(r=ye(i));const n=r.length>0?[...r,...t]:t;this.#re.attachAll(n)}#Te(){!function(e){let t=!1;for(const{name:i,styles:r}of e)tt.has(i)||(tt.set(i,r),t=!0);t&&it()}(this.#re?.getPluginStyles()??[])}#Me(){const e=this.#f?.plugins,t=Array.isArray(e)?e:[],i=this.#f?.features??void 0,r=i!==this.#oe;if((this.#ne===t||void 0!==this.#ne&&this.#ne.length===t.length&&this.#ne.every((e,i)=>e===t[i]))&&!r)return void(this.#ne=t);this.#re&&this.#re.detachAll();for(const o of this.#ue.toolPanels.keys()){const e=this.#ue.lightDomToolPanelIds.has(o),t=this.#ue.apiToolPanelIds.has(o);if(!e&&!t){const e=this.#ue.panelCleanups.get(o);e&&(e(),this.#ue.panelCleanups.delete(o)),this.#ue.toolPanels.delete(o)}}for(const o of this.#ue.headerContents.keys()){if(this.#ue.apiHeaderContentIds.has(o))continue;const e=this.#ue.headerContentCleanups.get(o);e&&(e(),this.#ue.headerContentCleanups.delete(o)),this.#ue.headerContents.delete(o)}this.#ke(),this.#Te(),this.#ne=t,this.#oe=i,this.#Le(),this.#Ie();const n=this.#U;if(this.#U=this.#re?.getAll().some(e=>e.onScroll)??!1,!n&&this.#U){const e=this.#z.querySelector(".tbw-grid-content")??this.#z.querySelector(".tbw-grid-root");this.#Pe(e)}}#He(){this.#re?.detachAll()}#Ie(){if(!this.#re)return;const e=this.#re.getToolPanels();for(const{panel:i}of e)this.#ue.toolPanels.has(i.id)||this.#ue.toolPanels.set(i.id,i);const t=this.#re.getHeaderContents();for(const{content:i}of t)this.#ue.headerContents.has(i.id)||this.#ue.headerContents.set(i.id,i)}#De(){const e=yt.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",yt.version),this.id||(this.id="tbw-grid-"+ ++yt.#F),this._rows=Array.isArray(this.#O)?[...this.#O]:[],this.#Q&&(this.#Q.abort(),this.#de=!1),this.#Q=new AbortController,this.#te&&(Re(this.#te),this.#te=void 0),this.#Fe(),this.#N.parseLightDomColumns(this),this.#N.merge(),this.#ke();const e=this.#f?.plugins;var t,i;this.#ne=Array.isArray(e)?e:[],this.#oe=this.#f?.features??void 0,this.#Ie(),this.#q||(this.#ze(),this.#Te(),this.#q=!0),this.#qe(),this.#te=(t=()=>{this.#Oe()},i={timeout:100},xe?requestIdleCallback(t,i):window.setTimeout(()=>{const e=Date.now();t({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-e))})},1))}disconnectedCallback(){this.#te&&(Re(this.#te),this.#te=void 0),this.#Y&&(clearTimeout(this.#Y),this.#Y=0),this.#He(),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.#ue),this.#ge.setInitialized(!1),this.#pe?.(),this.#pe=void 0,this.#fe?.(),this.#fe=void 0,ot(this.#Z),this.#Q&&(this.#Q.abort(),this.#Q=void 0),this.#ce?.abort(),this.#ce=void 0,this.#de=!1,this._resizeController&&this._resizeController.dispose(),this.#J&&(this.#J.disconnect(),this.#J=void 0),this.#ee&&(this.#ee.disconnect(),this.#ee=void 0,this.#Ne=!1),he(this),this.#Ge.clear(),this._virtualization.heightCache?.byKey.clear(),this.#ne=void 0,this.#oe=void 0;for(const e of this._rowPool)e.remove();this._rowPool.length=0,this.__rowsBodyEl=null,this.#G=!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{u("TBW130",`Invalid JSON for '${e}' attribute: ${i}`,this.id)}else"fit-mode"===e&&(this.fitMode=i)}#qe(){const e=this.#z.querySelector(".tbw-grid-content")??this.#z.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.#ge.isInitialized){Ke(this.#z,this.#ue),Ve(this.#z,this.#f?.shell,this.#ue);const e=this.#f?.shell?.toolPanel?.defaultOpen;e&&this.#ue.toolPanels.has(e)&&(this.openToolPanel(),this.#ue.expandedSections.add(e)),this.#ue.isPanelOpen&&(Ye(this.#z,this.#ue),Ue(this.#z,this.#ue,(this.#f,this.#f)),je(this.#z,this.#ue))}if(this.setAttribute("data-upgraded",""),this.#G=!0,this._resizeController=Se(this),this.#$e(),this.#Pe(e),this.#de)return;this.#de=!0;const t=this.disconnectSignal;ve(this,this,this.#z,t),this.#Le(),queueMicrotask(()=>this.#We()),this.#B.requestPhase(K.FULL,"afterConnect")}#Le(){const e=this.#f.rowHeight,t=this.#re.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.#se.initializePositionCache(),"function"!=typeof e&&(this.#j=!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.#Be())}#Be(){if(this.#re.hasExtraHeight())return;const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;if(e.style.getPropertyValue("--tbw-row-height"))return;const t=this.#Ve(),i=e.querySelectorAll(".cell");let r=0;i.forEach(e=>{const t=e.offsetHeight;t>r&&(r=t)});const n=e.getBoundingClientRect(),o=Math.max(n.height,r),s=this._virtualization.rowHeight,l=t>0&&Math.abs(t-s)>1;(l||o>0&&o-s>1)&&(this._virtualization.rowHeight=l?Math.max(t,o):o,this.#B.requestPhase(K.VIRTUALIZATION,"measureRowHeight"))}#Ve(){const e=getComputedStyle(this).getPropertyValue("--tbw-row-height").trim();if(!e)return 0;if(e.endsWith("px"))return parseFloat(e)||0;const t=this._bodyEl?.querySelector('.data-grid-row:not([style*="--tbw-row-height"]) > .cell');if(!t)return 0;const i=parseFloat(getComputedStyle(t).minHeight);return i>0?i:0}#Ke(){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 r=e.getBoundingClientRect(),n=Math.max(r.height,i);if(n>0){if(Math.abs(n-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=n),this.#se.initializePositionCache(),this._virtualization.totalHeightEl){const e=this.#se.calculateTotalSpacerHeight(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}}#Pe(e){this.#ce?.abort(),this.#ce=new AbortController;const t=this.#ce.signal,i=e?.querySelector(".faux-vscroll"),r=e?.querySelector(".rows");if(this._virtualization.container=i??this,this.#U=this.#re?.getAll().some(e=>e.onScroll)??!1,i&&r){i.addEventListener("scroll",()=>{if(!this._virtualization.enabled&&!this.#U)return;const e=i.scrollTop,t=this._virtualization.rowHeight;if(this._rows.length<=this._virtualization.bypassThreshold)r.style.transform=`translateY(${-e}px)`;else{const i=this._virtualization.positionCache;let n,o;if(this._virtualization.variableHeights&&i&&i.length>0){n=wt(i,e),-1===n&&(n=0);const r=n-n%2;o=i[r]?.offset??r*t}else{n=Math.floor(e/t);o=(n-n%2)*t}const s=-(e-o);r.style.transform=`translateY(${s}px)`}this.#K=e,this.#V||(this.#V=requestAnimationFrame(()=>{this.#V=0,null!==this.#K&&(this.#Ue(this.#K),this.#K=null)}))},{passive:!0,signal:t});const e=this.#z.querySelector(".tbw-scroll-area");this.#he=e,this._virtualization.scrollAreaEl=e,e&&this.#U&&e.addEventListener("scroll",()=>{const t=this.#ie;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.#re?.onScroll(t)},{passive:!0,signal:t});const n=this.#z.querySelector(".tbw-grid-content"),o=this.#he;n&&(n.addEventListener("wheel",e=>{try{if(n.querySelector("select:open"))return}catch{}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:r,clientWidth:n}=o;(t>0&&i<r-n||t<0&&i>0)&&(e.preventDefault(),o.scrollLeft+=t)}else if(!t){const{scrollTop:t,scrollHeight:r,clientHeight:n}=i;(e.deltaY>0&&t<r-n||e.deltaY<0&&t>0)&&(e.preventDefault(),i.scrollTop+=e.deltaY)}},{passive:!1,signal:t}),lt(n,this.#Z,{fauxScrollbar:i,scrollArea:o},t))}var n,o,s;this._bodyEl&&(n=this,o=this._bodyEl,s=t,o.addEventListener("mousedown",e=>{const t=e.target.closest(".cell[data-col]");if(!t)return;if(t.classList.contains("editing"))return;const i=e.target;i.draggable||i.closest('[draggable="true"]')||e.preventDefault(),me(n,t)},{signal:s}),o.addEventListener("click",e=>{const t=e.target.closest(".data-grid-row");if(t&&pe(n,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&&pe(n,e,t)},{signal:s})),this.#J?.disconnect(),this._virtualization.viewportEl&&(this.#J=new ResizeObserver(()=>{this.#je(),this.#B.requestPhase(K.VIRTUALIZATION,"resize-observer")}),this.#J.observe(this._virtualization.viewportEl)),this.#z.addEventListener("focusin",()=>{this.dataset.hasFocus=""},{signal:t}),this.#z.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.#z.contains(t)||this.#le.isInExternalFocusContainer(t))||delete this.dataset.hasFocus},{signal:t})}#Ne=!1;#Ye(){if(this.#Ne)return;const e=this._bodyEl?.querySelector(".data-grid-row");e&&(this.#Ne=!0,this.#ee?.disconnect(),this.#ee=new ResizeObserver(()=>{this.#Be()}),this.#ee.observe(e))}addEventListener(e,t,i){super.addEventListener(e,t,i)}removeEventListener(e,t,i){super.removeEventListener(e,t,i)}on(e,t){const i=e=>{t(e.detail,e)};return this.addEventListener(e,i),()=>this.removeEventListener(e,i)}#Xe(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}_emitDataChange(){this.#Xe("data-change",{rowCount:this._rows.length,sourceRowCount:this.#O.length})}#We(){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))})})}#Re(e){this.#W[e]=!0,this.#$||(this.#$=!0,queueMicrotask(()=>this.#Ze()))}#Ze(){if(!this.#$||!this.#G)return void(this.#$=!1);const e=this.#W;if(this.#$=!1,this.#W={rows:!1,columns:!1,gridConfig:!1,fitMode:!1},e.gridConfig)return this.#Qe(),void(e.rows&&this.#Je());e.columns&&this.#et(),e.rows&&this.#Je(),e.fitMode&&this.#tt()}#Je(){this._rows=Array.isArray(this.#O)?[...this.#O]:[],this._rebuildRowIdMap(),this.#B.requestPhase(K.ROWS,"applyRowsUpdate")}_rebuildRowIdMap(){this.#ye.clear();const e=this.#f.getRowId;this._rows.forEach((t,i)=>{const r=Le(t,e);void 0!==r&&this.#ye.set(r,{row:t,index:i})})}#et(){he(this),this.#N.merge(),this.#$e()}#tt(){this.#N.merge();"fixed"===this.#f.fitMode?(this.__didInitialAutoSize=!1,m(this)):(this._columns.forEach(e=>{!e.__userResized&&e.__autoSized&&delete e.width}),y(this))}#Qe(){$e(this,this.#ue),We(this,this.#ue);const e=!!this.#z.querySelector(".has-shell"),t=!!this.#z.querySelector(".tbw-tool-panel"),i=this.#z.querySelectorAll(".tbw-accordion-section").length,r=this.#z.querySelector(".tbw-tool-panel")?.dataset.position??"right";this.#N.parseLightDomColumns(this),this.#N.merge(),this.#Me(),this.#Le(),Be(this,this.#ue,this.#De()),this.#N.markSourcesChanged(),this.#N.merge();const n=Ge(this.#f?.shell),o=(this.#f?.shell?.toolPanels?.length??0)>0,s=this.#f?.shell?.toolPanels?.length??0,l=this.#f?.shell?.toolPanel?.position??"right";if(e!==n||!t&&o||t&&s!==i||t&&r!==l)return Xe(this.#ue),this.#ze(),this.#Te(),this.#qe(),void this._rebuildRowIdMap();e&&this.#it(),this._rebuildRowIdMap(),this.#B.requestPhase(K.COLUMNS,"applyGridConfigUpdate")}#it(){const e=this.#z.querySelector(".tbw-shell-header");if(!e)return;const t=this.#f.shell?.header?.title??this.#ue.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()}#rt(){if(this.__rowRenderEpoch++,this.#re){const e=this.#Ce.length>0?this.#Ce:this._columns,t=e.filter(e=>!e.hidden),i=e.filter(e=>e.hidden),r=this.#re.processColumns([...t]);if(r!==t){const n=new Set(r.map(e=>e.field));!t.some(e=>n.has(e.field))&&r.length>0?this._columns=[...r,...i]:this._columns=this.#nt(e,r,i)}else this._columns=[...e]}}#nt(e,t,i){if(0===i.length)return t;const r=new Map;for(const l of t)r.set(l.field,l);const n=new Set(e.map(e=>e.field)),o=[];for(const l of t)n.has(l.field)||o.push(l);const s=[];for(const l of e){const e=r.get(l.field);e?s.push(e):l.hidden&&s.push(l)}return s.push(...o),s}#ot(){he(this);const e=function(e,t){if(!e._sortState)return t;e.__originalOrder=[...t];const i=(e.effectiveConfig?.sortHandler??D)(t,e._sortState,e._columns);return i&&"function"==typeof i.then?t:i}(this,Array.isArray(this.#O)?[...this.#O]:[]),t=this.#re?.processRows(e)??e;this._rows=t,this._rebuildRowIdMap(),this._virtualization.variableHeights&&this.#se.initializePositionCache(),this._emitDataChange()}#st(e){const t={...r,...e.animation},i=t.mode??"reduced-motion";let n=1;!1===i||"off"===i?n=0:!0!==i&&"on"!==i||(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="boolean"==typeof i?i?"on":"off":i}_renderVisibleRows(e,t,i=this.__rowRenderEpoch){if(this.#X||(this.#X=(e,t,i)=>this.#re?.renderRow(e,t,i)??!1),function(e,t,i,r,n){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=ce();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=n&&!1!==e.__hasRenderRowPlugins,h=e._hasAfterRowRenderHook?.()??!1,g=e._virtualization?.variableHeights&&"function"==typeof e.effectiveConfig?.rowHeight?e.effectiveConfig.rowHeight:null;for(let f=0;f<o;f++){const i=t+f,o=e._rows[i],w=e._rowPool[f];if(w.setAttribute("aria-rowindex",String(i+d+1)),c&&n(o,w,i)){w.__epoch=r,w.__rowDataRef=o,w.parentNode!==s&&s.appendChild(w);continue}const m=w.__epoch,b=w.__rowDataRef;let v=w.children.length;v>a&&w.lastElementChild?.classList.contains("tbw-row-loading-overlay")&&v--;const y=m===r&&v===a,C=b!==o,x=!!e._isGridEditMode;let R=!1;if(y&&C)for(let e=0;e<a;e++)if(l[e].externalView&&!w.querySelector(`.cell[data-col="${e}"] [data-external-view]`)){R=!0;break}if(!y||R){const t=oe(w),n=x&&!C||e._activeEditRows===i;t&&!n?(w.__isCustomRow&&(w.className="data-grid-row",w.setAttribute("role","row"),w.__isCustomRow=!1),se(w),ge(e,w,o,i),w.__epoch=r,w.__rowDataRef=o):t&&n?(ue(e,w,o,i),w.__rowDataRef=o):(w.__isCustomRow&&(w.className="data-grid-row",w.setAttribute("role","row"),w.__isCustomRow=!1),ge(e,w,o,i),w.__epoch=r,w.__rowDataRef=o)}else if(C){const t=oe(w),n=e._activeEditRows===i;t&&!n?(se(w),ge(e,w,o,i),w.__epoch=r,w.__rowDataRef=o):(ue(e,w,o,i),w.__rowDataRef=o)}else{const t=oe(w),n=x||e._activeEditRows===i;t&&!n?(se(w),ge(e,w,o,i),w.__epoch=r,w.__rowDataRef=o):ue(e,w,o,i)}let E=!1;const S=e._changedRowIdSet;if(S&&S.size>0)try{const t=e.getRowId?.(o);t&&(E=S.has(t))}catch{}E!==w.classList.contains("changed")&&w.classList.toggle("changed",E);const _=e.effectiveConfig?.rowClass;if(_){const t=w.getAttribute("data-dynamic-classes");t&&t.split(" ").forEach(e=>e&&w.classList.remove(e));try{const e=_(o),t="string"==typeof e?e.split(/\s+/):e;if(t&&t.length>0){let e="";for(const i of t)i&&"string"==typeof i&&(w.classList.add(i),e+=(e?" ":"")+i);w.setAttribute("data-dynamic-classes",e)}else w.removeAttribute("data-dynamic-classes")}catch(p){u("TBW060",`rowClass callback error: ${p}`,e.id),w.removeAttribute("data-dynamic-classes")}}if(g){const e=g(o,i);void 0!==e&&e>0?w.style.setProperty("--tbw-row-height",`${e}px`):w.style.removeProperty("--tbw-row-height")}h&&e._afterRowRender?.({row:o,rowIndex:i,rowElement:w}),w.parentNode!==s&&s.appendChild(w)}}(this,e,t,i,this.#X),this.#me.size>0)for(const r of this.#me)this.#Se(r,!0)}#lt={rowCount:-1,colCount:-1,ariaLabel:void 0,ariaDescribedBy:void 0};_updateAriaCounts(e,t){!function(e,t,i,r,n){if(r===e.rowCount&&n===e.colCount)return!1;const o=e.rowCount;e.rowCount=r,e.colCount=n,t&&(t.setAttribute("aria-rowcount",String(r)),t.setAttribute("aria-colcount",String(n))),r!==o&&i&&(r>0?i.setAttribute("role","rowgroup"):i.removeAttribute("role"))}(this.#lt,this.__rowsBodyEl,this._bodyEl,e,t)}_requestSchedulerPhase(e,t){this.#B.requestPhase(e,t)}_getPluginExtraHeight(){return this.#re?.getExtraHeight()??0}_getPluginRowHeight(e,t){return this.#re?.getRowHeight?.(e,t)}_getPluginExtraHeightBefore(e){return this.#re?.getExtraHeightBefore?.(e)??0}_adjustPluginVirtualStart(e,t,i){return this.#re?.adjustVirtualStart(e,t,i)}_afterPluginRender(){this.#re?.afterRender()}_emitPluginEvent(e,t){this.#re?.emitPluginEvent(e,t)}_schedulerMergeConfig(){this.#N.parseLightDomColumns(this),this.#N.merge(),this.#Me(),function(e,t,i){const r=at,n=dt,o=new Map;function s(e,t,i,r,n=!1){o.has(e)||o.set(e,{description:t,importHint:i,fields:[],isConfigProperty:n});const s=o.get(e);s.fields.includes(r)||s.fields.push(r)}for(const a of n){const i=e[a.property];(a.isUsed?a.isUsed(i):void 0!==i)&&!ut(t,a.pluginName)&&s(a.pluginName,a.description,ct(a.pluginName),a.property,!0)}const l=e.columns;if(l&&l.length>0)for(const a of l)for(const e of r){const i=a[e.property];if((e.isUsed?e.isUsed(i):void 0!==i)&&!ut(t,e.pluginName)){const t=a.field||"<unknown>";s(e.pluginName,e.description,ct(e.pluginName),t)}}if(o.size>0){const e=[];for(const[t,{description:i,importHint:r,fields:n,isConfigProperty:s}]of o)if(s)e.push(`Config uses ${i}, but the required plugin is not loaded.\n → Add the plugin to your gridConfig.plugins array:\n ${r}\n plugins: [new ${ht(t)}Plugin(), ...]`);else{const o=n.slice(0,3).join(", ")+(n.length>3?`, ... (${n.length} total)`:"");e.push(`Column(s) [${o}] use ${i}, but the required plugin is not loaded.\n → Add the plugin to your gridConfig.plugins array:\n ${r}\n plugins: [new ${ht(t)}Plugin(), ...]`)}h([...o.values()].some(e=>e.isConfigProperty)?"TBW002":"TBW001",`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.`,i)}}(this.#f,this.#re?.getPlugins()??[],this.id),function(e,t){const i=[],r=[];for(const n of e){const e=n.constructor.manifest;if(e?.configRules)for(const t of e.configRules){const e=n.config;if(t.check(e)){const e=`[${ht(n.name)}Plugin] Configuration warning: ${t.message}`;"error"===t.severity?i.push(e):r.push(e)}}}if(r.length>0&&Y())for(const n of r)u("TBW004",n,t);i.length>0&&h("TBW003",`Configuration error:\n\n${i.join("\n\n")}`,t)}(this.#re?.getPlugins()??[],this.id),function(e,t){if(!Y())return;const i=new Set(e.map(e=>e.name)),r=new Set;for(const n of e){const e=n.constructor.manifest;if(e?.incompatibleWith)for(const o of e.incompatibleWith)if(i.has(o.name)){const e=[n.name,o.name].sort().join("↔");if(r.has(e))continue;r.add(e),u("TBW022",`${ht(n.name)}Plugin and ${ht(o.name)}Plugin are both loaded, but they are currently incompatible.\n\n → ${o.reason}\n\n Consider removing one of these plugins to avoid unexpected behavior.`,t)}}}(this.#re?.getPlugins()??[],this.id),this.#at(),this.#Ce=[...this._columns]}_schedulerProcessColumns(){this.#rt()}_schedulerProcessRows(){this.#ot()}_schedulerRenderHeader(){B(this)}_schedulerUpdateTemplate(){y(this)}_schedulerAfterRender(){this.#re?.afterRender(),this._virtualization.enabled&&this._virtualization.totalHeightEl&&queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const e=this.#se.calculateTotalSpacerHeight(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`});"fixed"!==this.#f.fitMode||this.__didInitialAutoSize||(this.__didInitialAutoSize=!0,m(this)),this._restoreFocusAfterRender&&(this._restoreFocusAfterRender=!1,fe(this)),this._virtualization.enabled&&!this.#Ne&&this.#Ye(),this.#j&&(this.#j=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.#Ke()})})),this.#we&&this.#Ee()}get _schedulerIsConnected(){return this.isConnected&&this.#G}get _hostElement(){return this}get _renderRoot(){return this.#z}_emit(e,t){this.#Xe(e,t)}get _accordionIcons(){return{expand:this.#f?.icons?.expand??o.expand,collapse:this.#f?.icons?.collapse??o.collapse}}get _shellState(){return this.#ue}_clearRowPool(){this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++}_setup(){this.#$e()}_applyAnimationConfig(e){this.#st(e)}#at(){!function(e,t,i,r){if(!t)return!1;let n=!1;const o=function(e,t){const i=e?.gridAriaLabel;return i||(e?.shell?.header?.title??t?.lightDomTitle??void 0)}(i,r);o!==e.ariaLabel&&(e.ariaLabel=o,o?t.setAttribute("aria-label",o):t.removeAttribute("aria-label"),n=!0);const s=i?.gridAriaDescribedBy;s!==e.ariaDescribedBy&&(e.ariaDescribedBy=s,s?t.setAttribute("aria-describedby",s):t.removeAttribute("aria-describedby"),n=!0)}(this.#lt,this.__rowsBodyEl,this.#f,this.#ue)}#Ee(){const e=this.querySelector(".tbw-grid-root");var t;e&&(this.#we?(this.#ve||(this.#ve=function(e){const t=document.createElement("div");return t.className="tbw-loading-overlay",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.appendChild(Ee("large",e)),t}(this.#f?.loadingRenderer)),function(e,t){e.appendChild(t)}(e,this.#ve)):(t=this.#ve,t?.remove()))}#Se(e,t){const i=this.#ye.get(e);if(!i)return;const r=this.findRenderedRowElement?.(i.index);r&&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()}(r,t)}#_e(e,t,i){const r=this.#ye.get(e);if(!r)return;const n=this.findRenderedRowElement?.(r.index);if(!n)return;const o=this._visibleColumns.findIndex(e=>e.field===t);if(o<0)return;const s=n.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)}#$e(){if(this.isConnected&&this._headerRowEl&&this._bodyEl){if(this.#N.parseLightDomColumns(this),this.#C){const e=this.#C;this.#C=void 0,this.#N.merge();const t=this.#re?.getAll()??[];this.#N.applyState(e,t)}this._bodyEl&&(this._bodyEl.style.display="",this._bodyEl.style.gridTemplateColumns=""),this.#B.requestPhase(K.FULL,"setup")}}#Ue(e){let t=0,i=0,r=0,n=0,o=0;if(this.#U){const e=this._virtualization.container,s=this.#he;t=s?.scrollLeft??0,i=e?.scrollHeight??0,r=s?.scrollWidth??0,n=e?.clientHeight??0,o=s?.clientWidth??0}if(this.refreshVirtualWindow(!1)&&this.#re?.onScrollRender(),this._virtualization.variableHeights&&(this.#Y&&clearTimeout(this.#Y),this.#Y=window.setTimeout(()=>{this.#Y=0,this.#se.measureRenderedRowHeights(this._virtualization.start,this._virtualization.end)},100)),this.#U){const s=this.#ie;s.scrollTop=e,s.scrollLeft=t,s.scrollHeight=i,s.scrollWidth=r,s.clientHeight=n,s.clientWidth=o,this.#re?.onScroll(s)}}findHeaderRow(){return this.#z.querySelector(".header-row")}findRenderedRowElement(e){const t=this._virtualization,i=e-t.start;return i>=0&&i<this._rowPool.length&&i<t.end-t.start?this._rowPool[i]:null}_dispatchCellClick(e,t,i,r){const n=this._rows[t],o=this._visibleColumns[i];if(!n||!o)return!1;const s=o.field,l=n[s],a=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,composed:!0,detail:{rowIndex:t,colIndex:i,column:o,field:s,value:l,row:n,cellEl:r,trigger:"pointer",originalEvent:e}});if(this.dispatchEvent(a),a.defaultPrevented)return!0;const d={row:n,rowIndex:t,colIndex:i,column:o,field:s,value:l,cellEl:r,originalEvent:e},c=this.#re?.onCellClick(d)??!1;return this.#Xe("cell-click",d),c}_dispatchRowClick(e,t,i,r){if(!i)return!1;const n={rowIndex:t,row:i,rowEl:r,originalEvent:e},o=this.#re?.onRowClick(n)??!1;return this.#Xe("row-click",n),o}_dispatchHeaderClick(e,t,i){if(!t)return!1;const r={colIndex:this._columns.indexOf(t),field:t.field,column:t,headerEl:i,originalEvent:e};return this.#re?.onHeaderClick(r)??!1}_dispatchKeyDown(e){return this.#re?.onKeyDown(e)??!1}_getHorizontalScrollOffsets(e,t){return this.#re?.getHorizontalScrollOffsets(e,t)??{left:0,right:0}}queryPlugins(e){return this.#re?.queryPlugins(e)??[]}query(e,t){return this.#re?.queryPlugins({type:e,context:t})??[]}_dispatchCellMouseDown(e){return this.#re?.onCellMouseDown(e)??!1}_dispatchCellMouseMove(e){this.#re?.onCellMouseMove(e)}_dispatchCellMouseUp(e){this.#re?.onCellMouseUp(e)}_afterCellRender(e){this.#re?.afterCellRender(e)}_hasAfterCellRenderHook(){return this.#re?.hasAfterCellRenderHook()??!1}_afterRowRender(e){this.#re?.afterRowRender(e)}_hasAfterRowRenderHook(){return this.#re?.hasAfterRowRenderHook()??!1}async ready(){return this.#r}async forceLayout(){return this.#B.requestPhase(K.FULL,"forceLayout"),this.#B.whenReady()}async getConfig(){return Object.freeze({...this.#f||{}})}getRowId(e){return Ie(e,this.id,this.#f.getRowId)}getRow(e){return this.#ae.getRow(e)}_getRowEntry(e){return this.#ye.get(e)}updateRow(e,t,i="api"){this.#ae.updateRow(e,t,i)}updateRows(e,t="api"){this.#ae.updateRows(e,t)}animateRow(e,t){return Me(this,e,t)}animateRows(e,t){return function(e,t,i){return Promise.all(t.map(t=>Me(e,t,i))).then(e=>e.filter(Boolean).length)}(this,e,t)}animateRowById(e,t){return function(e,t,i){const r=e._rows??[],n=e.getRowId;if(!n)return Promise.resolve(!1);const o=r.findIndex(e=>{if(null==e)return!1;try{return n(e)===t}catch{return!1}});return o<0?Promise.resolve(!1):Me(e,o,i)}(this,e,t)}async insertRow(e,t,i=!0){return this.#ae.insertRow(e,t,i)}async removeRow(e,t=!0){return this.#ae.removeRow(e,t)}async applyTransaction(e,t=!0){return this.#ae.applyTransaction(e,t)}applyTransactionAsync(e){return this.#ae.applyTransactionAsync(e)}suspendProcessing(){}focusCell(e,t){this.#le.focusCell(e,t)}get focusedCell(){return this.#le.focusedCell}scrollToRow(e,t){this.#le.scrollToRow(e,t)}scrollToRowById(e,t){this.#le.scrollToRowById(e,t)}setColumnVisible(e,t){const i=this.#N.setColumnVisible(e,t);return i&&this.requestStateChange(),i}toggleColumnVisibility(e){const t=this.#N.toggleColumnVisibility(e);return t&&this.requestStateChange(),t}isColumnVisible(e){return this.#N.isColumnVisible(e)}showAllColumns(){this.#N.showAllColumns(),this.requestStateChange()}getAllColumns(){return this.#N.getAllColumns()}setColumnOrder(e){this.#N.setColumnOrder(e),this.requestStateChange()}getColumnOrder(){return this.#N.getColumnOrder()}getColumnState(){const e=this.#re?.getAll()??[];return this.#N.collectState(e)}set columnState(e){e&&(this.#C=e,this.#N.initialColumnState=e,this.#q&&this.#dt(e))}get columnState(){return this.getColumnState()}#dt(e){const t=this.#re?.getAll()??[];this.#N.applyState(e,t),this.#$e()}requestStateChange(){const e=this.#re?.getAll()??[];this.#N.requestStateChange(e)}resetColumnState(){this.#C=void 0,this.__originalOrder=[];const e=this.#re?.getAll()??[];this.#N.resetState(e),this.#N.merge(),this.#$e()}get isToolPanelOpen(){return this.#ge.isPanelOpen}get defaultRowHeight(){return this._virtualization.rowHeight}get expandedToolPanelSections(){return this.#ge.expandedSections}openToolPanel(){this.#ge.openToolPanel()}closeToolPanel(){this.#ge.closeToolPanel()}toggleToolPanel(){this.#ge.toggleToolPanel()}toggleToolPanelSection(e){this.#ge.toggleToolPanelSection(e)}getToolPanels(){return this.#ge.getToolPanels()}registerToolPanel(e){this.#ue.apiToolPanelIds.add(e.id),this.#ge.registerToolPanel(e)}unregisterToolPanel(e){this.#ue.apiToolPanelIds.delete(e),this.#ge.unregisterToolPanel(e)}getHeaderContents(){return this.#ge.getHeaderContents()}registerHeaderContent(e){this.#ue.apiHeaderContentIds.add(e.id),this.#ge.registerHeaderContent(e)}unregisterHeaderContent(e){this.#ue.apiHeaderContentIds.delete(e),this.#ge.unregisterHeaderContent(e)}getToolbarContents(){return this.#ge.getToolbarContents()}registerToolbarContent(e){this.#ge.registerToolbarContent(e)}unregisterToolbarContent(e){this.#ge.unregisterToolbarContent(e)}#ct=!1;refreshShellHeader(){this.#ct||(this.#ct=!0,queueMicrotask(()=>{this.#ct=!1,this.isConnected&&(this.#Fe(),this.#N.markSourcesChanged(),this.#N.merge(),Xe(this.#ue),this.#ze(),this.#Te(),this.#ht())}))}#ht(){const e=this.#z.querySelector(".tbw-grid-content")??this.#z.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.#ge.isInitialized){Ke(this.#z,this.#ue),Ve(this.#z,this.#f?.shell,this.#ue);const e=this.#f?.shell?.toolPanel?.defaultOpen;e&&this.#ue.toolPanels.has(e)&&(this.openToolPanel(),this.#ue.expandedSections.add(e)),this.#ue.isPanelOpen&&(Ye(this.#z,this.#ue),Ue(this.#z,this.#ue,(this.#f,this.#f)),je(this.#z,this.#ue))}this._resizeController=Se(this),this.#Pe(e),this.#B.requestPhase(K.COLUMNS,"shellRefresh")}#Ge=new Map;registerStyles(e,t){let i=this.#Ge.get(e);i||(i=new CSSStyleSheet,this.#Ge.set(e,i)),i.replaceSync(t),this.#ut()}unregisterStyles(e){this.#Ge.delete(e)&&this.#ut()}getRegisteredStyles(){return Array.from(this.#Ge.keys())}#ut(){const e=Array.from(this.#Ge.values()),t=document.adoptedStyleSheets.filter(e=>!Array.from(this.#Ge.values()).includes(e));document.adoptedStyleSheets=[...t,...e]}registerExternalFocusContainer(e){this.#le.registerExternalFocusContainer(e)}unregisterExternalFocusContainer(e){this.#le.unregisterExternalFocusContainer(e)}containsFocus(e){return this.#le.containsFocus(e)}#Fe(){$e(this,this.#ue),We(this,this.#ue),Be(this,this.#ue,this.#De())}#gt(){const e=this.#z.querySelector(".tbw-shell-header");if(!e)return;Xe(this.#ue);const t=function(e,t,i="☰"){const r=e?.header?.title??t.lightDomTitle??"",n=!!r,o=Ne(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 ${n?`<div class="tbw-shell-title">${f=r,f&&"string"==typeof f?f.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""}</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.#f.shell,this.#ue,this.#f.icons?.toolPanel),i=document.createElement("div");i.innerHTML=t;const r=i.firstElementChild;r&&(e.replaceWith(r),this.#pt(),Ve(this.#z,this.#f?.shell,this.#ue))}#Oe(){const e=()=>{const e=this.#ue.lightDomTitle,t=this.#ue.hasToolButtonsContainer;this.#Fe();const i=this.#ue.lightDomTitle,r=this.#ue.hasToolButtonsContainer;(i&&!e||r&&!t)&&(this.#N.markSourcesChanged(),this.#N.merge(),this.#gt())},t=()=>{this.__lightDomColumnsCache=void 0,this.#$e()};this.#N.registerLightDomHandler("tbw-grid-header",e),this.#N.registerLightDomHandler("tbw-grid-tool-buttons",e),this.#N.registerLightDomHandler("tbw-grid-tool-panel",e),this.#N.registerLightDomHandler("tbw-grid-column",t),this.#N.registerLightDomHandler("tbw-grid-detail",t),this.#N.observeLightDOM(this)}refreshColumns(){this.__lightDomColumnsCache=void 0,he(this),this.#N.parseLightDomColumns(this);const e=this.#ue.lightDomTitle,t=this.#ue.hasToolButtonsContainer;this.#Fe();const i=this.#ue.lightDomTitle,r=this.#ue.hasToolButtonsContainer;(i&&!e||r&&!t)&&(this.#N.markSourcesChanged(),this.#N.merge(),this.#gt()),this.#B.requestPhase(K.COLUMNS,"refreshColumns")}#je(){this.#se.updateCachedGeometry()}refreshVirtualWindow(e=!1,t=!1){return this.#se.refreshVirtualWindow(e,t)}invalidateRowHeight(e,t){this.#se.invalidateRowHeight(e,t)}#ze(){this.#Fe(),this.#N.markSourcesChanged(),this.#N.merge();const e=this.#f?.shell;Qe(this.#z,e,{isPanelOpen:this.#ue.isPanelOpen,expandedSections:this.#ue.expandedSections},this.#f?.icons)&&(this.#pt(),this.#ge.setInitialized(!0))}#pt(){!function(e,t,i,r){const n=e.querySelector(".tbw-shell-toolbar");n&&n.addEventListener("click",e=>{e.target.closest("[data-panel-toggle]")&&r.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&&r.onSectionToggle(i)}})}(this.#z,this.#f,this.#ue,{onPanelToggle:()=>this.toggleToolPanel(),onSectionToggle:e=>this.toggleToolPanelSection(e)}),this.#pe?.(),this.#pe=function(e,t,i){const r=e.querySelector(".tbw-tool-panel"),n=e.querySelector("[data-resize-handle]"),o=e.querySelector(".tbw-shell-body");if(!r||!n||!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));r.style.width=`${i}px`},u=()=>{if(!c)return;c=!1,n.classList.remove("resizing"),r.style.transition="",document.body.style.cursor="",document.body.style.userSelect="";const e=r.getBoundingClientRect().width;i(e),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",u)},g=e=>{e.preventDefault(),c=!0,l=e.clientX,a=r.getBoundingClientRect().width,d=o.getBoundingClientRect().width-20,n.classList.add("resizing"),r.style.transition="none",document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",h),document.addEventListener("mouseup",u)};return n.addEventListener("mousedown",g),()=>{n.removeEventListener("mousedown",g),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",u)}}(this.#z,this.#f?.shell,e=>{this.style.setProperty("--tbw-tool-panel-width",`${e}px`)}),this.#fe?.(),this.#fe=function(e,t,i,r){if(!t?.toolPanel?.closeOnClickOutside)return()=>{};const n=e=>{if(!i.isPanelOpen)return;const t=e.target;t&&(t.closest(".tbw-tool-panel")||t.closest("[data-panel-toggle]")||r())};return e.addEventListener("mousedown",n),()=>e.removeEventListener("mousedown",n)}(this,this.#f?.shell,this.#ue,()=>this.closeToolPanel())}}customElements.get(yt.tagName)||customElements.define(yt.tagName,yt),globalThis.DataGridElement=yt;class Ct{static dependencies;static manifest;aliases;version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#ft;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}attach(e){this.#ft?.abort(),this.#ft=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#ft?.abort(),this.#ft=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?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}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?._hostElement}get disconnectSignal(){return this.#ft?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...o,...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,t){void 0!==t?console.warn(c(e,t,this.gridElement.id,this.name)):console.warn(`${s(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(c(e,t,this.gridElement.id,this.name))}}const xt={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"},Rt={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"},Et={ROOT:`.${xt.ROOT}`,HEADER:`.${xt.HEADER}`,HEADER_ROW:`.${xt.HEADER_ROW}`,HEADER_CELL:`.${xt.HEADER_CELL}`,ROWS_VIEWPORT:`.${xt.ROWS_VIEWPORT}`,ROWS_CONTAINER:`.${xt.ROWS_CONTAINER}`,DATA_ROW:`.${xt.DATA_ROW}`,DATA_CELL:`.${xt.DATA_CELL}`,GROUP_ROW:`.${xt.GROUP_ROW}`,ROW_BY_INDEX:e=>`.${xt.DATA_ROW}[${Rt.ROW_INDEX}="${e}"]`,CELL_BY_FIELD:e=>`.${xt.DATA_CELL}[${Rt.FIELD}="${e}"]`,CELL_AT:(e,t)=>`.${xt.DATA_ROW}[${Rt.ROW_INDEX}="${e}"] .${xt.DATA_CELL}[${Rt.COL_INDEX}="${t}"]`,SELECTED_ROWS:`.${xt.DATA_ROW}.${xt.SELECTED}`,EDITING_CELL:`.${xt.DATA_CELL}.${xt.EDITING}`};function St(e,t,i=!0){let r=e;if(i&&(r=r.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.meta?.utility)),t?.length){const e=new Set(t);r=r.filter(t=>e.has(t.field))}return r}function _t(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}function At(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}function kt(e,t){const i=t.delimiter??"\t",r=t.newline??"\n",n=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),o=[];let s=[],l="",a=!1;for(let d=0;d<n.length;d++){const e=n[d];'"'!==e||a?'"'===e&&a?'"'===n[d+1]?(l+='"',d++):a=!1:e!==i||a?e!==r||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 Tt(e,t){const{rows:i,target:r,fields:n}=e;if(!r)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=r.bounds?r.bounds.endRow:1/0;i.forEach((e,t)=>{const i=r.row+t;if(!(i>c)){if(r.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 r=n[t];r&&a.get(r)&&(d[i][r]=e)})}}),t.rows=d}function Mt(e){if(null==e)return 100;if("number"==typeof e)return e;const t=parseFloat(e);return isNaN(t)?100:t}function Lt(e){return e.map(e=>Mt(e.width))}function It(e){const t=[];let i=0;for(const r of e)t.push(i),i+=Mt(r.width);return t}function Pt(e){return e.reduce((e,t)=>e+Mt(t.width),0)}function Ht(e,t,i,r,n){const o=i.length;if(0===o)return{startCol:0,endCol:0,visibleColumns:[]};let s=function(e,t,i){let r=0,n=t.length-1;for(;r<n;){const o=Math.floor((r+n)/2);t[o]+i[o]<=e?r=o+1:n=o}return r}(e,i,r);s=Math.max(0,s-n);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+n);const d=[];for(let c=s;c<=a;c++)d.push(c);return{startCol:s,endCol:a,visibleColumns:d}}const Dt="@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 Ft(e,t){return("function"==typeof e?e(t):e).filter(e=>!0!==e.hidden&&("function"!=typeof e.hidden||!e.hidden(t)))}function zt(e,t){return!0===e.disabled||"function"==typeof e.disabled&&e.disabled(t)}function qt(e,t,i,r=o.submenuArrow){const n=document.createElement("div");n.className="tbw-context-menu",n.setAttribute("role","menu");const s=e.some(e=>!e.separator&&e.icon);for(const o of e){if(o.separator){const e=document.createElement("div");e.className="tbw-context-menu-separator",e.setAttribute("role","separator"),n.appendChild(e);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",o.cssClass&&e.classList.add(o.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",o.id),e.setAttribute("tabindex","-1");const l=zt(o,t);if(l&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),o.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=o.icon,e.appendChild(t)}else if(s){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=" ",e.appendChild(t)}const a=document.createElement("span");if(a.className="tbw-context-menu-label",a.textContent=o.name,e.appendChild(a),o.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(o.shortcut))o.shortcut.forEach((e,i)=>{i>0&&t.appendChild(document.createTextNode("+"));const r=document.createElement("kbd");r.textContent=e,t.appendChild(r)});else{const e=document.createElement("kbd");e.textContent=o.shortcut,t.appendChild(e)}e.appendChild(t)}if(o.subMenu?.length){const n=document.createElement("span");n.className="tbw-context-menu-arrow","string"==typeof r?n.innerHTML=r:r instanceof HTMLElement&&n.appendChild(r.cloneNode(!0)),e.appendChild(n),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!o.subMenu)return;const n=qt(Ft(o.subMenu,t),t,i,r);n.classList.add("tbw-context-submenu"),n.style.position="absolute",n.style.left="100%",n.style.top="0",e.style.position="relative",e.appendChild(n)}),e.addEventListener("mouseleave",()=>{const t=e.querySelector(".tbw-context-menu");t&&t.remove()})}l||!o.action||o.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),i(o)}),n.appendChild(e)}return n}const Ot="getContextMenuItems";let Nt=null,Gt=null,$t=0;const Wt=[{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 Bt extends Ct{static manifest={queries:[{type:Ot,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:Wt}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),$t++}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),r=[],n=i.getPropertyValue("color-scheme").trim();n&&r.push(`color-scheme: ${n}`);for(const o of Bt.CSS_VARS_TO_COPY){const e=i.getPropertyValue(o).trim();e&&r.push(`${o}: ${e}`)}if(r.length>0){const t=e.getAttribute("style")||"";e.setAttribute("style",t+r.join("; ")+";")}}installGlobalHandlers(){if(!Gt&&"undefined"!=typeof document&&Dt&&(Gt=document.createElement("style"),Gt.id="tbw-context-menu-styles",Gt.textContent=Dt,document.head.appendChild(Gt)),!Nt){Nt=new AbortController;const e=Nt.signal,t=()=>{document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())};document.addEventListener("click",t,{signal:e}),document.addEventListener("keydown",e=>{"Escape"===e.key&&t()},{signal:e}),document.addEventListener("scroll",t,{capture:!0,signal:e})}}uninstallGlobalHandlers(){$t--,$t>0||(Nt&&(Nt.abort(),Nt=null),Gt&&(Gt.remove(),Gt=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(Ot,e),i=[];for(const r of t)Array.isArray(r)&&i.push(...r);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 r of e){if(r.separator){t.push(r);continue}const e=Math.floor((r.order??100)/10);i>=0&&e!==i&&t.push({id:`__sep-${i}-${e}`,label:"",separator:!0,action:()=>{}}),i=e,t.push(r)}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}))}openMenuAt(e,t,i,r=!1){this.params=e,this.position={x:t,y:i};const n=this.collectPluginItems(e);let o=Ft(this.config.items??Wt,e);if(n.length>0){const e=this.convertPluginItems(n);o=o.length>0&&e.length>0?[...o,{id:"__plugin-sep",name:"",separator:!0},...e]:[...o,...e]}var s,l;(o=function(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}(o),o.length)&&(document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove()),this.menuElement=null,this.menuElement=qt(o,e,t=>{t.action&&t.action(e),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),s=this.menuElement,l=()=>this.hideMenu(),s.addEventListener("keydown",e=>{const t=Array.from(s.querySelectorAll('[role="menuitem"]:not(.disabled)'));if(!t.length)return;const i=document.activeElement,r=t.indexOf(i);switch(e.key){case"ArrowDown":e.preventDefault(),t[r<t.length-1?r+1:0].focus();break;case"ArrowUp":e.preventDefault(),t[r>0?r-1:t.length-1].focus();break;case"Enter":case" ":e.preventDefault(),i&&t.includes(i)&&i.click();break;case"Escape":e.preventDefault(),l()}}),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),function(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 r=e.getBoundingClientRect(),n=window.innerWidth,o=window.innerHeight;let s=t,l=i;t+r.width>n&&(s=t-r.width),i+r.height>o&&(l=i-r.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"}(this.menuElement,t,i),this.isOpen=!0,r&&function(e){const t=e.querySelector('[role="menuitem"]:not(.disabled)');t?.focus()}(this.menuElement),this.emit("context-menu-open",{params:e,items:o}))}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,r=i.closest("[data-row][data-col]"),n=i.closest('[part~="header-cell"]');let o;if(r){const e=parseInt(r.getAttribute("data-row")??"-1",10),i=parseInt(r.getAttribute("data-col")??"-1",10),n=this.visibleColumns[i],s=this.rows[e],l=this.syncSelectionOnContextMenu(e);o={row:s,rowIndex:e,column:n,columnIndex:i,field:n?.field??"",value:s?.[n?.field]??null,isHeader:!1,event:t,selectedRows:l}}else{if(!n)return;{const e=parseInt(n.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.openMenuAt(o,t.clientX,t.clientY)}))}onKeyDown(e){const t="F10"===e.key&&e.shiftKey,i="ContextMenu"===e.key;if(!t&&!i)return;e.preventDefault();const r=this.grid;if(!r)return;const n=r._focusRow,o=r._focusCol,s=this.visibleColumns[o],l=this.rows[n],a=this.gridElement,d=a?.querySelector(`[data-row="${n}"][data-col="${o}"]`);let c=0,h=0;if(d){const e=d.getBoundingClientRect();c=e.left+e.width/2,h=e.bottom}const u=this.syncSelectionOnContextMenu(n),g={row:l,rowIndex:n,column:s,columnIndex:o,field:s?.field??"",value:l?.[s?.field]??null,isHeader:!1,event:e,selectedRows:u};return this.openMenuAt(g,c,h,!0),!0}showMenu(e,t,i){const r={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??[]};this.openMenuAt(r,e,t)}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}function Vt(e){return t=>{const i=e.editorParams,r=document.createElement("input");r.type="date",t.value instanceof Date?r.valueAsDate=t.value:"string"==typeof t.value&&t.value&&(r.value=t.value.split("T")[0]),i?.min&&(r.min=i.min),i?.max&&(r.max=i.max),i?.placeholder&&(r.placeholder=i.placeholder);return r.addEventListener("change",()=>{var n;if(r.value)"string"==typeof t.value?t.commit(r.value):t.commit(r.valueAsDate);else if(e.nullable)t.commit(null);else{const e=i?.default;"string"==typeof t.value||"string"==typeof e?t.commit("string"==typeof e?e:`${(n=e??new Date).getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`):t.commit(e instanceof Date?e:new Date)}}),r.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),r}}const Kt="__tbw_null__";function Ut(e){switch(e.type){case"number":return function(e){return t=>{const i=e.editorParams,r=document.createElement("input");r.type="number",r.value=null!=t.value?String(t.value):"",void 0!==i?.min&&(r.min=String(i.min)),void 0!==i?.max&&(r.max=String(i.max)),void 0!==i?.step&&(r.step=String(i.step)),i?.placeholder&&(r.placeholder=i.placeholder);const n=()=>{""===r.value?e.nullable?t.commit(null):t.commit(i?.min??0):t.commit(Number(r.value))};return r.addEventListener("blur",n),r.addEventListener("keydown",e=>{"Enter"===e.key&&n(),"Escape"===e.key&&t.cancel()}),r}}(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 Vt(e);case"select":return function(e){return t=>{const i=e.editorParams,r=document.createElement("select");if(e.multi&&(r.multiple=!0),e.nullable||i?.includeEmpty){const n=document.createElement("option");n.value=e.nullable?Kt:"",n.textContent=e.nullable?i?.emptyLabel??"(Blank)":i?.emptyLabel??"",null==t.value&&(n.selected=!0),r.appendChild(n)}const n=function(e){const t=e.options;return t?"function"==typeof t?t():t:[]}(e);n.forEach(i=>{const n=document.createElement("option");n.value=String(i.value),n.textContent=i.label,e.multi&&Array.isArray(t.value)&&t.value.includes(i.value)?n.selected=!0:e.multi||t.value!==i.value||(n.selected=!0),r.appendChild(n)});const o=()=>{if(e.multi){const e=Array.from(r.selectedOptions).map(e=>e.value);t.commit(e)}else e.nullable&&r.value===Kt?t.commit(null):t.commit(r.value)};return r.addEventListener("change",o),r.addEventListener("blur",o),r.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),r}}(e);default:return function(e){return t=>{const i=e.editorParams,r=document.createElement("input");r.type="text",r.value=null!=t.value?String(t.value):"",void 0!==i?.maxLength&&(r.maxLength=i.maxLength),i?.pattern&&(r.pattern=i.pattern),i?.placeholder&&(r.placeholder=i.placeholder);const n=()=>{const i=r.value;""!==i?"string"==typeof t.value&&i===t.value.replace(/[\n\r]/g,"")||("number"==typeof t.value?t.commit(Number(i)):t.commit(i)):e.nullable?t.commit(null):t.commit("")};return r.addEventListener("blur",n),r.addEventListener("keydown",e=>{"Enter"===e.key&&n(),"Escape"===e.key&&t.cancel()}),r}}(e)}}function jt(e,t,i){if(e instanceof HTMLInputElement){if("checkbox"===e.type)return e.checked;if("number"===e.type){if(""===e.value){if(t?.nullable)return null;const e=t?.editorParams;return e?.min??0}return Number(e.value)}if("date"===e.type)return e.value?"string"==typeof i?e.value:e.valueAsDate:t?.nullable?null:"string"==typeof i?i||(new Date).toISOString().slice(0,10):i??new Date;if("number"==typeof i){if(""===e.value){if(t?.nullable)return null;const e=t?.editorParams;return e?.min??0}return Number(e.value)}return""===e.value&&null==i?t?.nullable?null:"":"string"==typeof i&&e.value===i.replace(/[\n\r]/g,"")?i:e.value}return"number"===t?.type&&""!==e.value||"number"==typeof i&&""!==e.value?Number(e.value):null==i&&""===e.value?t?.nullable?null:"":e.value}class Yt{#wt=new Map;#mt;constructor(e){this.#mt=e}setInvalid(e,t,i=""){let r=this.#wt.get(e);r||(r=new Map,this.#wt.set(e,r)),r.set(t,i),this.#mt(e,t,!0)}clearInvalid(e,t){const i=this.#wt.get(e);i&&(i.delete(t),0===i.size&&this.#wt.delete(e)),this.#mt(e,t,!1)}clearRowInvalid(e){const t=this.#wt.get(e);if(t){const i=Array.from(t.keys());this.#wt.delete(e),i.forEach(t=>this.#mt(e,t,!1))}}clearAllInvalid(){const e=Array.from(this.#wt.entries());this.#wt.clear(),e.forEach(([e,t])=>{t.forEach((t,i)=>this.#mt(e,i,!1))})}isCellInvalid(e,t){return this.#wt.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#wt.get(e)?.get(t)}hasInvalidCells(e){const t=this.#wt.get(e);return!!t&&t.size>0}getInvalidFields(e){return new Map(this.#wt.get(e)??[])}}function Xt(e,t,i){const r=e.get(t);return!!r&&!Zt(r,i)}function Zt(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(typeof e!=typeof t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Zt(e[i],t[i]))return!1;return!0}if("object"==typeof e){const i=e,r=t,n=Object.keys(i),o=Object.keys(r);if(n.length!==o.length)return!1;for(const e of n)if(!Zt(i[e],r[e]))return!1;return!0}return!1}function Qt(e,t,i){e.set(t,structuredClone(i))}function Jt(e,t,i){const r=e.get(t);if(!r)return!1;const n=r,o=i;for(const s of Object.keys(n))o[s]=n[s];return!0}class ei{baselines=new Map;baselinesWereCaptured=!1;newRowIds=new Set;changedRowIds=new Set;committedDirtyRowIds=new Set;clear(){this.changedRowIds.clear(),this.committedDirtyRowIds.clear(),this.baselines.clear(),this.newRowIds.clear(),this.baselinesWereCaptured=!1}capture(e,t){const i=this.baselines.size;!function(e,t,i){for(const r of t)try{const t=i(r);null==t||e.has(t)||e.set(t,structuredClone(r))}catch{}}(this.baselines,e,t),this.baselines.size>i&&(this.baselinesWereCaptured=!0)}drainCapturedFlag(){return this.baselinesWereCaptured?(this.baselinesWereCaptured=!1,this.baselines.size):null}isRowDirty(e,t){return Xt(this.baselines,e,t)}hasAnyDirty(e){if(this.newRowIds.size>0)return!0;for(const[t]of this.baselines){const i=e(t);if(i&&Xt(this.baselines,t,i))return!0}return!1}isCellDirty(e,t,i){return function(e,t,i,r){const n=e.get(t);return!!n&&!Zt(n[r],i[r])}(this.baselines,e,t,i)}getRowDirtyState(e,t){const i=this.newRowIds.has(e);return{isNew:i,isCommittedDirty:!i&&this.committedDirtyRowIds.has(e)&&Xt(this.baselines,e,t),hasBaseline:this.baselines.has(e)}}markPristine(e,t){Qt(this.baselines,e,t),this.newRowIds.delete(e),this.changedRowIds.delete(e),this.committedDirtyRowIds.delete(e)}markNew(e){this.newRowIds.add(e),this.committedDirtyRowIds.add(e)}markDirty(e){this.changedRowIds.add(e),this.committedDirtyRowIds.add(e)}markAllPristine(e){for(const[t]of this.baselines){const i=e(t);i&&Qt(this.baselines,t,i)}this.newRowIds.clear(),this.changedRowIds.clear(),this.committedDirtyRowIds.clear()}getOriginalRow(e){return function(e,t){const i=e.get(t);return i?structuredClone(i):void 0}(this.baselines,e)}hasBaseline(e){return this.baselines.has(e)}getDirtyRows(e){const t=[];for(const[i,r]of this.baselines){const n=e(i);n&&Xt(this.baselines,i,n)&&t.push({id:i,original:structuredClone(r),current:n})}for(const i of this.newRowIds){const r=e(i);r&&t.push({id:i,original:void 0,current:r})}return t}getDirtyRowIds(e){const t=[];for(const[i]of this.baselines){const r=e(i);r&&Xt(this.baselines,i,r)&&t.push(i)}for(const i of this.newRowIds)t.push(i);return t}revertRow(e,t){const i=Jt(this.baselines,e,t);return i&&(this.changedRowIds.delete(e),this.committedDirtyRowIds.delete(e)),i}revertAll(e){for(const[t]of this.baselines){const i=e(t);i&&Jt(this.baselines,t,i)}this.changedRowIds.clear(),this.committedDirtyRowIds.clear()}getChangedRows(e){const t=[];for(const i of this.changedRowIds){const r=e(i);r&&t.push(r)}return t}getChangedRowIds(){return Array.from(this.changedRowIds)}isRowChanged(e){return this.changedRowIds.has(e)}}const ti='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function ii(e){return"string"==typeof e&&("__proto__"!==e&&"constructor"!==e&&"prototype"!==e)}function ri(e){}function ni(e,t){return!1===e.onBeforeEditClose?.(t)}function oi(e,t,i,r,n,o,s,l){if(!r.editable)return;if(o.classList.contains("editing"))return;const{grid:a,isGridMode:d,config:c,editingCells:h,editorValueCallbacks:g}=e;let p;try{p=a.getRowId?.(t)}catch{}const f=p?e=>a.updateRow(p,e,"cascade"):ri,w=ii(r.field)?t[r.field]:void 0;o.classList.add("editing"),h.add(`${i}:${n}`);const m=l??o.parentElement;m&&function(e){const t=(e.__editingCellCount??0)+1;e.__editingCellCount=t,e.setAttribute("data-has-editing","")}(m);let b=!1;const v=n=>{if(b||!d&&!e.isEditSessionActive())return;const o=p?a._getRowEntry(p):void 0,s=o?.row??t,l=o?.index??i;e.commitCellValue(l,r,n,s)},y=()=>{if(b=!0,ii(r.field)){const e=p?a._getRowEntry(p):void 0;(e?.row??t)[r.field]=w}},C=document.createElement("div");C.className="tbw-editor-host",o.innerHTML="",o.appendChild(C),C.addEventListener("keydown",t=>{if("Enter"===t.key){if(d){t.stopPropagation(),t.preventDefault();const e=C.querySelector("input,textarea,select");return void(e&&v(jt(e,r,w)))}if(ni(c,t))return;t.stopPropagation(),t.preventDefault(),b=!0,e.exitRowEdit(i,!1)}if("Escape"===t.key){if(d)return t.stopPropagation(),void t.preventDefault();if(ni(c,t))return;t.stopPropagation(),t.preventDefault(),y(),e.exitRowEdit(i,!0)}});const x=r,R=x.__editorTemplate,E=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 r=e.__frameworkAdapter;if(r?.getTypeDefault){const e=r.getTypeDefault(t.type);if(e?.editor)return e.editor}}(a,x)??Ut(r),S=w,_=`${i}:${r.field}`,A=[];g.set(_,e=>{for(const t of A)t(e)});const k=e=>{A.push(e)};if("template"===E&&R)!function(e,t,i,r,n,o,s,l,a){const d=i.__editorTemplate;if(!d)return;const c=d.cloneNode(!0),h=i.__compiledEditor;h?c.innerHTML=h({row:r,value:n,field:i.field,column:i,commit:o,cancel:s}):c.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(!ii(t))return"";const i=r[t];return null==i?"":String(i)})||"")});const u=c.querySelector("input,textarea,select");if(u){u instanceof HTMLInputElement&&"checkbox"===u.type?u.checked=!!n:u.value=String(n??"");let t=!1;u.addEventListener("blur",()=>{t||o(jt(u,i,n))}),u.addEventListener("keydown",r=>{const l=r;if("Enter"===l.key){if(ni(e.config,l))return;l.stopPropagation(),l.preventDefault(),t=!0,o(jt(u,i,n)),e.exitRowEdit(a,!1)}if("Escape"===l.key){if(ni(e.config,l))return;l.stopPropagation(),l.preventDefault(),s(),e.exitRowEdit(a,!0)}}),u instanceof HTMLInputElement&&"checkbox"===u.type&&u.addEventListener("change",()=>o(u.checked)),l||setTimeout(()=>u.focus({preventScroll:!0}),0)}t.appendChild(c)}(e,C,x,t,w,v,y,s,i),k(e=>{if(null!=e&&"object"==typeof e)return;const t=C.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if("string"==typeof E){const e=document.createElement(E);e.value=S,e.addEventListener("change",()=>v(e.value)),k(t=>{e.value=t}),C.appendChild(e),s||queueMicrotask(()=>{const e=C.querySelector(ti);e?.focus({preventScroll:!0})})}else if("function"==typeof E){const e=E({row:t,rowId:p??"",value:S,field:r.field,column:r,commit:v,cancel:y,updateRow:f,onValueChange:k});if("string"==typeof e)C.innerHTML=e,function(e,t,i,r){const n=e.querySelector("input,textarea,select");n&&(n.addEventListener("blur",()=>{i(jt(n,t,r))}),n instanceof HTMLInputElement&&"checkbox"===n.type?n.addEventListener("change",()=>i(n.checked)):n instanceof HTMLSelectElement&&n.addEventListener("change",()=>i(jt(n,t,r))))}(C,r,v,w),k(e=>{const t=C.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if(e instanceof Node){C.appendChild(e);e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?k(t=>{e instanceof HTMLInputElement&&"checkbox"===e.type?e.checked=!!t:e.value=String(t??"")}):o.setAttribute("data-editor-managed","")}else!e&&C.hasChildNodes()&&o.setAttribute("data-editor-managed","");s||queueMicrotask(()=>{const e=C.querySelector(ti);e?.focus({preventScroll:!0})})}else if(E&&"object"==typeof E){const i=document.createElement("div");i.setAttribute("data-external-editor",""),i.setAttribute("data-field",r.field),C.appendChild(i),o.setAttribute("data-editor-managed","");const n={row:t,rowId:p??"",value:S,field:r.field,column:r,commit:v,cancel:y,updateRow:f,onValueChange:k};if(E.mount)try{E.mount({placeholder:i,context:n,spec:E})}catch(T){u("TBW080",`External editor mount error for column '${r.field}': ${T}`,e.grid.id)}else a.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:i,spec:E,context:n}}))}}function si(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 li(e,t){const i=URL.createObjectURL(e),r=document.createElement("a");r.href=i,r.download=t,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(i)}function ai(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const di="(Blank)";function ci(e){if(e instanceof Date)return e.getTime();const t=Number(e);if(!isNaN(t))return t;return new Date(e).getTime()}function hi(e,t,i=!1,r){return t.length?e.filter(e=>t.every(t=>function(e,t,i=!1,r){const n=e[t.field];if("blank"===t.operator)return null==n||""===n;if("notBlank"===t.operator)return null!=n&&""!==n;if(r&&("notIn"===t.operator||"in"===t.operator)){const i=r(n,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(di):!o.some(t=>e.includes(t)))}if("in"===t.operator){const e=t.value;return!!Array.isArray(e)&&(0===o.length?e.includes(di):o.some(t=>e.includes(t)))}}if("notIn"===t.operator)return null==n||""===n?!Array.isArray(t.value)||!t.value.includes(di):Array.isArray(t.value)&&!t.value.includes(n);if("in"===t.operator)return null==n||""===n?Array.isArray(t.value)&&t.value.includes(di):Array.isArray(t.value)&&t.value.includes(n);if(null==n)return!1;const o=String(n),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 ci(n)<ci(t.value);case"lessThanOrEqual":return ci(n)<=ci(t.value);case"greaterThan":return ci(n)>ci(t.value);case"greaterThanOrEqual":return ci(n)>=ci(t.value);case"between":return ci(n)>=ci(t.value)&&ci(n)<=ci(t.valueTo);default:return!0}}(e,t,i,r?.get(t.field)))):e}function ui(e,t,i){const r=new Set;let n=!1;for(const o of e){const e=o[t];if(i){const t=i(e,o);if(Array.isArray(t)){0===t.length&&(n=!0);for(const e of t)null!=e&&r.add(e)}else null!=t?r.add(t):n=!0}else null!=e&&""!==e?r.add(e):n=!0}return n&&r.add(di),[...r].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t)))}const gi="__tbw_expander";function pi(e){return e.field===gi}function fi(e){return!0===e.meta?.utility}function wi(e){return e?e.toISOString().split("T")[0]:""}function mi(e){return e?"string"==typeof e?e:"number"==typeof e?wi(new Date(e)):"":""}function bi(e,t,i,r,n,o){const{field:s,column:l}=t,a=function(e){if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-filter-item-height");if(t&&t.trim()){const e=parseFloat(t);if(!isNaN(e)&&e>0)return e}}return 28}(e),d=e=>{if(null==e)return"(Blank)";if(l.format&&!l.filterValue){const t=l.format(e,void 0);if(t)return t}return String(e)};i=i.slice().sort((e,t)=>d(e).localeCompare(d(t)));const c=document.createElement("div");c.className="tbw-filter-search";const h=document.createElement("input");h.type="text",h.placeholder="Search...",h.className="tbw-filter-search-input",h.value=o.get(s)??"",c.appendChild(h),e.appendChild(c);const u=document.createElement("div");u.className="tbw-filter-actions";const g=document.createElement("label");g.className="tbw-filter-value-item",g.style.padding="0",g.style.margin="0";const p=document.createElement("input");p.type="checkbox",p.className="tbw-filter-checkbox";const f=document.createElement("span");f.textContent="Select All",g.appendChild(p),g.appendChild(f),u.appendChild(g);const w=new Map;i.forEach(e=>{const t=null==e?"__null__":String(e);w.set(t,!r.has(e))});const m=()=>{const e=[...w.values()],t=e.every(e=>e),i=e.every(e=>!e);p.checked=t,p.indeterminate=!t&&!i};p.addEventListener("change",()=>{const e=p.checked;for(const t of w.keys())w.set(t,e);m(),R()}),m(),e.appendChild(u);const b=document.createElement("div");b.className="tbw-filter-values";const v=document.createElement("div");v.className="tbw-filter-values-spacer",b.appendChild(v);const y=document.createElement("div");y.className="tbw-filter-values-content",b.appendChild(y);let C=[];const x=(e,t)=>{const i=d(e),r=null==e?"__null__":String(e),n=document.createElement("label");n.className="tbw-filter-value-item",n.style.position="absolute",n.style.top=`calc(var(--tbw-filter-item-height, 28px) * ${t})`,n.style.left="0",n.style.right="0",n.style.boxSizing="border-box";const o=document.createElement("input");o.type="checkbox",o.className="tbw-filter-checkbox",o.checked=w.get(r)??!0,o.dataset.value=r,o.addEventListener("change",()=>{w.set(r,o.checked),m()});const s=document.createElement("span");return s.textContent=i,n.appendChild(o),n.appendChild(s),n},R=()=>{const e=C.length,t=b.clientHeight,i=b.scrollTop;if(v.style.height=e*a+"px",e<=50/3)return y.innerHTML="",y.style.transform="translateY(0px)",void C.forEach((e,t)=>{y.appendChild(x(e,t))});const r=function(e){const{totalRows:t,viewportHeight:i,scrollTop:r,rowHeight:n,overscan:o}=e,s=Math.ceil(i/n);let l=Math.floor(r/n)-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*n,totalHeight:t*n}}({totalRows:e,viewportHeight:t,scrollTop:i,rowHeight:a,overscan:3});y.style.transform=`translateY(${r.offsetY}px)`,y.innerHTML="";for(let n=r.start;n<r.end;n++)y.appendChild(x(C[n],n-r.start))},E=e=>{const t=n.caseSensitive??!1,r=t?e:e.toLowerCase();if(C=i.filter(i=>{const n=d(i),o=t?n:n.toLowerCase();return!e||o.includes(r)}),C.sort((e,t)=>{const i=null==e?"__null__":String(e),r=null==t?"__null__":String(t),n=w.get(i)??!0;return n!==(w.get(r)??!0)?n?-1:1:d(e).localeCompare(d(t))}),0===C.length){v.style.height="0px",y.innerHTML="";const e=document.createElement("div");return e.className="tbw-filter-no-match",e.textContent="No matching values",void y.appendChild(e)}R()};let S;b.addEventListener("scroll",()=>{C.length>0&&R()},{passive:!0}),E(h.value),e.appendChild(b),h.addEventListener("input",()=>{clearTimeout(S),S=setTimeout(()=>{o.set(s,h.value),E(h.value)},n.debounceMs??150)});const _=document.createElement("div");_.className="tbw-filter-buttons";const A=document.createElement("button");A.className="tbw-filter-apply-btn",A.textContent="Apply",A.addEventListener("click",()=>{const e=[];for(const[t,r]of w)if(!r)if("__null__"===t)e.push(null);else{const r=i.find(e=>String(e)===t);e.push(void 0!==r?r:t)}t.applySetFilter(e)}),_.appendChild(A);const k=document.createElement("button");k.className="tbw-filter-clear-btn",k.textContent="Clear Filter",k.addEventListener("click",()=>{t.clearFilter()}),_.appendChild(k),e.appendChild(_)}function vi(e,t){if("number"==typeof e)return e;if("string"==typeof e){const i=parseFloat(e);return isNaN(i)?t:i}return t}class yi extends Ct{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;computeSelected(){const e={},t=[];for(const[i,r]of this.filters)if("set"===r.type)if("in"===r.operator&&Array.isArray(r.value))e[i]=r.value;else if("notIn"===r.operator){const e=this.grid.effectiveConfig?.columns?.find(e=>e.field===i);t.push({field:i,filterValue:e?.filterValue})}if(t.length>0){const i=function(e,t){const i=new Map;for(const{field:n,filterValue:o}of t)i.set(n,{values:new Set,hasBlank:!1,hasExtractor:!!o});for(const n of e)for(const{field:e,filterValue:r}of t){const t=i.get(e),o=n[e];if(r){const e=r(o,n);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 r=new Map;for(const[n,{values:o,hasBlank:s}]of i)s&&o.add(di),r.set(n,[...o].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t))));return r}(this.sourceRows,t);for(const{field:r}of t){const t=this.excludedValues.get(r),n=i.get(r)??[];e[r]=t?n.filter(e=>!t.has(e)):n}}return e}syncExcludedValues(e,t){if(t)if("set"===t.type&&"notIn"===t.operator&&Array.isArray(t.value))this.excludedValues.set(e,new Set(t.value));else if("set"===t.type&&"in"===t.operator&&Array.isArray(t.value)){const i=this.sourceRows;if(!i||0===i.length)return void this.excludedValues.delete(e);const r=t.value,n=new Set(r.map(e=>null==e?di:e)),o=this.getUniqueValues(e),s=new Set(o.filter(e=>!n.has(e)));this.excludedValues.set(e,s)}else"set"===t.type&&this.excludedValues.delete(e);else 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 r=[],n=this.isFieldFiltered(i.field),o=this.filters.size>0;return n&&r.push({id:"filtering/clear-column-filter",label:"Clear Filter",icon:"✕",order:20,action:()=>this.clearFieldFilter(i.field)}),o&&r.push({id:"filtering/clear-all-filters",label:"Clear All Filters",icon:"✕",order:21,disabled:!o,action:()=>this.clearAllFilters()}),r.length>0?r: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=(r=t,JSON.stringify(r.map(e=>({field:e.field,operator:e.operator,value:e.value,valueTo:e.valueTo}))));var r;const n={len:e.length,first:e[0],mid:e[Math.floor(e.length/2)],last:e[e.length-1]},o=null!=this.cachedInputSpot&&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=hi([...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(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(fi(i))return;const r=i.field;if(!r)return;const n=this.filters.has(r);let o=e.querySelector(".tbw-filter-btn");if(o){const t=o.classList.contains("active");if(o.classList.toggle("active",n),e.classList.toggle("filtered",n),n?e.setAttribute("aria-description","Filtered"):e.removeAttribute("aria-description"),t!==n){const e=n?"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??r}`);const s=n?"filterActive":"filter";this.setIcon(o,this.resolveIcon(s)),n&&(o.classList.add("active"),e.classList.add("filtered"),e.setAttribute("aria-description","Filtered")),o.addEventListener("click",e=>{e.stopPropagation(),this.toggleFilterPanel(r,i,o)});const l=e.querySelector(".resize-handle");l?e.insertBefore(o,l):e.appendChild(o)})}setFilter(e,i,r){if(null===i)this.filters.delete(e),this.syncExcludedValues(e,null);else{const t={...i,field:e};this.filters.set(e,t),this.syncExcludedValues(e,t)}if(this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,!r?.silent){this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.();const r=this.grid.effectiveConfig?.columns?.find(t=>t.field===e)?.header??e;t(this.gridElement,null===i?`Filter cleared from ${r}`:`Filter applied on ${r}`)}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,t){this.filters.clear(),this.excludedValues.clear();for(const i of e)this.filters.set(i.field,i),this.syncExcludedValues(i.field,i);this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,t?.silent||(this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.()),this.emitPluginEvent("filter-applied",{filters:[...this.filters.values()]}),this.requestRender()}clearAllFilters(e){this.filters.clear(),this.excludedValues.clear(),this.searchText.clear(),this.applyFiltersInternal(e?.silent),e?.silent||t(this.gridElement,"All filters cleared")}clearFieldFilter(e,i){if(this.filters.delete(e),this.excludedValues.delete(e),this.searchText.delete(e),this.applyFiltersInternal(i?.silent),!i?.silent){const i=this.grid.effectiveConfig?.columns?.find(t=>t.field===e)?.header??e;t(this.gridElement,`Filter cleared from ${i}`)}}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 ui(this.sourceRows,e,i)}copyGridThemeContext(e){const t=this.gridElement;if(!t)return;for(const r of t.classList)r.startsWith("tbw-")||"selecting"===r||e.classList.add(r);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 r=document.createElement("div");if(r.className="tbw-filter-panel",this.copyGridThemeContext(r),this.isAnimationEnabled&&r.classList.add("tbw-filter-panel-animated"),this.panelElement=r,this.openPanelField=e,this.config.valuesHandler)return r.innerHTML='<div class="tbw-filter-loading">Loading...</div>',document.body.appendChild(r),this.positionPanel(r,i),this.setupPanelCloseHandler(r,i),void this.config.valuesHandler(e,t).then(i=>{this.openPanelField===e&&this.panelElement&&(r.innerHTML="",this.renderPanelContent(e,t,r,i))});const n=ui(this.sourceRows,e,t.filterValue);document.body.appendChild(r),this.positionPanel(r,i),this.renderPanelContent(e,t,r,n),this.setupPanelCloseHandler(r,i)}renderPanelContent(e,t,i,r){const n=this.filters.get(e);if("in"===n?.operator&&"set"===n.type&&Array.isArray(n.value)&&!this.excludedValues.has(e)){const t=n.value,i=new Set(t.map(e=>null==e?di:e)),o=new Set(r.filter(e=>!i.has(e)));this.excludedValues.set(e,o)}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:r,excludedValues:o,searchText:s,currentFilter:this.filters.get(e),applySetFilter:(t,i)=>{this.applySetFilter(e,t,i),this.closeFilterPanel()},applyTextFilter:(t,i,r)=>{this.applyTextFilter(e,t,i,r),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 e=this.grid.effectiveConfig.typeDefaults?.[t.type];e?.filterPanelRenderer&&(e.filterPanelRenderer(i,l),a=i.children.length>0)}if(!a){const e=t.type;"number"===e?function(e,t,i,r){const{field:n,column:o}=t,s=o.filterParams,l=o.editorParams,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=vi(s?.min??l?.min,d),u=vi(s?.max??l?.max,c),g=s?.step??l?.step??1,p=r.get(n);let f=h,w=u;const m="blank"===p?.operator;"between"===p?.operator?(f=vi(p.value,h),w=vi(p.valueTo,u)):"greaterThanOrEqual"===p?.operator?f=vi(p.value,h):"lessThanOrEqual"===p?.operator&&(w=vi(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 R=document.createElement("div");R.className="tbw-filter-range-group";const E=document.createElement("label");E.textContent="Max",E.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),R.appendChild(E),R.appendChild(S),b.appendChild(R),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 M=document.createElement("input");M.type="range",M.className="tbw-filter-range-thumb tbw-filter-range-thumb-max",M.min=String(h),M.max=String(u),M.step=String(g),M.value=String(w),_.appendChild(A),_.appendChild(k),_.appendChild(T),_.appendChild(M),e.appendChild(_);const L=document.createElement("label");L.className="tbw-filter-blank-option";const I=document.createElement("input");I.type="checkbox",I.className="tbw-filter-blank-checkbox",I.checked=m;const P=document.createTextNode("Blank");L.appendChild(I),L.appendChild(P);const H=e=>{C.disabled=e,S.disabled=e,T.disabled=e,M.disabled=e,b.classList.toggle("tbw-filter-disabled",e),_.classList.toggle("tbw-filter-disabled",e)};H(m),I.addEventListener("change",()=>{H(I.checked)}),e.appendChild(L);const D=()=>{const e=parseFloat(T.value),t=parseFloat(M.value),i=u-h,r=(e-h)/i*100,n=(t-h)/i*100;k.style.left=`${r}%`,k.style.width=n-r+"%"};T.addEventListener("input",()=>{const e=Math.min(parseFloat(T.value),parseFloat(M.value));T.value=String(e),C.value=String(e),D()}),M.addEventListener("input",()=>{const e=Math.max(parseFloat(M.value),parseFloat(T.value));M.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))),M.value=String(e),D()}),D();const F=document.createElement("div");F.className="tbw-filter-buttons";const z=document.createElement("button");z.className="tbw-filter-apply-btn",z.textContent="Apply",z.addEventListener("click",()=>{if(I.checked)return void t.applyTextFilter("blank","");const e=parseFloat(C.value),i=parseFloat(S.value);t.applyTextFilter("between",e,i)}),F.appendChild(z);const q=document.createElement("button");q.className="tbw-filter-clear-btn",q.textContent="Clear Filter",q.addEventListener("click",()=>{t.clearFilter()}),F.appendChild(q),e.appendChild(F)}(i,l,r,this.filters):"date"===e?function(e,t,i,r){const{field:n,column:o}=t,s=o.filterParams,l=o.editorParams,a=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())),d=a.length>0?new Date(Math.min(...a.map(e=>e.getTime()))):null,c=a.length>0?new Date(Math.max(...a.map(e=>e.getTime()))):null,h=mi(s?.min)||mi(l?.min)||wi(d),u=mi(s?.max)||mi(l?.max)||wi(c),g=r.get(n);let p="",f="";const w="blank"===g?.operator;"between"===g?.operator?(p=mi(g.value)||"",f=mi(g.valueTo)||""):"greaterThanOrEqual"===g?.operator?p=mi(g.value)||"":"lessThanOrEqual"===g?.operator&&(f=mi(g.value)||"");const m=document.createElement("div");m.className="tbw-filter-date-range";const b=document.createElement("div");b.className="tbw-filter-date-group";const v=document.createElement("label");v.textContent="From",v.className="tbw-filter-range-label";const y=document.createElement("input");y.type="date",y.className="tbw-filter-date-input",h&&(y.min=h),u&&(y.max=u),y.value=p,b.appendChild(v),b.appendChild(y),m.appendChild(b);const C=document.createElement("span");C.className="tbw-filter-range-separator",C.textContent="–",m.appendChild(C);const x=document.createElement("div");x.className="tbw-filter-date-group";const R=document.createElement("label");R.textContent="To",R.className="tbw-filter-range-label";const E=document.createElement("input");E.type="date",E.className="tbw-filter-date-input",h&&(E.min=h),u&&(E.max=u),E.value=f,x.appendChild(R),x.appendChild(E),m.appendChild(x),e.appendChild(m);const S=document.createElement("label");S.className="tbw-filter-blank-option";const _=document.createElement("input");_.type="checkbox",_.className="tbw-filter-blank-checkbox",_.checked=w;const A=document.createTextNode("Show only blank");S.appendChild(_),S.appendChild(A);const k=e=>{y.disabled=e,E.disabled=e,m.classList.toggle("tbw-filter-disabled",e)};k(w),_.addEventListener("change",()=>{k(_.checked)}),e.appendChild(S);const T=document.createElement("div");T.className="tbw-filter-buttons";const M=document.createElement("button");M.className="tbw-filter-apply-btn",M.textContent="Apply",M.addEventListener("click",()=>{if(_.checked)return void t.applyTextFilter("blank","");const e=y.value,i=E.value;e&&i?t.applyTextFilter("between",e,i):e?t.applyTextFilter("greaterThanOrEqual",e):i?t.applyTextFilter("lessThanOrEqual",i):t.clearFilter()}),T.appendChild(M);const L=document.createElement("button");L.className="tbw-filter-clear-btn",L.textContent="Clear Filter",L.addEventListener("click",()=>{t.clearFilter()}),T.appendChild(L),e.appendChild(T)}(i,l,r,this.filters):bi(i,l,r,o,{caseSensitive:this.config.caseSensitive,debounceMs:this.config.debounceMs},this.searchText)}}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===yi.supportsAnchorPositioning&&(yi.supportsAnchorPositioning=CSS.supports("anchor-name","--test")),yi.supportsAnchorPositioning}positionPanel(e,t){const i=t.closest(".cell")??t;if(i.style.anchorName="--tbw-filter-anchor",this.panelAnchorElement=i,yi.checkAnchorPositioningSupport())return void requestAnimationFrame(()=>{const t=e.getBoundingClientRect(),r=i.getBoundingClientRect();t.top<r.top&&e.classList.add("tbw-filter-panel-above")});const r=i.getBoundingClientRect();e.style.position="fixed",e.style.top=`${r.bottom+4}px`,e.style.left=`${r.left}px`,requestAnimationFrame(()=>{const t=e.getBoundingClientRect();t.right>window.innerWidth-8&&(e.style.left=r.right-t.width+"px"),t.bottom>window.innerHeight-8&&(e.style.top=r.top-t.height-4+"px",e.classList.add("tbw-filter-panel-above"))})}applySetFilter(e,t,i){if(this.excludedValues.set(e,new Set(t)),0===t.length)this.filters.delete(e);else{const r=this.filters.get(e);if("in"===r?.operator){const r=this.getUniqueValues(e),n=new Set(t),o=r.filter(e=>!n.has(e));this.filters.set(e,{field:e,type:"set",operator:"in",value:o,...void 0!==i&&{valueTo:i}})}else this.filters.set(e,{field:e,type:"set",operator:"notIn",value:t,...void 0!==i&&{valueTo:i}})}this.applyFiltersInternal()}applyTextFilter(e,t,i,r){this.filters.set(e,{field:e,type:"text",operator:t,value:i,valueTo:r}),this.applyFiltersInternal()}applyFiltersInternal(e){this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null;const t=[...this.filters.values()];if(this.config.filterHandler){this.gridElement.setAttribute("aria-busy","true");const i=this.config.filterHandler(t,this.sourceRows),r=i=>{this.gridElement.removeAttribute("aria-busy"),this.cachedResult=i,this.grid.rows=i,e||(this.emit("filter-change",{filters:t,filteredRowCount:i.length,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.()),this.emitPluginEvent("filter-applied",{filters:t}),this.requestRender()};return void(i&&"function"==typeof i.then?i.then(r):r(i))}e||(this.emit("filter-change",{filters:t,filteredRowCount:0,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.()),this.emitPluginEvent("filter-applied",{filters:t}),this.requestRender()}getColumnState(e){if(!this.config.trackColumnState)return;const t=this.filters.get(e);return t?{filter:{type:t.type,operator:t.operator,value:t.value,valueTo:t.valueTo}}:void 0}applyColumnState(e,t){if(!this.config.trackColumnState)return;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 Ci(e){if(!e.length)return[];const t=[],i=new Map,r=(e,i)=>{if(!i.length)return;const r=t[t.length-1];r&&r.implicit&&r.firstIndex+r.columns.length===e?r.columns.push(...i):t.push({id:"__implicit__"+e,label:void 0,columns:i,firstIndex:e,implicit:!0})};let n=[],o=0;return e.forEach((e,s)=>{const l=e.group;if(!l)return 0===n.length&&(o=s),void n.push(e);n.length&&(r(o,n.slice()),n=[]);const a="string"==typeof l?l:l.id,d="string"==typeof l?void 0:l.label;d&&!i.has(a)&&i.set(a,d);const c=i.get(a)??d,h=t[t.length-1];h&&!h.implicit&&h.id===a?h.columns.push(e):t.push({id:a,label:c,columns:[e],firstIndex:s})}),n.length&&r(o,n),1===t.length&&t[0].implicit&&t[0].columns.length===e.length?[]:t}function xi(e,t){const i=e.columns[0],r=e.columns[e.columns.length-1],n=i?t.findIndex(e=>e.field===i.field):-1,o=r?t.findIndex(e=>e.field===r.field):-1;return-1!==n&&-1!==o?[n,o]:null}function Ri(e){const t=new Set;for(let i=0;i<e.length;i++){if(!String(e[i].id).startsWith("__implicit__"))continue;if(!e[i].columns.every(e=>e.field?.startsWith("__tbw_")))continue;let r=null;for(let t=i-1;t>=0;t--)if(!String(e[t].id).startsWith("__implicit__")){r=e[t].id;break}let n=null;for(let t=i+1;t<e.length;t++)if(!String(e[t].id).startsWith("__implicit__")){n=e[t].id;break}r&&n&&r===n&&t.add(String(e[i].id))}return t}function Ei(e,t){const i=[];for(const r of e){if(String(r.id).startsWith("__implicit__")&&t.has(String(r.id)))continue;const e=i[i.length-1];e&&!String(r.id).startsWith("__implicit__")&&e.id===r.id?i[i.length-1]={...e,columns:[...e.columns,...r.columns]}:i.push({...r,columns:[...r.columns]})}return i}const Si={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]},_i=new Map,Ai={register(e,t){_i.set(e,t)},unregister(e){_i.delete(e)},get(e){if(void 0!==e)return"function"==typeof e?e:_i.get(e)??Si[e]},run(e,t,i,r){const n=this.get(e);return n?n(t,i,r):void 0},has:e=>_i.has(e)||e in Si,list:()=>[...Object.keys(Si),..._i.keys()]},ki={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};Ai.register.bind(Ai),Ai.unregister.bind(Ai);const Ti=Ai.get.bind(Ai),Mi=Ai.run.bind(Ai);function Li({rows:e,config:t,expanded:i,initialExpanded:r}){const n=t.groupOn;if("function"!=typeof n)return[];const o={key:"__root__",value:null,depth:-1,rows:[],children:new Map};if(e.forEach(e=>{let t=n(e);null==t||!1===t?t=["__ungrouped__"]:Array.isArray(t)||(t=[t]);let i=o;t.forEach((e,t)=>{const r=null==e?"∅":String(e),n="__root__"===i.key?r:i.key+"||"+r;let o=i.children.get(r);o||(o={key:n,value:e,depth:t,rows:[],children:new Map,parent:i},i.children.set(r,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,...r??[]]),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}Ai.list.bind(Ai);function Ii(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}function Pi(e,t,i,r){const n=document.createElement("div");n.className="master-detail-row",n.setAttribute("data-detail-for",String(t)),n.setAttribute("role","row");const o=document.createElement("div");o.className="master-detail-cell",o.setAttribute("role","cell"),o.style.gridColumn=`1 / ${r+1}`;const s=i(e,t);return"string"==typeof s?o.innerHTML=s:s instanceof HTMLElement&&o.appendChild(s),n.appendChild(o),n}class Hi extends Ct{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 .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#bt(){return this.grid}get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,animation:"slide"}}attach(e){super.attach(e),this.parseLightDomDetail()}parseLightDomDetail(){const e=this.gridElement;if(!e)return;const t=e.querySelector("tbw-grid-detail");if(!t)return;const i=this.#bt.__frameworkAdapter;if(i?.parseDetailElement){const e=i.parseDetailElement(t);if(e)return void(this.config={...this.config,detailRenderer:e})}const r=t.getAttribute("animation"),n=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!==r&&(a.animation="false"!==r&&r),null!==n&&(a.showExpandColumn="false"!==n),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)=>T(M(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 r=!1;const n=()=>{r||(r=!0,e.classList.remove("tbw-expanding"),void 0!==t&&void 0!==i&&this.#vt(e,t,i))};return e.addEventListener("animationend",n,{once:!0}),setTimeout(n,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)}#vt(e,t,i){if(!e.isConnected)return;const r=e.offsetHeight;if(r>0){const e=this.measuredDetailHeights.get(t);this.measuredDetailHeights.set(t,r),e!==r&&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:Hi.DEFAULT_DETAIL_HEIGHT}toggleAndEmit(e,t){if(e?.__isGroupRow)return;this.expandedRows=Ii(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(pi)}(t);if(i)return t;const r=(n=this.name,{field:gi,header:"",width:32,resizable:!1,sortable:!1,filterable:!1,meta:{lockPosition:!0,suppressMovable:!0,expanderColumn:!0,expanderPlugin:n,utility:!0}});var n;return r.viewRenderer=e=>{const{row:t}=e,i=this.expandedRows.has(t),r=document.createElement("span");r.className="master-detail-expander expander-cell";const n=document.createElement("span");return n.className="master-detail-toggle"+(i?" expanded":""),this.setIcon(n,this.resolveIcon(i?"collapse":"expand")),n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.setAttribute("aria-expanded",String(i)),n.setAttribute("aria-label",i?"Collapse details":"Expand details"),r.appendChild(n),r},[r,...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.#yt())}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusCol,i=this.grid._focusRow,r=this.visibleColumns[t];if(!r||!pi(r))return;const n=this.rows[i];return n?(e.preventDefault(),this.toggleAndEmit(n,i),this.requestRenderWithFocus(),!0):void 0}afterRender(){this.#Ct(),this.#yt()}#Ct(){const e=this.gridElement?.querySelector('.header-row .cell[data-field="__tbw_expander"]');if(!e)return;const t=parseInt(e.getAttribute("data-col")||"0",10),i=e.nextElementSibling;i&&(i.style.gridColumn=`${t+1} / ${t+3}`)}onScrollRender(){this.config.detailRenderer&&0!==this.expandedRows.size&&this.#yt()}#yt(){if(!this.config.detailRenderer)return;const e=this.gridElement?.querySelector(".rows");if(!e)return;const t=this.grid,i=t._rowPool,r=t._virtualization?.start??0,n=t._virtualization?.end??0,o=this.columns.length,s=r,l=n,a=new Map;if(i){const t=Math.min(i.length,l-s);for(let r=0;r<t;r++){const t=i[r];t.parentNode===e&&a.set(s+r,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.#bt.__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=Pi(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 r=this.rowsToAnimate.has(e);r&&this.rowsToAnimate.delete(e);r&&this.animateExpand(i,e,d)||requestAnimationFrame(()=>{this.#vt(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 r=this.rows.indexOf(i);r>=0&&r<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 r=this.grid?._virtualization?.positionCache;let n=e;if(r&&r.length>0)for(const o of this.expandedRows){const i=this.rows.indexOf(o);if(i<0||i>=e)continue;r[i].offset+r[i].height>t&&i<n&&(n=i)}else{const r=[];for(const e of this.expandedRows){const t=this.rows.indexOf(e);t>=0&&r.push({index:t,row:e})}r.sort((e,t)=>e.index-t.index);let o=0;for(const{index:s,row:l}of r){const r=s*i+o,a=this.getDetailHeight(l);o+=a,s>=e||r+i+a>t&&s<n&&(n=s)}}return n}expand(e){const t=this.rows[e];t&&!t.__isGroupRow&&(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&&!t.__isGroupRow&&(this.expandedRows=Ii(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)e?.__isGroupRow||(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.#bt;"function"==typeof e.refreshColumns?e.refreshColumns():this.requestRender()}}}function Di(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 Fi(e,t){const i=e.findIndex(e=>e.field===t);return i>=0?i+1:void 0}function zi(e,t){return e.find(e=>e.field===t)?.direction}function qi(e){return e.pinned??e.sticky??e.meta?.pinned??e.meta?.sticky}function Oi(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 Ni(e,t){const i=qi(e);return!!i&&"left"===Oi(i,t)}function Gi(e,t){const i=qi(e);return!!i&&"right"===Oi(i,t)}function $i(e){return e.some(e=>null!=qi(e))}function Wi(e,t){const i={addGroupEnd:new Set,removeGroupEnd:new Set},r=Array.from(e.querySelectorAll(".header-row .cell"));if(!r.length)return i;const n=ee(e);let o=0;for(const a of t)if(Ni(a,n)){const t=r.find(e=>e.getAttribute("data-field")===a.field);t&&(t.classList.add("sticky-left"),t.style.position="sticky",t.style.left=o+"px",e.querySelectorAll(`.data-grid-row .cell[data-field="${a.field}"]`).forEach(e=>{e.classList.add("sticky-left"),e.style.position="sticky",e.style.left=o+"px"}),o+=t.offsetWidth)}let s=0;for(const a of[...t].reverse())if(Gi(a,n)){const t=r.find(e=>e.getAttribute("data-field")===a.field);t&&(t.classList.add("sticky-right"),t.style.position="sticky",t.style.right=s+"px",e.querySelectorAll(`.data-grid-row .cell[data-field="${a.field}"]`).forEach(e=>{e.classList.add("sticky-right"),e.style.position="sticky",e.style.right=s+"px"}),s+=t.offsetWidth)}const l=function(e,t,i,r){const n={addGroupEnd:new Set,removeGroupEnd:new Set},o=Array.from(e.querySelectorAll(".header-group-row .header-group-cell"));if(!o.length)return n;for(const s of o){const e=s.style.gridColumn;if(!e)continue;const o=e.match(/^(\d+)\s*\/\s*span\s+(\d+)$/);if(!o)continue;const l=parseInt(o[1],10)-1,a=l+parseInt(o[2],10)-1,d=t.slice(l,a+1);if(!d.length)continue;const c=d.every(e=>Ni(e,r)),h=d.every(e=>Gi(e,r));if(c){const e=d[0].field,t=i.find(t=>t.getAttribute("data-field")===e);t&&(s.classList.add("sticky-left"),s.style.position="sticky",s.style.left=t.style.left)}else if(h){const e=d[d.length-1].field,t=i.find(t=>t.getAttribute("data-field")===e);t&&(s.classList.add("sticky-right"),s.style.position="sticky",s.style.right=t.style.right)}else s.classList.contains("implicit-group")&&Vi(s,d,l,i,r,n)}return n}(e,t,r,n);if(l.addGroupEnd.size>0||l.removeGroupEnd.size>0){for(const t of l.addGroupEnd){const i=r.find(e=>e.getAttribute("data-field")===t);i&&i.classList.add("group-end"),e.querySelectorAll(`.data-grid-row .cell[data-field="${t}"]`).forEach(e=>{e.classList.add("group-end")})}for(const t of l.removeGroupEnd){const i=r.find(e=>e.getAttribute("data-field")===t);i&&i.classList.remove("group-end"),e.querySelectorAll(`.data-grid-row .cell[data-field="${t}"]`).forEach(e=>{e.classList.remove("group-end")})}}return l}function Bi(e,t){return Ni(e,t)?"left":Gi(e,t)?"right":"none"}function Vi(e,t,i,r,n,o){const s=[];for(let d=0;d<t.length;d++){const e=Bi(t[d],n),r=s[s.length-1];r&&r.state===e?r.cols.push(t[d]):s.push({state:e,cols:[t[d]],colStart:i+d})}if(s.length<=1)return;const l=e.parentElement;if(!l)return;const a=e.nextSibling;l.removeChild(e);for(const d of s){const t=document.createElement("div");if(t.className=e.className,t.setAttribute("data-group",e.getAttribute("data-group")||""),t.style.gridColumn=`${d.colStart+1} / span ${d.cols.length}`,"left"===d.state){const e=d.cols[0].field,i=r.find(t=>t.getAttribute("data-field")===e);i&&(t.classList.add("sticky-left"),t.style.position="sticky",t.style.left=i.style.left)}else if("right"===d.state){const e=d.cols[d.cols.length-1].field,i=r.find(t=>t.getAttribute("data-field")===e);i&&(t.classList.add("sticky-right"),t.style.position="sticky",t.style.right=i.style.right)}else if("none"===d.state){d.cols.every(e=>String(e.field||"").startsWith("__tbw_"))&&(t.style.borderRightStyle="none")}a?l.insertBefore(t,a):l.appendChild(t)}for(let d=0;d<s.length;d++){const e=s[d],t=s[d+1];if("none"!==e.state&&t&&"none"===t.state){const t=e.cols[e.cols.length-1].field;t&&o.addGroupEnd.add(t)}if("none"===e.state){if(e.cols.every(e=>String(e.field||"").startsWith("__tbw_"))){const t=e.cols[e.cols.length-1].field;t&&o.removeGroupEnd.add(t)}}}}function Ki(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 Ui="canMoveColumn";function ji(e,t){const i=document.createElement("div");i.className="tbw-pinned-rows",i.setAttribute("role","presentation"),i.setAttribute("aria-live","polite");const r=document.createElement("div");r.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",!1!==e.showRowCount){const e=document.createElement("span");e.className="tbw-status-panel tbw-status-panel-row-count",e.textContent=`Total: ${t.totalRows} rows`,r.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}`,r.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=er(s,t);switch(s.position){case"left":r.appendChild(e);break;case"center":n.appendChild(e);break;case"right":o.appendChild(e)}}return i.appendChild(r),i.appendChild(n),i.appendChild(o),i}function Yi(e){const t=document.createElement("div");return t.className=`tbw-aggregation-rows tbw-aggregation-rows-${e}`,t.setAttribute("role","presentation"),t}function Xi(e,t,i,r,n=!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??n?Zi(t,o,i,r):Qi(t,o,i,r),e.appendChild(t)}}function Zi(e,t,i,r){const n=document.createElement("div");n.className="tbw-aggregation-cell tbw-aggregation-cell-full",n.style.gridColumn="1 / -1";const o="function"==typeof t.label?t.label(r,i):t.label;if(o){const e=document.createElement("span");e.className="tbw-aggregation-label",e.textContent=o,n.appendChild(e)}const s=function(e,t,i){const r=e.aggregators&&Object.keys(e.aggregators).length>0,n=e.cells&&Object.keys(e.cells).length>0;if(!r&&!n)return null;const o=document.createElement("span");o.className="tbw-aggregation-aggregates";for(const s of t){const{value:t,formatter:r}=Ji(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,n=r?r(t,s.field,s):String(t);e.textContent=`${i}: ${n}`,o.appendChild(e)}}return o.children.length>0?o:null}(t,i,r);s&&n.appendChild(s),e.appendChild(n)}function Qi(e,t,i,r){for(const o of i){const i=document.createElement("div");i.className="tbw-aggregation-cell",i.setAttribute("data-field",o.field);const{value:n,formatter:s}=Ji(t,o,r);i.textContent=null!=n?s?s(n,o.field,o):String(n):"",e.appendChild(i)}const n="function"==typeof t.label?t.label(r,i):t.label;if(n){const t=document.createElement("span");t.className="tbw-aggregation-label",t.textContent=n,e.appendChild(t)}}function Ji(e,t,i){let r,n;const o=e.aggregators?.[t.field];if(o)if("object"==typeof(s=o)&&null!==s&&"aggFunc"in s){const e=Ti(o.aggFunc);e&&(r=e(i,t.field,t)),n=o.formatter}else{const e=Ti(o);e&&(r=e(i,t.field,t))}else if(e.cells&&Object.prototype.hasOwnProperty.call(e.cells,t.field)){const n=e.cells[t.field];r="function"==typeof n?n(i,t.field,t):n}var s;return{value:r,formatter:n}}function er(e,t){const i=document.createElement("div");i.className="tbw-status-panel tbw-status-panel-custom",i.id=`status-panel-${e.id}`;const r=e.render(t);return"string"==typeof r?i.innerHTML=r:i.appendChild(r),i}function tr(e,t,i,r,n){return{totalRows:e.length,filteredRows:n?.cachedResult?.length??e.length,selectedRows:r?.selected?.size??0,columns:t,rows:e,grid:i}}const ir=function(e){return ki[e]??ki.sum};function rr(e,t){return[...e,t].join("|")}function nr(e,t){const i=t.rowGroupFields??[],r=t.columnGroupFields??[],n=t.valueFields??[],o=function(e,t){if(0===t.length)return["value"];const i=new Set;for(const r of e){const e=t.map(e=>String(r[e]??"")).join("|");i.add(e)}return[...i].sort()}(e,r),s=or(e,i,r,o,n,0,""),l=function(e,t,i){const r={};function n(e){for(const o of e)if(o.isGroup&&o.children?.length)o.children&&n(o.children);else for(const e of t)for(const t of i){const i=rr([e],t.field);r[i]=(r[i]??0)+(o.values[i]??0)}}return n(e),r}(s,o,n);return{rows:s,columnKeys:o,totals:l,grandTotal:Object.values(l).reduce((e,t)=>e+t,0)}}function or(e,t,i,r,n,o,s){const l=[];if(0===t.length){const t=sr(e,i,r,n),a=lr(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 r of e){const e=String(r[t]??""),n=i.get(e);n?n.push(r):i.set(e,[r])}return i}(e,a);for(const[u,g]of h){const e=s?`${s}|${u}`:u,t=sr(g,i,r,n),a=lr(t);let h;c&&(h=or(g,d,i,r,n,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 sr(e,t,i,r){const n={};for(const o of i)for(const i of r){const r=(t.length>0?e.filter(e=>t.map(t=>String(e[t]??"")).join("|")===o):e).map(e=>Number(e[i.field])||0),s=ir(i.aggFunc),l=r.length>0?s(r):null;n[rr([o],i.field)]=l}return n}function lr(e){let t=0;for(const i of Object.values(e))t+=i??0;return t}const ar=["sum","avg","count","min","max","first","last"];function dr(e,t,i,r){const n=new AbortController,o={config:t,callbacks:r,signal:n.signal},s=document.createElement("div");return s.className="tbw-pivot-panel",s.appendChild(cr("Options",()=>function(e,t){const{config:i,callbacks:r,signal:n}=t,o=document.createElement("div");return o.className="tbw-pivot-options",o.appendChild(pr("Enable Pivot View",e,e=>{r.onTogglePivot(e)},n)),o.appendChild(pr("Show Row Totals",i.showTotals??!0,e=>{r.onOptionChange("showTotals",e)},n)),o.appendChild(pr("Show Grand Total",i.showGrandTotal??!0,e=>{r.onOptionChange("showGrandTotal",e)},n)),o}(i,o))),s.appendChild(cr("Row Groups",()=>hr("rowGroups",o))),s.appendChild(cr("Column Groups",()=>hr("columnGroups",o))),s.appendChild(cr("Values",()=>function(e){const{config:t,callbacks:i,signal:r}=e,n=document.createElement("div");n.className="tbw-pivot-drop-zone tbw-pivot-values-zone",n.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",n.appendChild(e)}else for(const s of o)n.appendChild(gr(s,e));return n.addEventListener("dragover",e=>{e.preventDefault(),n.classList.add("drag-over")},{signal:r}),n.addEventListener("dragleave",()=>{n.classList.remove("drag-over")},{signal:r}),n.addEventListener("drop",e=>{e.preventDefault(),n.classList.remove("drag-over");const t=e.dataTransfer?.getData("text/plain");t&&i.onAddValueField(t,"sum")},{signal:r}),n}(o))),s.appendChild(cr("Available Fields",()=>function(e){const{config:t,callbacks:i,signal:r}=e,n=document.createElement("div");n.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",n.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:r}),e.addEventListener("dragend",()=>{e.classList.remove("dragging")},{signal:r}),n.appendChild(e)}return n}(o))),e.appendChild(s),()=>{n.abort(),s.remove()}}function cr(e,t){const i=document.createElement("div");i.className="tbw-pivot-section";const r=document.createElement("div");r.className="tbw-pivot-section-header",r.textContent=e;const n=document.createElement("div");return n.className="tbw-pivot-section-content",n.appendChild(t()),i.appendChild(r),i.appendChild(n),i}function hr(e,t){const{config:i,callbacks:r,signal:n}=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(ur(l,e,t));return o.addEventListener("dragover",e=>{e.preventDefault(),o.classList.add("drag-over")},{signal:n}),o.addEventListener("dragleave",()=>{o.classList.remove("drag-over")},{signal:n}),o.addEventListener("drop",t=>{t.preventDefault(),o.classList.remove("drag-over");const i=t.dataTransfer?.getData("text/plain");i&&r.onAddFieldToZone(i,e)},{signal:n}),o}function ur(e,t,i){const{callbacks:r,signal:n}=i,o=document.createElement("div");o.className="tbw-pivot-field-chip",o.draggable=!0;const s=r.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(),r.onRemoveFieldFromZone(e,t)},{signal:n}),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:n}),o.addEventListener("dragend",()=>{o.classList.remove("dragging")},{signal:n}),o}function gr(e,t){const{callbacks:i,signal:r}=t,n=document.createElement("div");n.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 ar){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:r});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:r}),s.appendChild(l),s.appendChild(a),n.appendChild(s),n.appendChild(d),n}function pr(e,t,i,r){const n=document.createElement("label");n.className="tbw-pivot-checkbox";const o=document.createElement("input");o.type="checkbox",o.checked=t,o.addEventListener("change",()=>i(o.checked),{signal:r});const s=document.createElement("span");return s.textContent=e,n.appendChild(o),n.appendChild(s),n}class fr extends Ct{static manifest={incompatibleWith:[{name:"groupingRows",reason:"PivotPlugin creates its own aggregated row and column structure. Row grouping cannot be applied on top of pivot-generated rows."},{name:"tree",reason:"PivotPlugin replaces the entire row and column structure with aggregated pivot data. Tree hierarchy cannot coexist with pivot aggregation."},{name:"serverSide",reason:"PivotPlugin requires the full dataset to compute aggregations. ServerSidePlugin lazy-loads rows in blocks, so pivot aggregation cannot be performed client-side."}]};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:fr.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=nr(e,this.config),0===this.expandedKeys.size&&this.defaultExpanded&&!this.userHasToggledExpand&&this.expandAllKeys();const i=this.config.indentWidth??20,r=function(e,t,i=!0){const r=[];function n(e){r.push(e);const o=t?t.has(e.rowKey):i;if(e.children&&o)for(const t of e.children)n(t)}for(const o of e)n(o);return r}(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 n=new Set;for(const o of r){const e=o.__pivotRowKey;n.add(e),!this.previousVisibleKeys.has(e)&&o.__pivotDepth>0&&this.keysToAnimate.add(e)}return this.previousVisibleKeys=n,r}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 r of this.pivotResult.columnKeys)for(const e of this.config.valueFields??[]){const i=rr([r],e.field),n=e.header||this.fieldHeaderMap.get(e.field)||e.field;t.push({field:i,header:`${r} - ${n} (${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 r=e;return r.__pivotRowKey&&r.__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((r,n)=>{const o=document.createElement("div");if(o.className="cell",o.setAttribute("data-col",String(n)),o.setAttribute("data-row",String(i.rowIndex)),o.setAttribute("role","gridcell"),0===n){const t=Number(e.__pivotIndent)||0;o.style.paddingLeft=`${t}px`;const r=String(e.__pivotRowKey),n=document.createElement("button");n.type="button",n.className="pivot-toggle",n.setAttribute("aria-label",e.__pivotExpanded?"Collapse group":"Expand group"),i.setIcon(n,i.resolveIcon(e.__pivotExpanded?"collapse":"expand")),n.addEventListener("click",e=>{e.stopPropagation(),i.onToggle(r)}),o.appendChild(n);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[r.field];o.textContent=null!=t?String(t):""}t.appendChild(o)}),!0}(r,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!==r.__pivotRowKey&&this.isActive?function(e,t,i,r){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,n)=>{const o=document.createElement("div");if(o.className="cell",o.setAttribute("data-col",String(n)),o.setAttribute("data-row",String(r)),o.setAttribute("role","gridcell"),0===n){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}(r,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 r of t.querySelectorAll(".pivot-group-row, .pivot-leaf-row")){const e=r.dataset.pivotKey;e&&this.keysToAnimate.has(e)&&(r.classList.add(i),r.addEventListener("animationend",()=>r.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.querySelector(".tbw-grid-root");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 r,n,o;r=i,n=this.grandTotalFooter,o=this.gridColumns,n.className="pivot-grand-total-row",n.setAttribute("role","presentation"),n.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=r[e.field];i.textContent=null!=t?String(t):""}n.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 r of e)i(r);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(fr.PANEL_ID)||this.grid.toggleToolPanelSection(fr.PANEL_ID)}hidePanel(){this.grid.closeToolPanel()}togglePanel(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(fr.PANEL_ID)}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(fr.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 dr(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??[],r=i.findIndex(t=>t.field===e);r>=0&&(i[r]={...i[r],aggFunc:t},this.config.valueFields=[...i]),this.isActive&&this.refresh()}}const wr="tbw-print-isolation-style";async function mr(e,t={}){const{orientation:i="landscape"}=t,r=e.id;document.querySelectorAll(`#${CSS.escape(r)}`).length>1&&u("TBW093",`Multiple elements found with id="${r}". Print isolation may not work correctly. Ensure each grid has a unique ID.`,r,"print"),document.getElementById(wr)?.remove();const n=function(e,t){const i=document.createElement("style");return i.id=wr,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}(r,i);return document.head.appendChild(n),new Promise(e=>{const t=()=>{window.removeEventListener("afterprint",t),document.getElementById(wr)?.remove(),e()};window.addEventListener("afterprint",t),window.print(),setTimeout(()=>{window.removeEventListener("afterprint",t),document.getElementById(wr)?.remove(),e()},5e3)})}const br={button:!1,orientation:"landscape",warnThreshold:500,maxRows:0,includeTitle:!0,includeTimestamp:!0,title:"",isolate:!1};function vr(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 r=[...e],[n]=r.splice(t,1);return r.splice(i,0,n),r}const yr="__tbw_row_drag";function Cr(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 xr(e){const t=Cr(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function Rr(e){return e.map(xr)}function Er(e,t,i){return i.some(i=>function(e,t,i){const r=Cr(i);return e>=r.startRow&&e<=r.endRow&&t>=r.startCol&&t<=r.endCol}(e,t,i))}function Sr(e){const t=[],i=Cr(e);for(let r=i.startRow;r<=i.endRow;r++)for(let e=i.startCol;e<=i.endCol;e++)t.push({row:r,col:e});return t}function _r(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function Ar(e,t){const i=Cr(e),r=Cr(t);return i.startRow===r.startRow&&i.startCol===r.startCol&&i.endRow===r.endRow&&i.endCol===r.endCol}const kr="__tbw_checkbox";function Tr(e,t){return Math.floor(e/t)}async function Mr(e,t,i,r){const n=function(e,t){return{start:e*t,end:(e+1)*t}}(t,i);return e.getRows({startRow:n.start,endRow:n.end,sortModel:r.sortModel,filterModel:r.filterModel})}function Lr(e,t,i){const r=Tr(e,t),n=i.get(r);if(!n)return;return n[e%t]}function Ir(e,t,i){return void 0!==e.id?String(e.id):i?`${i}-${t}`:String(t)}function Pr(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}function Hr(e,t,i=null,r=0){const n=t.childrenField??"children",o=new Set;for(let s=0;s<e.length;s++){const l=e[s],a=Ir(l,s,i),d=l[n];if(Array.isArray(d)&&d.length>0){o.add(a);const e=Hr(d,t,a,r+1);for(const t of e)o.add(t)}}return o}function Dr(e,t,i,r=null,n=0){const o=i.childrenField??"children";for(let s=0;s<e.length;s++){const l=e[s],a=Ir(l,s,r);if(a===t)return[a];const d=l[o];if(Array.isArray(d)&&d.length>0){const e=Dr(d,t,i,a,n+1);if(e)return[a,...e]}}return null}function Fr(e,t,i,r){const n=Dr(e,t,i);if(!n)return r;const o=new Set(r);for(let s=0;s<n.length-1;s++)o.add(n[s]);return o}function zr(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 qr(e,t,i){const r=[...e.undoStack,t];for(;r.length>i;)r.shift();return{undoStack:r,redoStack:[]}}function Or(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 Nr(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 Gr(e){const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}class $r extends Ct{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),this.gridElement.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:$r.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes($r.PANEL_ID)||this.grid.toggleToolPanelSection($r.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection($r.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($r.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 r=document.createElement("button");return r.className="tbw-visibility-show-all",r.textContent="Show All",r.addEventListener("click",()=>{this.grid.showAllColumns(),this.rebuildToggles(i)}),t.appendChild(r),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),r=this.grid.query("getColumnGrouping"),n=r?.flat().filter(e=>e&&e.fields.length>0)??[];if(0===n.length)return void this.renderFlatColumnList(i,t,e);const o=new Map;for(const l of n)for(const e of l.fields)o.set(e,l);const s=this.computeFragments(i,o);for(const l of s)if(l.group)this.renderGroupSection(l.group,l.columns,t,e);else{const r=i.indexOf(l.columns[0]);e.appendChild(this.createColumnRow(l.columns[0],r,t,e))}}computeFragments(e,t){const i=[];let r=null,n=[];for(const o of e){const e=t.get(o.field)??null;e&&r&&e.id===r.id?n.push(o):(n.length>0&&i.push({group:r,columns:n}),r=e,n=[o])}return n.length>0&&i.push({group:r,columns:n}),i}renderGroupSection(e,t,i,r){const n=t.map(e=>e.field),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,r));const s=document.createElement("label");s.className="tbw-visibility-label";const l=document.createElement("input");l.type="checkbox";const a=t.filter(e=>e.visible).length,d=t.every(e=>e.lockVisible);a===t.length?(l.checked=!0,l.indeterminate=!1):0===a?(l.checked=!1,l.indeterminate=!1):(l.checked=!1,l.indeterminate=!0),l.disabled=d,l.addEventListener("change",()=>{const e=l.checked;for(const i of t)i.lockVisible||this.grid.setColumnVisible(i.field,e);setTimeout(()=>this.rebuildToggles(r),0)});const c=document.createElement("span");if(c.textContent=e.label,s.appendChild(l),s.appendChild(c),o.appendChild(s),i){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,this.resolveIcon("dragHandle")),e.title="Drag to reorder group",o.insertBefore(e,s)}r.appendChild(o);const h=this.grid.getAllColumns().filter(e=>!e.utility);for(const u of t){const e=h.findIndex(e=>e.field===u.field),t=this.createColumnRow(u,e,i,r);t.classList.add("tbw-visibility-row--grouped"),r.appendChild(t)}}renderFlatColumnList(e,t,i){const r=this.grid.getAllColumns().filter(e=>!e.utility);for(const n of e){const e=r.findIndex(e=>e.field===n.field);i.appendChild(this.createColumnRow(n,e,t,i))}}createColumnRow(e,t,i,r){const n=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&&Gr(e)&&(o.draggable=!0,o.classList.add("reorderable"),this.setupDragListeners(o,e.field,t,r));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(r),0)});const a=document.createElement("span");if(a.textContent=n,s.appendChild(l),s.appendChild(a),i&&Gr(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,r){e.addEventListener("dragstart",n=>{this.isDragging=!0,this.draggedGroupId=t.id,this.draggedGroupFields=[...i],this.draggedField=null,this.draggedIndex=null,n.dataTransfer&&(n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",`group:${t.id}`)),e.classList.add("dragging"),r.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(r)}),e.addEventListener("dragover",t=>{if(t.preventDefault(),!this.isDragging)return;if(this.draggedGroupFields.length===i.length&&this.draggedGroupFields.every(e=>i.includes(e)))return;if(!this.draggedGroupId)return;const n=e.getBoundingClientRect(),o=n.top+n.height/2,s=t.clientY<o;this.clearDragClasses(r),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=>{if(t.preventDefault(),!this.isDragging||!this.draggedGroupId)return;if(this.draggedGroupFields.length===i.length&&this.draggedGroupFields.every(e=>i.includes(e)))return;const r=e.getBoundingClientRect(),n=t.clientY<r.top+r.height/2;this.executeGroupDrop(this.draggedGroupFields,i,n)})}executeGroupDrop(e,t,i){const r=this.grid.getAllColumns().map(e=>e.field),n=r.filter(t=>!e.includes(t)),o=i?t[0]:t[t.length-1],s=n.indexOf(o);if(-1===s)return;const l=i?s:s+1,a=r.filter(t=>e.includes(t));n.splice(l,0,...a);const d=this.grid.getPluginByName?.("reorder");d?.setColumnOrder&&d.gridElement?d.setColumnOrder(n):this.grid.setColumnOrder(n),requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})}setupDragListeners(e,t,i,r){e.addEventListener("dragstart",r=>{this.isDragging=!0,this.draggedField=t,this.draggedIndex=i,this.draggedGroupId=null,this.draggedGroupFields=[],r.dataTransfer&&(r.dataTransfer.effectAllowed="move",r.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(r)}),e.addEventListener("dragover",n=>{if(n.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=n.clientY<s?i:i+1,this.clearDragClasses(r),this.draggedGroupId?(r.querySelector(`.tbw-visibility-group-header[data-group-id="${this.draggedGroupId}"]`)?.classList.add("dragging"),r.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&e.classList.add("dragging")})):this.draggedField&&r.querySelector(`.tbw-visibility-row[data-field="${this.draggedField}"]`)?.classList.add("dragging"),e.classList.add("drop-target"),e.classList.toggle("drop-before",n.clientY<s),e.classList.toggle("drop-after",n.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(),n=i.clientY<r.top+r.height/2;return void this.executeGroupDrop(this.draggedGroupFields,[t],n)}const r=this.draggedField,n=this.draggedIndex,o=this.dropIndex;if(null===r||null===n||null===o)return;const s=o>n?o-1:o;if(s!==n){const e=this.grid.getAllColumns(),t=e.filter(e=>!e.utility),i=t[s]?.field,o={field:r,fromIndex:n,toIndex:i?e.findIndex(e=>e.field===i):e.length};this.emit("column-reorder-request",o)}})}}e.BLANK_FILTER_VALUE=di,e.BaseGridPlugin=Ct,e.ClipboardPlugin=class extends Ct{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.#xt(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#Rt(e.target),!0)}#Rt(e){const t=this.#Et();if(t&&0===t.ranges.length){const t=this.#St(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()}#xt(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const i=kt(t,this.config),r=this.#Et(),n=r?.ranges?.[0],o=n?.from.row??0,s=n?.from.col??0,l=n&&("range"===r?.mode||"row"===r?.mode)&&(n.from.row!==n.to.row||n.from.col!==n.to.col)?{endRow:n.to.row,endCol:n.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.#_t(g)}#_t(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??Tt)(e,this.grid)}#Et(){const e=this.grid?.query("getSelection");return e?.[0]}#At(e){const t=this.#Et();let i,r;if(e?.columns)i=St(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],r=Math.min(e.from.col,e.to.col),n=Math.max(e.from.col,e.to.col);i=St(this.visibleColumns.slice(r,n+1))}else i=St(this.columns);if(e?.rowIndices)r=_t(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),n=Math.max(e.from.row,e.to.row);r=[];for(let t=i;t<=n;t++){const e=this.rows[t];e&&r.push(e)}}else r=this.rows;return{columns:i,rows:r}}#kt(e,t,i){const r=i?.delimiter??this.config.delimiter??"\t",n=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(r));for(const a of t){const t=e.map(e=>{const t=a[e.field];return s?s(t,e.field,a):At(t)});l.push(t.join(r))}return l.join(n)}#St(e){const t=e.closest("[data-field-cache]");if(!t)return null;const i=t.dataset.fieldCache,r=t.dataset.row;if(!i||!r)return null;const n=parseInt(r,10);if(isNaN(n))return null;const o=this.columns.findIndex(e=>e.field===i);return-1===o?null:{row:n,col:o}}getSelectionAsText(e){const{columns:t,rows:i}=this.#At(e);return 0===t.length||0===i.length?"":this.#kt(t,i,e)}async copy(e){const{columns:t,rows:i}=this.#At(e);if(0===t.length||0===i.length)return"";const r=this.#kt(t,i,e);return await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){u("TBW100",`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 r=document.execCommand("copy");return document.body.removeChild(i),r}}(r),this.lastCopied={text:r,timestamp:Date.now()},this.emit("copy",{text:r,rowCount:i.length,columnCount:t.length}),r}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?kt(e,this.config):null}getLastCopied(){return this.lastCopied}},e.ColumnVirtualizationPlugin=class extends Ct{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=Lt(t),this.columnOffsets=It(t),this.totalWidth=Pt(t),this.endCol=t.length-1}detach(){this.#Tt(),this.columnWidths=[],this.columnOffsets=[],this.originalColumns=[],this.isVirtualized=!1,this.startCol=0,this.endCol=0,this.scrollLeft=0,this.totalWidth=0}#Tt(){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 r=e.querySelector(".rows-body");r&&(r.style.minWidth="")}processColumns(e){(0===this.originalColumns.length||e.length>=this.originalColumns.length)&&(this.originalColumns=e,this.columnWidths=Lt(e),this.columnOffsets=It(e),this.totalWidth=Pt(e));const t=this.originalColumns,i=(r=t.length,n=this.config.threshold??30,!!(this.config.autoEnable??!0)&&r>n);var r,n;if(this.isVirtualized=i??!1,!i)return this.startCol=0,this.endCol=t.length-1,[...t];const o=this.grid?.clientWidth||800,s=Ht(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"),r=e.querySelectorAll(".data-grid-row");i&&(i.style.paddingLeft=`${t}px`,i.style.minWidth=`${this.totalWidth}px`),r.forEach(e=>{e.style.paddingLeft=`${t}px`});const n=e.querySelector(".rows-viewport .rows");n&&(n.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,i=this.gridElement;i&&(i.scrollLeft=t)}getColumnOffset(e){return this.columnOffsets[e]??0}getTotalWidth(){return this.totalWidth}},e.ContextMenuPlugin=Bt,e.DEFAULT_ANIMATION_CONFIG=r,e.DEFAULT_GRID_ICONS=o,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",DATA_CHANGE:"data-change"},e.DataGridElement=yt,e.EditingPlugin=class extends Ct{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>!0===e||"function"==typeof e},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'},{property:"nullable",level:"column",description:'the "nullable" column property (allows null values)'}],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#Mt(){return"grid"===this.config.mode}#Lt(e,t){const i=this.#bt.effectiveConfig?.rowEditable;if(i&&!i(t))return!1;const{editable:r}=e;return"function"==typeof r?r(t):!0===r}#It(e){return!0===e.editable||"function"==typeof e.editable}#Pt=-1;#Ht;#Dt;#Ft=-1;#zt=new Map;#qt=new Set;#Ot=new Map;#Nt=!1;#Gt=-1;#$t;#Wt=!1;#Bt=!1;#Vt=!1;#Kt=null;#Ut=new ei;#jt;get#bt(){return this.grid}attach(e){super.attach(e);const t=this.disconnectSignal,i=this.#bt;if(this.#$t=new Yt((e,t,i)=>{this.#Yt(e,t,i)}),this.#jt={grid:i,isGridMode:this.#Mt,config:this.config,editingCells:this.#qt,editorValueCallbacks:this.#Ot,isEditSessionActive:()=>-1!==this.#Pt,commitCellValue:(e,t,i,r)=>this.#Xt(e,t,i,r),exitRowEdit:(e,t)=>this.#Zt(e,t)},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}),Object.defineProperty(e,"_changedRowIdSet",{get:()=>this.#Ut.changedRowIds,configurable:!0}),e.resetChangedRows=e=>this.resetChangedRows(e),e.beginBulkEdit=(e,t)=>{t&&this.beginCellEdit(e,t)},document.addEventListener("keydown",e=>{if(!this.#Mt&&"Escape"===e.key&&-1!==this.#Pt){if(ni(this.config,e))return;this.#Zt(this.#Pt,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",e=>{if(this.#Mt)return;if(-1===this.#Pt)return;const t=i.findRenderedRowElement?.(this.#Pt);if(!t)return;if((e.composedPath&&e.composedPath()||[]).includes(t))return;const r=e.target;r&&!this.gridElement.contains(r)&&this.grid.containsFocus?.(r)||ni(this.config,e)||queueMicrotask(()=>{-1!==this.#Pt&&this.#Zt(this.#Pt,!1)})},{signal:t}),this.config.focusTrap&&this.gridElement.addEventListener("focusout",e=>{if(this.#Mt)return;if(-1===this.#Pt)return;const t=e.relatedTarget;t&&this.grid.containsFocus?.(t)||t&&this.gridElement.contains(t)||queueMicrotask(()=>{-1!==this.#Pt&&this.#Qt()})},{signal:t}),this.gridElement.addEventListener("cell-change",e=>{const t=e.detail;if("user"===t.source)return;const i=`${t.rowIndex}:${t.field}`,r=this.#Ot.get(i);r&&r(t.newValue)},{signal:t}),this.config.dirtyTracking){const e=e=>{const t=e.detail,i=t?.action;if(!i)return;const r=this.rows[i.rowIndex];if(!r)return;const n=this.grid.getRowId(r);if(!n)return;const o=this.#Ut.isRowDirty(n,r);this.emit("dirty-change",{rowId:n,row:r,original:this.#Ut.getOriginalRow(n),type:o?"modified":"pristine"})};this.gridElement.addEventListener("undo",e,{signal:t}),this.gridElement.addEventListener("redo",e,{signal:t}),this.on("row-inserted",e=>{const t=this.grid.getRowId(e.row);null!=t&&this.markAsNew(String(t))})}this.#Mt&&(i._isGridEditMode=!0,this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",e=>{const t=e.target;if(t!==this.gridElement&&t.matches(ti)){if(this.#Bt)return t.blur(),void this.gridElement.focus();const e=i._focusRow,r=i._focusCol,n=this.#Kt;if(!n||n.rowIndex!==e||n.colIndex!==r){const t=i._visibleColumns?.[r],n=i._rows?.[e];if(t?.field&&n){const i=t.field;this.#Kt={rowIndex:e,colIndex:r,field:i,value:n[i]}}}this.#Wt=!0}},{signal:t}),this.gridElement.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.gridElement.contains(t)||this.grid.containsFocus?.(t))&&t.matches(ti)||(this.#Wt=!1,this.#Kt=null)},{signal:t}),this.gridElement.addEventListener("keydown",e=>{if("Escape"===e.key&&this.#Wt){if(ni(this.config,e))return void queueMicrotask(()=>{if(this.#Wt){this.#Jt();const e=document.activeElement;e&&this.gridElement.contains(e)&&(e.blur(),this.gridElement.focus()),this.#Wt=!1,this.#Bt=!0}});this.#Jt();const t=document.activeElement;t&&this.gridElement.contains(t)&&(t.blur(),this.gridElement.focus()),this.#Wt=!1,this.#Bt=!0,e.preventDefault(),e.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",e=>{e.target.matches(ti)&&(this.#Bt=!1)},{signal:t}))}detach(){this.#bt._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#Pt=-1,this.#Ht=void 0,this.#Dt=void 0,this.#Ft=-1,this.#zt.clear(),this.#Ut.clear(),this.#qt.clear(),this.#Ot.clear(),this.#Wt=!1,this.#Bt=!1,this.#Kt=null,this.#Vt=!1,super.detach()}handleQuery(e){if("isEditing"===e.type)return this.#Mt||-1!==this.#Pt}onCellClick(e){if(this.#Mt)return!1;const t=this.#bt,i=this.config.editOn??t.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;if("click"!==i&&"dblclick"!==i)return!1;const r="dblclick"===e.originalEvent.type;if("click"===i&&r)return!1;if("dblclick"===i&&!r)return!1;const{rowIndex:n}=e,o=t._columns?.some(e=>this.#It(e));if(!o)return!1;const s=t._rows[n],l=t.effectiveConfig?.rowEditable;return!(s&&l&&!l(s))&&(e.originalEvent.stopPropagation(),this.beginBulkEdit(n),!0)}onKeyDown(e){const t=this.#bt;if("Escape"===e.key){if(this.#Mt&&this.#Wt){this.#Jt();const e=document.activeElement;return e&&this.gridElement.contains(e)&&(e.blur(),this.gridElement.focus()),this.#Wt=!1,this.#Bt=!0,this.requestAfterRender(),!0}if(-1!==this.#Pt&&!this.#Mt)return ni(this.config,e)||this.#Zt(this.#Pt,!0),!0}if(this.#Mt&&!this.#Wt&&("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key))return!1;if(this.#Mt&&this.#Wt&&("ArrowUp"===e.key||"ArrowDown"===e.key))return!0;if(("ArrowUp"===e.key||"ArrowDown"===e.key)&&-1!==this.#Pt&&!this.#Mt){if(ni(this.config,e))return!0;const i=t._rows.length-1,r=this.#Pt;return this.#Zt(r,!1),"ArrowDown"===e.key?t._focusRow=Math.min(i,t._focusRow+1):t._focusRow=Math.max(0,t._focusRow-1),e.preventDefault(),fe(t),this.requestAfterRender(),!0}if("Tab"===e.key&&(-1!==this.#Pt||this.#Mt)){if(e.preventDefault(),this.#Vt)return this.#Zt(this.#Pt,!1),!0;const t=!e.shiftKey;return this.#ei(t),!0}if(" "===e.key||"Spacebar"===e.key){if(-1!==this.#Pt)return!1;const i=t._focusRow,r=t._focusCol;if(i>=0&&r>=0){const n=t._visibleColumns[r],o=t._rows[i];if(n&&o&&this.#Lt(n,o)&&"boolean"===n.type){const t=n.field;if(ii(t)){const r=!o[t];return this.#Xt(i,n,r,o),e.preventDefault(),this.requestRender(),!0}}}return!1}if(!("Enter"!==e.key||e.shiftKey||e.ctrlKey||e.altKey||e.metaKey)){if(this.#Mt&&!this.#Wt)return this.#Qt(),!0;if(-1!==this.#Pt)return!!ni(this.config,e);const i=this.config.editOn??t.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;const r=t._focusRow,n=t._focusCol;if(r>=0){const i=t._columns?.some(e=>this.#It(e)),o=t._rows[r],s=t.effectiveConfig?.rowEditable,l=o&&s&&!s(o);if(i&&!l){const i=t._visibleColumns[n],o=t._rows[r],s=i?.field??"",l=s&&o?o[s]:void 0,a=this.gridElement.querySelector(`[data-row="${r}"][data-col="${n}"]`),d=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:r,colIndex:n,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:r,col:n}});return this.gridElement.dispatchEvent(c),d.defaultPrevented||c.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(r),!0)}}return!1}if("F2"===e.key){if(-1!==this.#Pt||this.#Mt)return!1;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return!1;const i=t._focusRow,r=t._focusCol;if(i>=0&&r>=0){const n=t._visibleColumns[r],o=t._rows[i];if(n&&o&&this.#Lt(n,o)&&n.field)return e.preventDefault(),this.beginCellEdit(i,n.field),!0}return!1}return!1}processColumns(e){const t=this.#bt,i=t.effectiveConfig?.typeDefaults,r=t.__frameworkAdapter;return i||r?.getTypeDefault?e.map(e=>{if(!e.type)return e;let t;if(i?.[e.type]?.editorParams&&(t=i[e.type].editorParams),!t&&r?.getTypeDefault){const i=r.getTypeDefault(e.type);i?.editorParams&&(t=i.editorParams)}return t?{...e,editorParams:{...t,...e.editorParams}}:e}):e}processRows(e){const t=this.#bt;if(this.config.dirtyTracking&&t.getRowId&&this.#Ut.capture(e,e=>{try{return t.getRowId?.(e)}catch{return}}),-1===this.#Pt||this.#Mt)return e;const i=this.#Ht,r=this.#Dt;if(!i||!r)return e;const n=[...e];let o=-1;for(let s=0;s<n.length;s++)try{if(t.getRowId?.(n[s])===i){o=s;break}}catch{}return-1===o?(setTimeout(()=>this.cancelActiveRowEdit(),0),n):(n[o]=r,this.#Pt!==o&&this.#ti(this.#Pt,o),n)}afterRender(){const e=this.#bt;if(-1!==this.#Pt&&this.#Dt&&!this.#Mt&&e._rows[this.#Pt]!==this.#Dt){const t=e._rows.indexOf(this.#Dt);if(-1===t)return void setTimeout(()=>this.cancelActiveRowEdit(),0);this.#ti(this.#Pt,t)}if(this.#Nt&&(this.#Nt=!1,this.#ii(e)),-1!==this.#Gt){const t=this.#Gt;this.#Gt=-1,e.animateRow?.(t,"change")}const t=this.#Ut.drainCapturedFlag();if(null!=t&&this.emit("baselines-captured",{count:t}),!this.#Mt&&0!==this.#qt.size)for(const i of this.#qt){const[t,r]=i.split(":"),n=parseInt(t,10),o=parseInt(r,10),s=e.findRenderedRowElement?.(n);if(!s)continue;const l=s.querySelector(`.cell[data-col="${o}"]`);if(!l||l.classList.contains("editing"))continue;const a=e._rows[n],d=e._visibleColumns[o];a&&d&&this.#ri(a,n,d,o,l,!0)}}afterCellRender(e){const{row:t,rowIndex:i,column:r,colIndex:n,cellElement:o}=e,s=this.#Lt(r,t);if(s)o.removeAttribute("aria-readonly");else if(o.setAttribute("aria-readonly","true"),this.#Mt&&o.classList.contains("editing")){o.classList.remove("editing");const e=t[r.field];o.textContent=null==e?"":String(e)}this.#Mt&&s&&(o.classList.contains("editing")||this.#ri(t,i,r,n,o,!0,e.rowElement))}afterRowRender(e){if(!this.config.dirtyTracking)return;const t=this.#bt,i=t.getRowId?.(e.row);if(!i)return;const{isNew:r,isCommittedDirty:n,hasBaseline:o}=this.#Ut.getRowDirtyState(i,e.row),s=e.rowElement;if(s.classList.toggle("tbw-row-dirty",n),s.classList.toggle("tbw-row-new",r),o){const t=s.querySelectorAll(".cell[data-field]");for(let r=0;r<t.length;r++){const n=t[r],o=n.getAttribute("data-field");o&&n.classList.toggle("tbw-cell-dirty",this.#Ut.isCellDirty(i,e.row,o))}}else{const e=s.querySelectorAll(".tbw-cell-dirty");for(let t=0;t<e.length;t++)e[t].classList.remove("tbw-cell-dirty")}}onScrollRender(){this.afterRender()}get changedRows(){return this.#Ut.getChangedRows(e=>this.grid.getRow(e))}get changedRowIds(){return this.#Ut.getChangedRowIds()}get activeEditRow(){return this.#Pt}get activeEditCol(){return this.#Ft}isRowEditing(e){return this.#Pt===e}isCellEditing(e,t){return this.#qt.has(`${e}:${t}`)}isRowChanged(e){const t=this.#bt,i=t._rows[e];if(!i)return!1;try{const e=t.getRowId?.(i);return!!e&&this.#Ut.isRowChanged(e)}catch{return!1}}isRowChangedById(e){return this.#Ut.isRowChanged(e)}isDirty(e){if(!this.config.dirtyTracking)return!1;if(this.#Ut.newRowIds.has(e))return!0;const t=this.grid.getRow(e);return!!t&&this.#Ut.isRowDirty(e,t)}isPristine(e){return!this.isDirty(e)}get dirty(){if(!this.config.dirtyTracking)return!1;const e=this.#bt;return this.#Ut.hasAnyDirty(t=>e._getRowEntry(t)?.row)}get pristine(){return!this.dirty}markAsPristine(e){if(!this.config.dirtyTracking)return;const t=this.grid.getRow(e);t&&(this.#Ut.markPristine(e,t),this.emit("dirty-change",{rowId:e,row:t,original:t,type:"pristine"}))}markAsNew(e){if(!this.config.dirtyTracking)return;this.#Ut.markNew(e);const t=this.grid.getRow(e);this.emit("dirty-change",{rowId:e,row:t,original:void 0,type:"new"})}markAsDirty(e){if(!this.config.dirtyTracking)return;const t=this.grid.getRow(e);t&&(this.#Ut.markDirty(e),this.emit("dirty-change",{rowId:e,row:t,original:this.#Ut.getOriginalRow(e),type:"modified"}))}markAllPristine(){if(!this.config.dirtyTracking)return;const e=this.#bt;this.#Ut.markAllPristine(t=>e._getRowEntry(t)?.row)}getOriginalRow(e){if(this.config.dirtyTracking)return this.#Ut.getOriginalRow(e)}hasBaseline(e){return!!this.config.dirtyTracking&&this.#Ut.hasBaseline(e)}getDirtyRows(){if(!this.config.dirtyTracking)return[];const e=this.#bt;return this.#Ut.getDirtyRows(t=>e._getRowEntry(t)?.row)}get dirtyRowIds(){if(!this.config.dirtyTracking)return[];const e=this.#bt;return this.#Ut.getDirtyRowIds(t=>e._getRowEntry(t)?.row)}revertRow(e){if(!this.config.dirtyTracking)return;const t=this.grid.getRow(e);t&&this.#Ut.revertRow(e,t)&&(this.emit("dirty-change",{rowId:e,row:t,original:this.#Ut.getOriginalRow(e),type:"reverted"}),this.requestRender())}revertAll(){if(!this.config.dirtyTracking)return;const e=this.#bt;this.#Ut.revertAll(t=>e._getRowEntry(t)?.row),this.requestRender()}setInvalid(e,t,i=""){this.#$t.setInvalid(e,t,i)}clearInvalid(e,t){this.#$t.clearInvalid(e,t)}clearRowInvalid(e){this.#$t.clearRowInvalid(e)}clearAllInvalid(){this.#$t.clearAllInvalid()}isCellInvalid(e,t){return this.#$t.isCellInvalid(e,t)}getInvalidMessage(e,t){return this.#$t.getInvalidMessage(e,t)}hasInvalidCells(e){return this.#$t.hasInvalidCells(e)}getInvalidFields(e){return this.#$t.getInvalidFields(e)}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#Ut.changedRowIds.clear(),this.#Ut.committedDirtyRowIds.clear(),this.#ni(),e||this.emit("changed-rows-reset",{rows:t,ids:i});const r=this.#bt;r._rowPool?.forEach(e=>e.classList.remove("changed"))}beginCellEdit(e,t){const i=this.#bt,r=i._visibleColumns.findIndex(e=>e.field===t);if(-1===r)return;const n=i._visibleColumns[r],o=i._rows[e];if(!n||!o||!this.#Lt(n,o))return;const s=i.findRenderedRowElement?.(e),l=s?.querySelector(`.cell[data-col="${r}"]`);l&&(this.#Vt=!0,this.#oi(e,r,l))}beginBulkEdit(e){const t=this.#bt;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return;const i=t._columns?.some(e=>this.#It(e));if(!i)return;const r=t.findRenderedRowElement?.(e);if(!r)return;const n=t._rows[e],o=t.effectiveConfig?.rowEditable;n&&o&&!o(n)||(this.#Vt=!1,this.#si(e,n),Array.from(r.children).forEach((i,r)=>{const o=t._visibleColumns[r];if(o&&this.#Lt(o,n)){const t=i;t.classList.contains("editing")||this.#ri(n,e,o,r,t,!0)}}),setTimeout(()=>{let e=r.querySelector(`.cell[data-col="${t._focusCol}"]`);if(e?.classList.contains("editing")||(e=r.querySelector(".cell.editing")),e?.classList.contains("editing")){const t=e.querySelector(ti);try{t?.focus({preventScroll:!0})}catch{}}},0))}commitActiveRowEdit(){-1!==this.#Pt&&this.#Zt(this.#Pt,!1)}cancelActiveRowEdit(){-1!==this.#Pt&&this.#Zt(this.#Pt,!0)}#Yt(e,t,i){const r=this.#bt,n=r._visibleColumns?.findIndex(e=>e.field===t);if(-1===n||void 0===n)return;const o=r._rows,s=o?.findIndex(t=>{try{return r.getRowId?.(t)===e}catch{return!1}});if(-1===s||void 0===s)return;const l=r.findRenderedRowElement?.(s),a=l?.querySelector(`.cell[data-col="${n}"]`);if(a)if(i){a.setAttribute("data-invalid","true");const i=this.#$t.getInvalidMessage(e,t);i&&a.setAttribute("title",i)}else a.removeAttribute("data-invalid"),a.removeAttribute("title")}#ti(e,t){this.#Pt=t;const i=new Set,r=`${e}:`;for(const s of this.#qt)s.startsWith(r)?i.add(`${t}:${s.substring(r.length)}`):i.add(s);this.#qt.clear();for(const s of i)this.#qt.add(s);const n=this.#zt.get(e);void 0!==n&&(this.#zt.delete(e),this.#zt.set(t,n));const o=[];for(const[s,l]of this.#Ot)s.startsWith(r)&&(o.push([`${t}:${s.substring(r.length)}`,l]),this.#Ot.delete(s));for(const[s,l]of o)this.#Ot.set(s,l);this.#ni()}#oi(e,t,i){const r=this.#bt,n=r._rows[e],o=r._visibleColumns[t];n&&o&&this.#Lt(o,n)&&(i.classList.contains("editing")||(this.#Pt!==e&&this.#si(e,n),this.#Ft=t,this.#ri(n,e,o,t,i,!1)))}#Jt(){const e=this.#Kt;if(!e)return;const t=this.#bt,i=t._rows?.[e.rowIndex];i&&(i[e.field]=e.value);const r=`${e.rowIndex}:${e.field}`,n=this.#Ot.get(r);if(n&&n(e.value),this.emit("cell-cancel",{rowIndex:e.rowIndex,colIndex:e.colIndex,field:e.field,previousValue:e.value}),i){let e;try{e=this.grid.getRowId(i)}catch{}e&&(this.config.dirtyTracking?this.#Ut.isRowDirty(e,i)||(this.#Ut.changedRowIds.delete(e),this.emit("dirty-change",{rowId:e,row:i,original:this.#Ut.getOriginalRow(e),type:"reverted"})):this.#Ut.changedRowIds.delete(e))}this.requestRender(),this.#Kt=null}#Qt(){const e=this.#bt,t=e._focusRow,i=e._focusCol;if(t<0||i<0)return;const r=e.findRenderedRowElement?.(t),n=r?.querySelector(`.cell[data-col="${i}"]`);if(n?.classList.contains("editing")){const e=n.querySelector(ti);e&&(this.#Bt=!1,e.focus(),this.#Wt=!0,e instanceof HTMLInputElement&&("text"===e.type||"number"===e.type)&&e.select())}}#ei(e){const t=this.#bt,i=t._rows,r=this.#Mt?t._focusRow:this.#Pt,n=i[r],o=t._visibleColumns.map((e,t)=>n&&this.#Lt(e,n)?t:-1).filter(e=>e>=0);if(0===o.length)return;const s=o.indexOf(t._focusCol)+(e?1:-1);if(s>=0&&s<o.length){t._focusCol=o[s];const e=t.findRenderedRowElement?.(r),i=e?.querySelector(`.cell[data-col="${o[s]}"]`);if(i?.classList.contains("editing")){const e=i.querySelector(ti);e?.focus({preventScroll:!0})}return void fe(t,{forceHorizontalScroll:!0})}const l=r+(e?1:-1);if(l>=0&&l<i.length){const n=i[l],o=t._visibleColumns.map((e,t)=>n&&this.#Lt(e,n)?t:-1).filter(e=>e>=0);if(0===o.length)return;this.#Mt?(t._focusRow=l,t._focusCol=e?o[0]:o[o.length-1],fe(t,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const e=t.findRenderedRowElement?.(l),i=e?.querySelector(`.cell[data-col="${t._focusCol}"]`);if(i?.classList.contains("editing")){const e=i.querySelector(ti);e?.focus({preventScroll:!0})}},0)):(this.#Zt(r,!1),t._focusRow=l,t._focusCol=e?o[0]:o[o.length-1],this.beginBulkEdit(l),fe(t,{forceHorizontalScroll:!0}))}}#ni(){const e=this.#bt;e._activeEditRows=this.#Pt,e._rowEditSnapshots=this.#zt}#si(e,t){if(this.#Pt!==e){-1!==this.#Pt&&this.#Zt(this.#Pt,!1),this.#zt.set(e,{...t}),this.#Pt=e,this.#Dt=t;const i=this.#bt;try{this.#Ht=i.getRowId?.(t)??void 0}catch{this.#Ht=void 0}this.#ni(),this.#Mt||this.emit("edit-open",{rowIndex:e,rowId:this.#Ht??"",row:t})}}#Zt(e,t){if(this.#Pt!==e)return;const i=this.#bt,r=this.#zt.get(e),n=i.findRenderedRowElement?.(e);let o=this.#Ht;const s=o?i._getRowEntry(o):void 0,l=s?.row??this.#Dt??i._rows[e];if(!o&&l)try{o=i.getRowId?.(l)}catch{}if(!t&&n&&l){n.querySelectorAll(".cell.editing").forEach(t=>{const r=Number(t.getAttribute("data-col"));if(isNaN(r))return;const n=i._visibleColumns[r];if(!n)return;if(t.hasAttribute("data-editor-managed"))return;const o=t.querySelector("input,textarea,select");if(o){const t=n.field,i=l[t],r=jt(o,n,i);i!==r&&this.#Xt(e,n,r,l)}})}if(t||this.#Mt||!l||this.emit("before-edit-close",{rowIndex:e,rowId:o??"",row:l}),t&&r&&l)Object.keys(r).forEach(e=>{l[e]=r[e]}),o&&(this.#Ut.changedRowIds.delete(o),this.#Ut.committedDirtyRowIds.delete(o),this.clearRowInvalid(o));else if(!t&&l){const t=function(e,t){if(!e)return!1;const i=e,r=t,n=new Set([...Object.keys(i),...Object.keys(r)]);for(const o of n)if(i[o]!==r[o])return!0;return!1}(r,l),i=o?this.#Ut.changedRowIds.has(o):t,n=this.emitCancelable("row-commit",{rowIndex:e,rowId:o??"",row:l,oldValue:r,newValue:l,changed:i,changedRows:this.changedRows,changedRowIds:this.changedRowIds});n&&r?(Object.keys(r).forEach(e=>{l[e]=r[e]}),o&&(this.#Ut.changedRowIds.delete(o),this.#Ut.committedDirtyRowIds.delete(o),this.clearRowInvalid(o))):n||(o&&this.config.dirtyTracking&&(this.#Ut.isRowDirty(o,l)?this.#Ut.committedDirtyRowIds.add(o):this.#Ut.committedDirtyRowIds.delete(o)),t&&this.isAnimationEnabled&&(this.#Gt=e))}this.#zt.delete(e),this.#Pt=-1,this.#Ht=void 0,this.#Dt=void 0,this.#Ft=-1,this.#Vt=!1,this.#ni();for(const a of this.#qt)a.startsWith(`${e}:`)&&this.#qt.delete(a);for(const a of this.#Ot.keys())a.startsWith(`${e}:`)&&this.#Ot.delete(a);this.#Nt=!0,n?(n.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.#ii(i),this.#Nt=!1),!this.#Mt&&l&&this.emit("edit-close",{rowIndex:e,rowId:o??"",row:l,reverted:t})}#Xt(e,t,i,r){const n=t.field;if(!ii(n))return;const o=r[n];if(o===i)return;const s=this.#bt;let l;try{l=this.grid.getRowId(r)}catch{}const a=!l||!this.#Ut.changedRowIds.has(l),d=l?e=>this.grid.updateRow(l,e,"cascade"):ri;let c=!1;const h=l?e=>{c=!0,this.setInvalid(l,n,e??"")}:()=>{};if(this.emitCancelable("cell-commit",{row:r,rowId:l??"",field:n,oldValue:o,value:i,rowIndex:e,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:a,updateRow:d,setInvalid:h}))return;if(l&&!c&&this.isCellInvalid(l,n)&&this.clearInvalid(l,n),r[n]=i,l&&this.#Ut.changedRowIds.add(l),this.#ni(),this.config.dirtyTracking&&l){const e=this.#Ut.isRowDirty(l,r);this.emit("dirty-change",{rowId:l,row:r,original:this.#Ut.getOriginalRow(l),type:e?"modified":"pristine"})}this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:n,oldValue:o,newValue:i});const u=s.findRenderedRowElement?.(e);u&&u.classList.add("changed")}#ri(e,t,i,r,n,o,s){oi(this.#jt,e,t,i,r,n,o,s)}#ii(e){queueMicrotask(()=>{try{const t=e._focusRow,i=e._focusCol,r=e.findRenderedRowElement?.(t);if(r){Array.from(e._bodyEl.querySelectorAll(".cell-focus")).forEach(e=>e.classList.remove("cell-focus"));const n=r.querySelector(`.cell[data-row="${t}"][data-col="${i}"]`);n&&(n.classList.add("cell-focus"),n.setAttribute("aria-selected","true"),n.hasAttribute("tabindex")||n.setAttribute("tabindex","-1"),n.focus({preventScroll:!0}))}}catch{}})}},e.ExportPlugin=class extends Ct{name="export";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;performExport(e,t){const i=this.config,r={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},n=St(this.columns,t?.columns,i.onlyVisible);let o;if(t?.rowIndices)o=_t(this.rows,t.rowIndices);else if(i.onlySelected){const e=this.getSelectionState();o=e?.selected?.size?_t(this.rows,[...e.selected]):[...this.rows]}else o=[...this.rows];this.isExportingFlag=!0;let s=r.fileName;try{switch(e){case"csv":{const e=function(e,t,i,r={}){const n=r.delimiter??",",o=r.newline??"\n",s=[],l=r.bom?"\ufeff":"";if(!1!==i.includeHeaders){const e=t.map(e=>{const t=e.header||e.field;return si(i.processHeader?i.processHeader(t,e.field):t)});s.push(e.join(n))}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)),si(t)});s.push(e.join(n))}return l+s.join(o)}(o,n,r,{bom:!0});s=s.endsWith(".csv")?s:`${s}.csv`,function(e,t){li(new Blob([e],{type:"text/csv;charset=utf-8;"}),t)}(e,s);break}case"excel":{const e=function(e,t,i){let r='<?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){r+="\n<Row>";for(const e of t){const t=e.header||e.field;r+=`<Cell><Data ss:Type="String">${ai(i.processHeader?i.processHeader(t,e.field):t)}</Data></Cell>`}r+="</Row>"}for(const n of e){r+="\n<Row>";for(const e of t){let t=n[e.field];i.processCell&&(t=i.processCell(t,e.field,n));let o="String",s="";null==t?s="":"number"!=typeof t||isNaN(t)?t instanceof Date?(o="DateTime",s=t.toISOString()):s=ai(String(t)):(o="Number",s=String(t)),r+=`<Cell><Data ss:Type="${o}">${s}</Data></Cell>`}r+="</Row>"}return r+="\n</Table>\n</Worksheet>\n</Workbook>",r}(o,n,r);s=s.endsWith(".xls")?s:`${s}.xls`,function(e,t){const i=t.endsWith(".xls")?t:`${t}.xls`;li(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 n){let n=e[i.field];r.processCell&&(n=r.processCell(n,i.field,e)),t[i.field]=n}return t}),t=JSON.stringify(e,null,2);s=s.endsWith(".json")?s:`${s}.json`;li(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:n.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=yi,e.FitModeEnum=i,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=xt,e.GridDataAttrs=Rt,e.GridElement=yt,e.GridSelectors=Et,e.GroupingColumnsPlugin=class extends Ct{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;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;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;#li=new Set;#ai=[];#di=new Map;attach(e){super.attach(e),this.gridElement.addEventListener("column-move",this.#ci,{signal:this.disconnectSignal})}detach(){this.groups=[],this.isActive=!1,this.#li.clear(),this.#ai=[],this.#di.clear()}#ci=e=>{if(!this.isActive)return;const t=e,{field:i,columnOrder:r}=t.detail;if(this.config.lockGroupOrder){const e=new Map;for(const t of this.groups){if(t.id.startsWith("__implicit__"))continue;const i=e.get(t.id);i?i.push(...t.columns):e.set(t.id,[...t.columns])}for(const[,n]of e)if(!this.#hi(n,r))return t.preventDefault(),void this.#ui(i)}this.#gi(r)};#gi(e){this.#li.clear();const t=new Map;for(const i of this.groups)for(const e of i.columns)t.set(e.field,i.id);for(let i=0;i<e.length-1;i++){t.get(e[i])!==t.get(e[i+1])&&this.#li.add(e[i])}}#hi(e,t){const i=e.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}#ui(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.#pi()}#pi(){let e;if(this.#ai.length>0)e=this.#ai.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){const t=new Map;for(const e of this.groups){if(e.id.startsWith("__implicit__"))continue;const i=t.get(e.id);if(i)for(const t of e.columns)i.fields.includes(t.field)||i.fields.push(t.field);else t.set(e.id,{id:e.id,label:e.label??e.id,fields:e.columns.map(e=>e.field)})}e=Array.from(t.values());const i=this.columns;for(const r of i)if(r.hidden&&r.group){const t="string"==typeof r.group?r.group:r.group.id,i="string"==typeof r.group?r.group:r.group.label??r.group.id,n=e.find(e=>e.id===t);n?n.fields.includes(r.field)||n.fields.push(r.field):e.push({id:t,label:i,fields:[r.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,r="string"==typeof e.group?e.group:e.group.label??e.group.id,n=i.get(t);n?n.fields.includes(e.field)||n.fields.push(e.field):i.set(t,{id:t,label:r,fields:[e.field]})}e=Array.from(i.values())}const t=this.grid?.getColumnOrder();if(t&&t.length>0){const i=new Map(t.map((e,t)=>[e,t]));for(const t of e)t.fields.sort((e,t)=>(i.get(e)??1/0)-(i.get(t)??1/0))}return e}static detect(e,t){const i=t?.features?.groupingColumns;if(i&&"object"==typeof i&&Array.isArray(i.columnGroups)&&i.columnGroups.length>0)return!0;if(t?.columnGroups&&Array.isArray(t.columnGroups)&&t.columnGroups.length>0)return!0;const r=t?.columns;return!!Array.isArray(r)&&function(e){return e.some(e=>null!=e.group)}(r)}processColumns(e){const t=this.config?.columnGroups,i=this.grid?.gridConfig?.columnGroups;let r,n;if(t&&Array.isArray(t)&&t.length>0?(i&&Array.isArray(i)&&i.length>0&&this.warn("TBW114","columnGroups defined in both gridConfig and groupingColumns feature config. Using feature config (higher precedence)."),r=t):i&&Array.isArray(i)&&i.length>0&&(r=i),r&&r.length>0){const t=r.map(e=>{return e.id?e:(e.header||h("TBW113",'ColumnGroupDefinition requires either an "id" or a "header" to generate an id from.'),{...e,id:(t=e.header,t.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))});var t});this.#ai=t,this.#di.clear();for(const e of t)e.renderer&&this.#di.set(e.id,e.renderer);const i=new Map;for(const e of t)for(const t of e.children)i.set(t,{id:e.id,label:e.header});n=e.map(e=>{const t=i.get(e.field);return t&&!e.group?{...e,group:t}:e})}else this.#ai=[],this.#di.clear(),n=[...e];const o=Ci(n);if(0===o.length)return this.isActive=!1,this.groups=[],n;if(this.#di.size>0)for(const s of o){const e=this.#di.get(s.id);e&&(s.renderer=e)}this.isActive=!0,this.groups=o,this.#li.clear();for(const s of o){const e=s.columns[s.columns.length-1];e?.field&&this.#li.add(e.field)}return n}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,r=Ci(i);if(0===r.length)return;if(this.#di.size>0)for(const l of r){const e=this.#di.get(l.id);e&&(l.renderer=e)}this.#li.clear();const n=Ei(r,Ri(r));for(let l=0;l<n.length;l++){const e=n[l],t=e.columns[e.columns.length-1];t?.field&&l<n.length-1&&this.#li.add(t.field)}const o=function(e,t,i){if(0===e.length)return null;const r=document.createElement("div");r.className="header-group-row",r.setAttribute("role","row");const n=Ei(e,Ri(e));for(const o of n){const e=String(o.id),n=e.startsWith("__implicit__"),s=xi(o,t);if(!s)continue;const[l,a]=s,d=a-l+1,c=n?"":o.label||o.id,h=document.createElement("div");h.className="cell header-group-cell",n&&h.classList.add("implicit-group"),h.setAttribute("data-group",e),h.style.gridColumn=`${l+1} / span ${d}`;const u=!n&&(o.renderer||i)||void 0;if(u&&!n){const t=u({id:e,label:String(c),columns:o.columns,firstIndex:l,isImplicit:!1});t instanceof HTMLElement?h.appendChild(t):"string"==typeof t?h.innerHTML=t:h.textContent=c}else h.textContent=c;r.appendChild(h)}return r}(r,i,this.config.groupHeaderRenderer);if(o){o.classList.toggle("no-borders",!this.config.showGroupBorders);const t=e.querySelector(".header-row");t?e.insertBefore(o,t):e.appendChild(o)}const s=e.querySelector(".header-row");s&&(s.classList.toggle("no-group-borders",!this.config.showGroupBorders),function(e,t){if(!t.length||!e)return;const i=Ri(t),r=Ei(t,i),n=new Map;for(const s of r)if(!String(s.id).startsWith("__implicit__"))for(const e of s.columns)e.field&&n.set(e.field,s.id);for(let s=0;s<t.length;s++){const e=t[s];if(String(e.id).startsWith("__implicit__")&&i.has(String(e.id)))for(let i=s-1;i>=0;i--)if(!String(t[i].id).startsWith("__implicit__")){for(const r of e.columns)r.field&&n.set(r.field,t[i].id);break}}const o=Array.from(e.querySelectorAll(".cell[data-field]"));o.forEach(e=>{const t=e.getAttribute("data-field")||"",i=n.get(t);i&&(e.classList.add("grouped"),e.getAttribute("data-group")||e.setAttribute("data-group",i))});for(const s of r){const e=s.columns[s.columns.length-1],t=o.find(t=>t.getAttribute("data-field")===e.field);t&&t.classList.add("group-end")}}(s,r))}afterCellRender(e){this.isActive&&this.config.showGroupBorders&&e.cellElement.classList.toggle("group-end",this.#li.has(e.column.field))}isGroupingActive(){return this.isActive}getGroups(){return this.groups}getGroupColumns(e){return this.groups.filter(t=>t.id===e).flatMap(e=>e.columns)}refresh(){this.requestRender()}},e.GroupingRowsPlugin=class extends Ct{static manifest={incompatibleWith:[{name:"tree",reason:"Both plugins transform the entire row model. TreePlugin flattens nested hierarchies while GroupingRowsPlugin groups flat rows with synthetic headers. Use one approach per grid."},{name:"pivot",reason:"PivotPlugin creates its own aggregated row and column structure. Row grouping cannot be applied on top of pivot-generated rows."},{name:"serverSide",reason:"Row grouping requires the full dataset to compute group boundaries. ServerSidePlugin lazy-loads rows in blocks, so groups cannot be built client-side."}],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=Li({rows:[...e],config:t,expanded:new Set});if(0===i.length)return this.isActive=!1,this.flattenedRows=[],[...e];let r;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);r=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),r.size>0&&(this.expandedKeys=new Set(r),this.hasAppliedDefaultExpanded=!0)}const n=Li({rows:[...e],config:t,expanded:this.expandedKeys,initialExpanded:r});this.isActive=!0,this.flattenedRows=n,this.keysToAnimate.clear();const o=new Set;return n.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,n.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 r=this.config;if(r.groupRowRenderer){const i=()=>{this.toggle(e.__groupKey)},n=r.groupRowRenderer({key:e.__groupKey,value:e.__groupValue,depth:e.__groupDepth,rows:e.__groupRows,expanded:e.__groupExpanded,toggleExpand:i});if(n)return t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),"string"==typeof n?t.innerHTML=n:(t.innerHTML="",t.appendChild(n)),!0}const n=()=>{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!==r.indentWidth&&t.style.setProperty("--tbw-group-indent-width",`${r.indentWidth}px`),t.style.height="",t.innerHTML="";return!1!==r.fullWidth?this.renderFullWidthGroupRow(e,t,n):this.renderPerColumnGroupRow(e,t,n),!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 r of t.querySelectorAll(".data-grid-row:not(.group-row)")){const e=r.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,n=this.flattenedRows[t],o="data"===n?.kind?`data-${t}`:void 0;o&&this.keysToAnimate.has(o)&&(r.classList.add(i),r.addEventListener("animationend",()=>r.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 r=this.config;return r.formatLabel?r.formatLabel(e,t,i):String(e)}renderFullWidthGroupRow(e,t,i){const r=this.config,n=r.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!==r.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(n);if(a.length>0){const e=document.createElement("span");e.className="group-aggregates";for(const[t,i]of a){const r=this.columns.find(e=>e.field===t),n=Mi(i,o,t,r);if(null!=n){const i=document.createElement("span");i.className="group-aggregate",i.setAttribute("data-field",t);const o=r?.header??t;i.textContent=`${o}: ${n}`,e.appendChild(i)}}e.children.length>0&&s.appendChild(e)}t.appendChild(s)}renderPerColumnGroupRow(e,t,i){const r=this.config,n=r.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"),pi(o))return a.setAttribute("data-field",o.field),void t.appendChild(a);if(d){const e=n[o.field];if(e){const t=Mi(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=n[o.field];if(l){const i=Mi(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!==r.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,r=this.flattenedRows.find(t=>"group"===t.kind&&t.key===e);if(i.accordion&&t&&r){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!==r.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:r?.value,depth:r?.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=Hi,e.MultiSortPlugin=class extends Ct{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;get#bt(){return this.grid}clearCoreSortState(){this.#bt._sortState=null}detach(){this.sortModel=[],this.cachedSortResult=null}processRows(e){if(0===this.sortModel.length)return this.cachedSortResult=null,[...e];const t=this.#bt;if(!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,r)=>{for(const n of t){const t=i.find(e=>e.field===n.field),o=(t?.sortComparator??Di)(e[n.field],r[n.field],e,r);if(0!==o)return"asc"===n.direction?o:-o}return 0}):[...e]}([...e],this.sortModel,[...this.columns]);return this.cachedSortResult=i,i}onHeaderClick(e){const i=this.columns.find(t=>t.field===e.field);if(!i?.sortable)return!1;const r=e.originalEvent.shiftKey,n=this.config.maxSortColumns??3;if(this.sortModel=function(e,t,i,r){const n=e.find(e=>e.field===t);return i?n?"asc"===n.direction?e.map(e=>e.field===t?{...e,direction:"desc"}:e):e.filter(e=>e.field!==t):e.length<r?[...e,{field:t,direction:"asc"}]:e:"asc"===n?.direction?[{field:t,direction:"desc"}]:"desc"===n?.direction?[]:[{field:t,direction:"asc"}]}(this.sortModel,e.field,r,n),this.clearCoreSortState(),this.emit("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),this.grid?.requestStateChange?.(),this.sortModel.length>0){const e=this.sortModel.map(e=>{const t=this.columns.find(t=>t.field===e.field);return`${t?.header??e.field} ${"asc"===e.direction?"ascending":"descending"}`});t(this.gridElement,`Sorted by ${e.join(", then ")}`)}else t(this.gridElement,"Sort cleared");return!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 r=Fi(this.sortModel,i),n=zi(this.sortModel,i),o=e.querySelector(".sort-index");if(o?.remove(),n){const i=e.querySelector('[part~="sort-indicator"], .sort-indicator');i?.remove(),e.setAttribute("data-sort",n);const o=document.createElement("span");o.className="sort-indicator",this.setIcon(o,this.resolveIcon("asc"===n?"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!==r){const t=document.createElement("span");t.className="sort-index",t.textContent=String(r),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){if(this.sortModel=[...e],this.clearCoreSortState(),this.emit("sort-change",{sortModel:[...e]}),this.requestRender(),this.grid?.requestStateChange?.(),e.length>0){const i=e.map(e=>{const t=this.columns.find(t=>t.field===e.field);return`${t?.header??e.field} ${"asc"===e.direction?"ascending":"descending"}`});t(this.gridElement,`Sorted by ${i.join(", then ")}`)}}clearSort(){this.sortModel=[],this.clearCoreSortState(),this.emit("sort-change",{sortModel:[]}),this.requestRender(),this.grid?.requestStateChange?.(),t(this.gridElement,"Sort cleared")}getSortIndex(e){return Fi(this.sortModel,e)}getSortDirection(e){return zi(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),r={field:e,direction:t.sort.direction};-1!==i?this.sortModel[i]=r:this.sortModel.splice(t.sort.priority,0,r),this.clearCoreSortState()}},e.PLUGIN_QUERIES={CAN_MOVE_COLUMN:"canMoveColumn",GET_CONTEXT_MENU_ITEMS:"getContextMenuItems"},e.PinnedColumnsPlugin=class extends Ct{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}],queries:[{type:Ui,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;#fi={addGroupEnd:new Set,removeGroupEnd:new Set};#wi=[];detach(){this.leftOffsets.clear(),this.rightOffsets.clear(),this.isApplied=!1,this.#fi={addGroupEnd:new Set,removeGroupEnd:new Set},this.#wi=[]}static detect(e,t){const i=t?.columns;return!!Array.isArray(i)&&$i(i)}processColumns(e){const t=[...e];if(this.isApplied=$i(t),!this.isApplied)return t;const i=this.gridElement;return function(e,t="ltr"){const i=[],r=[],n=[];for(const o of e){const e=qi(o);e?"left"===Oi(e,t)?i.push(o):n.push(o):r.push(o)}return[...i,...r,...n]}(t,i?ee(i):"ltr")}afterRender(){if(!this.isApplied)return;const e=this.gridElement,t=[...this.columns];if(!$i(t))return Ki(e),void(this.isApplied=!1);queueMicrotask(()=>{this.#fi=Wi(e,t)})}afterCellRender(e){if(!this.isApplied)return;const t=e.column.field;this.#fi.addGroupEnd.has(t)?e.cellElement.classList.add("group-end"):this.#fi.removeGroupEnd.has(t)&&e.cellElement.classList.remove("group-end")}handleQuery(e){switch(e.type){case Ui:return null==qi(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 r=[];return null!=qi(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 r=i.findIndex(t=>t.field===e);if(-1===r)return;const n=this.gridElement;if(t){0===this.#wi.length&&(this.#wi=i.map(e=>e.field));const r=i.map(i=>{if(i.field!==e)return i;const r={...i};return r.pinned=t,delete r.sticky,r});n.columns=r}else{const t={...i[r]};delete t.pinned,delete t.sticky;const o=[...i];o.splice(r,1);const s=this.#wi.indexOf(e);if(s>=0){let e=o.length;for(let t=0;t<o.length;t++){if(qi(o[t]))continue;if(this.#wi.indexOf(o[t].field)>s){e=t;break}}o.splice(e,0,t)}else o.splice(Math.min(r,o.length),0,t);o.some(e=>null!=qi(e))||(this.#wi=[]),n.columns=o}}refreshStickyOffsets(){const e=[...this.columns];Wi(this.gridElement,e)}getLeftPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>Ni(e,t))}([...this.columns],ee(this.gridElement))}getRightPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>Gi(e,t))}([...this.columns],ee(this.gridElement))}clearStickyPositions(){Ki(this.gridElement)}getHorizontalScrollOffsets(e,t){if(!this.isApplied)return;let i=0,r=0;if(e){const t=e.querySelectorAll(".sticky-left"),n=e.querySelectorAll(".sticky-right");t.forEach(e=>{i+=e.offsetWidth}),n.forEach(e=>{r+=e.offsetWidth})}else{this.gridElement.querySelectorAll(".header-row .cell").forEach(e=>{e.classList.contains("sticky-left")?i+=e.offsetWidth:e.classList.contains("sticky-right")&&(r+=e.offsetWidth)})}const n=t?.classList.contains("sticky-left")||t?.classList.contains("sticky-right");return{left:i,right:r,skipScroll:n}}},e.PinnedRowsPlugin=class extends Ct{name="pinnedRows";styles="@layer tbw-plugins{.tbw-scroll-area{container-type:inline-size}.tbw-footer{flex-shrink:0;z-index:var(--tbw-z-layer-pinned-rows, 20);background:var(--tbw-color-panel-bg);min-width:fit-content}.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;position:sticky;left:0;min-width:0;width:100cqi}.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);position:relative;background:inherit}.tbw-aggregation-row>.tbw-aggregation-label{position:sticky;left:0;grid-row:1;grid-column:1;display:flex;align-items:center;padding:var(--tbw-cell-padding, .125rem .5rem);background:inherit;z-index:1;pointer-events:none}.tbw-aggregation-row>.tbw-aggregation-cell:first-child{grid-column:1;grid-row:1}.tbw-aggregation-cell:not(:empty){position:relative;z-index:2;background:inherit}.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.querySelector(".tbw-grid-root");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(),r=this.getFilterState(),n=tr(this.sourceRows,this.columns,this.gridElement,i,r),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=Yi("top");const i=e.querySelector(".header");i&&i.nextSibling?t.insertBefore(this.topAggregationContainer,i.nextSibling):t.appendChild(this.topAggregationContainer)}Xi(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&&n.selectedRows>0||this.config.showFilteredCount&&n.filteredRows!==n.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=ji(this.config,n);this.infoBarElement.replaceWith(e),this.infoBarElement=e}else this.infoBarElement=ji(this.config,n),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=Yi("bottom")),this.footerWrapper.appendChild(this.bottomAggregationContainer),Xi(this.bottomAggregationContainer,l,this.visibleColumns,this.sourceRows,this.config.fullWidth)),d&&(this.infoBarElement=ji(this.config,n),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 tr(this.rows,this.columns,this.gridElement,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=fr,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=vt,e.PrintPlugin=class extends Ct{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}}}";#mi=!1;#bi=null;#vi=null;#yi=null;#Ci=null;#xi=null;#Ri=null;get#bt(){return this.grid}isPrinting(){return this.#mi}async print(e){if(this.#mi)return void this.warn("TBW090","Print already in progress");const t=this.gridElement;if(!t)return void this.warn("TBW091","Grid not available");const i={...br,...this.config,...e},r=this.rows.length;let n=r,o=!1;if(i.warnThreshold>0&&r>i.warnThreshold){const e=i.maxRows>0?`\n\nNote: Output will be limited to ${i.maxRows.toLocaleString()} rows.`:"";if(!confirm(`This grid has ${r.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&&r>i.maxRows&&(n=i.maxRows,o=!0),this.#mi=!0;const s=performance.now();this.emit("print-start",{rowCount:n,limitApplied:o,originalRowCount:r});try{const e=this.#bt;this.#vi={bypassThreshold:e._virtualization?.bypassThreshold??24},this.#Ei(),o&&(this.#yi=this.sourceRows,this.grid.rows=this.sourceRows.slice(0,n),await new Promise(e=>setTimeout(e,50))),(i.includeTitle||i.includeTimestamp)&&this.#Si(i),await this.#_i(),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.#Ai(i):await this.#ki(),this.emit("print-complete",{success:!0,rowCount:n,duration:Math.round(performance.now()-s)})}catch(l){p("TBW092",`Print failed: ${l}`,this.gridElement?.id,this.name),this.emit("print-complete",{success:!1,rowCount:0,duration:Math.round(performance.now()-s)})}finally{this.#Ti(),this.#mi=!1}}#Si(e){const t=this.gridElement;if(t){if(this.#Ci=document.createElement("div"),this.#Ci.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.#Ci.appendChild(i)}if(e.includeTimestamp){const e=document.createElement("div");e.className="tbw-print-header-timestamp",e.textContent=`Printed: ${(new Date).toLocaleString()}`,this.#Ci.appendChild(e)}t.insertBefore(this.#Ci,t.firstChild),this.#xi=document.createElement("div"),this.#xi.className="tbw-print-footer",this.#xi.textContent=`Page generated from ${window.location.hostname}`,t.appendChild(this.#xi)}}async#_i(){const e=this.#bt;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#ki(){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#Ai(e){const t=this.gridElement;t&&await mr(t,{orientation:e.orientation})}#Ei(){const e=this.columns;if(e){this.#bi=new Map;for(const t of e)t.printHidden&&t.field&&(this.#bi.set(t.field,!t.hidden),this.grid.setColumnVisible(t.field,!1))}}#Mi(){if(this.#bi){for(const[e,t]of this.#bi)this.grid.setColumnVisible(e,t);this.#bi=null}}#Ti(){const e=this.gridElement;if(!e)return;this.#Mi(),e.classList.remove("print-portrait","print-landscape"),null!==this.#Ri&&(e.style.transform="",e.style.transformOrigin="",e.style.width="",this.#Ri=null),this.#Ci&&(this.#Ci.remove(),this.#Ci=null),this.#xi&&(this.#xi.remove(),this.#xi=null);const t=this.#bt;this.#vi&&t._virtualization&&(t._virtualization.bypassThreshold=this.#vi.bypassThreshold,t.refreshVirtualWindow(!0),this.#vi=null),null!==this.#yi&&(this.grid.rows=this.#yi,this.#yi=null)}afterRender(){this.config?.button&&!this.#Li&&(this.#Ii(),this.#Li=!0)}#Li=!1;#Ii(){const e=this.#bt;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=yr,e.RenderPhase=K,e.ReorderPlugin=class extends Ct{name="reorderColumns";aliases=["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;draggedGroupFields=[];get#bt(){return this.grid}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, .header-group-row > .cell").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),this.gridElement.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,this.draggedGroupFields=[]}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 r=this.columns.find(e=>e.field===i);this.canMoveColumnWithPlugins(r)?(t.draggable=!0,t.getAttribute("data-dragstart-bound")||(t.setAttribute("data-dragstart-bound","true"),t.addEventListener("dragstart",e=>{const r=this.getColumnOrder().indexOf(i);this.isDragging=!0,this.draggedField=i,this.draggedIndex=r,this.draggedGroupFields=[],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.draggedGroupFields=[],this.clearDragClasses()}),t.addEventListener("dragover",e=>{if(e.preventDefault(),!this.isDragging)return;if(this.draggedField===i&&0===this.draggedGroupFields.length)return;if(this.draggedGroupFields.includes(i))return;const r=t.getBoundingClientRect(),n=r.left+r.width/2,o=this.getColumnOrder().indexOf(i);if(this.dropIndex=e.clientX<n?o:o+1,this.clearDragClasses(),this.draggedGroupFields.length>0)for(const t of this.draggedGroupFields)this.gridElement?.querySelector(`.header-row > .cell[data-field="${t}"]`)?.classList.add("dragging");else this.draggedField&&this.gridElement?.querySelector(`.header-row > .cell[data-field="${this.draggedField}"]`)?.classList.add("dragging");t.classList.add("drop-target"),t.classList.toggle("drop-before",e.clientX<n),t.classList.toggle("drop-after",e.clientX>=n)}),t.addEventListener("dragleave",()=>{t.classList.remove("drop-target","drop-before","drop-after")}),t.addEventListener("drop",e=>{if(e.preventDefault(),!this.isDragging)return;if(this.draggedGroupFields.length>0){if(this.draggedGroupFields.includes(i))return;const r=t.getBoundingClientRect(),n=e.clientX<r.left+r.width/2;return void this.executeGroupBlockMove(this.draggedGroupFields,[i],n)}const r=this.draggedField,n=this.draggedIndex,o=this.dropIndex;if(!this.isDragging||null===r||null===n||null===o)return;const s=o>n?o-1:o,l=vr(this.getColumnOrder(),n,s),a={field:r,fromIndex:n,toIndex:s,columnOrder:l};this.emitCancelable("column-move",a)||this.updateColumnOrder(l)}))):t.draggable=!1}),queueMicrotask(()=>this.setupGroupHeaderDrag(e))}setupGroupHeaderDrag(e){e.querySelectorAll(".header-group-row > .cell[data-group]").forEach(t=>{const i=t,r=i.getAttribute("data-group");if(!r||r.startsWith("__implicit__"))return;if(i.getAttribute("data-group-drag-bound"))return;i.setAttribute("data-group-drag-bound","true");const n=this.getGroupFragmentFields(i,r);if(0===n.length)return;n.every(e=>{const t=this.columns.find(t=>t.field===e);return this.canMoveColumnWithPlugins(t)})&&(i.draggable=!0,i.style.cursor="grab",i.addEventListener("dragstart",t=>{this.isDragging=!0,this.draggedField=null,this.draggedIndex=null,this.draggedGroupFields=[...n],t.dataTransfer&&(t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",`group:${r}`)),i.classList.add("dragging");for(const i of n)e.querySelector(`.header-row > .cell[data-field="${i}"]`)?.classList.add("dragging")}),i.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.draggedGroupFields=[],this.clearDragClasses()}),i.addEventListener("dragover",e=>{if(e.preventDefault(),!this.isDragging)return;if(this.draggedGroupFields.length>0&&this.draggedGroupFields.length===n.length&&this.draggedGroupFields.every(e=>n.includes(e)))return;const t=i.getBoundingClientRect(),r=t.left+t.width/2,o=e.clientX<r;this.clearDragClasses(),i.classList.add("drop-target"),i.classList.toggle("drop-before",o),i.classList.toggle("drop-after",!o)}),i.addEventListener("dragleave",()=>{i.classList.remove("drop-target","drop-before","drop-after")}),i.addEventListener("drop",e=>{if(e.preventDefault(),!this.isDragging)return;const t=i.getBoundingClientRect(),r=e.clientX<t.left+t.width/2;if(this.draggedGroupFields.length>0){if(this.draggedGroupFields.length===n.length&&this.draggedGroupFields.every(e=>n.includes(e)))return;this.executeGroupBlockMove(this.draggedGroupFields,n,r)}else if(this.draggedField){const e=this.getColumnOrder(),t=r?n[0]:n[n.length-1],i=e.indexOf(this.draggedField),o=r?e.indexOf(t):e.indexOf(t)+1;if(-1===i||-1===o)return;const s=o>i?o-1:o,l=vr(e,i,s);this.emitCancelable("column-move",{field:this.draggedField,fromIndex:i,toIndex:s,columnOrder:l})||this.updateColumnOrder(l)}}))})}getGroupFragmentFields(e,t){const i=e.style.gridColumn,r=/(\d+)\s*\/\s*span\s+(\d+)/.exec(i);if(!r)return[];const n=parseInt(r[1],10),o=parseInt(r[2],10),s=this.visibleColumns,l=[];for(let a=n-1;a<n-1+o&&a<s.length;a++){const e=s[a];e&&l.push(e.field)}return l}executeGroupBlockMove(e,t,i){const r=this.getColumnOrder(),n=r.filter(t=>!e.includes(t)),o=i?t[0]:t[t.length-1],s=n.indexOf(o);if(-1===s)return;const l=i?s:s+1,a=r.filter(t=>e.includes(t));n.splice(l,0,...a);this.emitCancelable("column-move",{field:e[0],fromIndex:r.indexOf(e[0]),toIndex:l,columnOrder:n})||this.updateColumnOrder(n)}onKeyDown(e){if(!e.altKey||"ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;const t=this.#bt,i=t._focusCol,r=t._visibleColumns;if(i<0||i>=r.length)return;const n=r[i];if(!this.canMoveColumnWithPlugins(n))return;const o=this.getColumnOrder(),s=o.indexOf(n.field);if(-1===s)return;const l="ArrowLeft"===e.key?s-1:s+1;if(l<0||l>=o.length)return;const a=r.find(e=>e.field===o[l]);return this.canMoveColumnWithPlugins(a)?(this.moveColumn(n.field,l),t._focusCol=l,fe(this.#bt),e.preventDefault(),e.stopPropagation(),!0):void 0}getColumnOrder(){return this.grid.getColumnOrder()}moveColumn(e,t){const i=this.getColumnOrder(),r=i.indexOf(e);if(-1===r)return;const n=vr(i,r,t);this.emitCancelable("column-move",{field:e,fromIndex:r,toIndex:t,columnOrder:n})||this.updateColumnOrder(n)}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 r=t.getAttribute("data-field");if(!r)return;const n=e.get(r);if(void 0===n)return;const o=n-t.getBoundingClientRect().left;Math.abs(o)>1&&i.set(r,o)}),0===i.size)return;const r=[];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)`,r.push(i)}}),0===r.length)return;t.offsetHeight;const n=this.animationDuration;requestAnimationFrame(()=>{r.forEach(e=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{r.forEach(e=>{e.style.transform="",e.classList.remove("flip-animating")})},n+50)})}animateFade(e){const t=this.gridElement;if(!t)return void e();const i=this.captureHeaderPositions();e();const r=new Set;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(!t)return;const n=i.get(t);if(void 0===n)return;const o=e.getBoundingClientRect().left;Math.abs(n-o)>1&&r.add(t)}),0===r.size)return;const n=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(t&&r.has(t)){const t=e;t.classList.add("fade-animating"),n.push(t)}}),0===n.length)return;const o=this.animationDuration;setTimeout(()=>{n.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),"function"==typeof this.grid.forceLayout?this.grid.forceLayout().then(()=>{this.animateFLIP(t)}):requestAnimationFrame(()=>{this.animateFLIP(t)})}else"fade"===t?this.animateFade(()=>this.grid.setColumnOrder(e)):this.grid.setColumnOrder(e);this.grid.requestStateChange?.()}},e.ResponsivePlugin=class extends Ct{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] .data-grid-row>.cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .data-grid-row>.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={queries:[{type:"isCardMode",description:"Returns whether the grid is currently in responsive card mode"}]};#J;#Pi=!1;#Hi;#Di=!1;#Fi=0;#zi=new Set;#qi=new Set;#Oi=null;#Ni=[];get#bt(){return this.grid}isResponsive(){return this.#Pi}setResponsive(e){e!==this.#Pi&&(this.#Pi=e,this.#Gi(),this.emit("responsive-change",{isResponsive:e,width:this.#Fi,breakpoint:this.config.breakpoint??0}),this.requestRender())}setBreakpoint(e){this.config.breakpoint=e,this.#$i(this.#Fi)}setCardRenderer(e){this.config.cardRenderer=e,this.#Pi&&this.requestRender()}getWidth(){return this.#Fi}getActiveBreakpoint(){return this.#Oi}attach(e){super.attach(e),this.#Wi(),this.#Bi(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#Ni=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#J=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#Fi=t,clearTimeout(this.#Hi),this.#Hi=setTimeout(()=>{this.#$i(t)},this.config.debounceMs??100)}),this.#J.observe(this.gridElement)}#Wi(){const e=this.gridElement;if(!e)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const i=this.#bt.__frameworkAdapter;if(i?.parseResponsiveCardElement){const e=i.parseResponsiveCardElement(t);e&&(this.config={...this.config,cardRenderer:e})}const r=t.getAttribute("breakpoint"),n=t.getAttribute("card-row-height"),o=t.getAttribute("hidden-columns"),s=t.getAttribute("hide-header"),l=t.getAttribute("debounce-ms"),a={};if(null!==r){const e=parseInt(r,10);isNaN(e)||(a.breakpoint=e)}if(null!==n&&(a.cardRowHeight="auto"===n?"auto":parseInt(n,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?.parseResponsiveCardElement||(a.cardRenderer=e=>{const t=T(M(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})}#Bi(e){if(this.#zi.clear(),this.#qi.clear(),e)for(const t of e)"string"==typeof t?this.#zi.add(t):t.showValue?this.#qi.add(t.field):this.#zi.add(t.field)}detach(){this.#J?.disconnect(),this.#J=void 0,clearTimeout(this.#Hi),this.#Hi=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#Pi}afterRender(){this.#Vi();if(!(this.#Ni.length>0?null!==this.#Oi:this.#Pi))return;const e=this.#zi.size>0,t=this.#qi.size>0;if(!e&&!t)return;const i=this.gridElement.querySelectorAll(".cell[data-field]");for(const r of i){const e=r.getAttribute("data-field");e&&(this.#zi.has(e)?(r.setAttribute("data-responsive-hidden",""),r.removeAttribute("data-responsive-value-only")):this.#qi.has(e)?(r.setAttribute("data-responsive-value-only",""),r.removeAttribute("data-responsive-hidden")):(r.removeAttribute("data-responsive-hidden"),r.removeAttribute("data-responsive-value-only")))}}#$i(e){if(this.#Ni.length>0)return void this.#Ki(e);const t=this.config.breakpoint??0;0!==t||this.#Di||(this.#Di=!0,this.warn("TBW110","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.#Pi&&(this.#Pi=i,this.#Gi(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#Ki(e){let t=null;for(const i of this.#Ni)e<=i.maxWidth&&(t=i);if(t!==this.#Oi){this.#Oi=t,t?.hiddenColumns?this.#Bi(t.hiddenColumns):this.#Bi(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#Pi&&(this.#Pi=i,this.#Gi()),this.emit("responsive-change",{isResponsive:this.#Pi,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#Ui;#Gi(){this.gridElement.toggleAttribute("data-responsive",this.#Pi);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.#bt;if(this.#Pi){t._virtualization&&(this.#Ui=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.#Ui&&this.#Ui>0&&t._virtualization&&(t._virtualization.rowHeight=this.#Ui,this.#Ui=void 0),this.#ji=void 0,this.#Yi=void 0,this.#Xi=void 0}}renderRow(e,t,i){if(!this.#Pi||!this.config.cardRenderer)return;if(e.__isGroupRow)return;t.replaceChildren();const r=this.config.cardRenderer(e,i);t.className="data-grid-row responsive-card";const n=this.config.cardRowHeight;return t.style.height="auto"===n||void 0===n?"auto":`${this.#Zi()}px`,t.appendChild(r),!0}onKeyDown(e){if(!this.#Pi)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(),fe(this.#bt),!0;if(this.grid._focusRow<t)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),fe(this.#bt),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),fe(this.#bt),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=i,e.preventDefault(),fe(this.#bt),!0;break;case"ArrowRight":if(this.grid._focusRow<t)return this.grid._focusRow+=1,e.preventDefault(),fe(this.#bt),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),fe(this.#bt),!0}return!1}#ji;#Yi;#Xi;#Zi(){if(this.#ji&&this.#ji>0)return this.#ji;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#Qi(){return this.#Yi&&this.#Yi>0?this.#Yi:this.#Ui??28}#Ji(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}#er(){let e=0,t=0;for(const i of this.rows)i.__isGroupRow?e++:t++;return{groupCount:e,cardCount:t}}getExtraHeight(){if(!this.#Pi||!this.config.cardRenderer)return 0;if(!this.#Ji())return 0;const e=this.#Ui??28,t=this.#Qi(),i=this.#Zi(),{groupCount:r,cardCount:n}=this.#er();return r*Math.max(0,t-e)+n*Math.max(0,i-e)}getExtraHeightBefore(e){if(!this.#Pi||!this.config.cardRenderer)return 0;if(!this.#Ji())return 0;const t=this.#Ui??28,i=this.#Qi(),r=this.#Zi(),n=Math.max(0,i-t),o=Math.max(0,r-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*n+l*o}getRowHeight(e,t){if(this.#Pi&&this.config.cardRenderer)return e.__isGroupRow?this.#Qi():this.#Zi()}#tr(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#ir=!1;#Vi(){if(!this.#Pi)return;let e=!1;const t=this.#bt,i=this.#Ji(),r=this.#tr();if(r!==this.#Xi&&(this.#Xi=r,e=!0),i){const t=this.gridElement.querySelector(".data-grid-row.group-row");if(t){const i=t.getBoundingClientRect().height;i>0&&i!==this.#Yi&&(this.#Yi=i,e=!0)}}const n=this.config.cardRenderer?".data-grid-row.responsive-card":".data-grid-row:not(.group-row)",o=this.gridElement.querySelector(n);if(o){const r=o.getBoundingClientRect().height;r>0&&r!==this.#ji&&(this.#ji=r,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=r))}e&&!this.#ir&&(this.#ir=!0,queueMicrotask(()=>{this.#ir=!1,this.grid&&this.#Pi&&this.#bt.refreshVirtualWindow?.(!0,!0)}))}},e.RowReorderPlugin=class extends Ct{name="reorderRows";aliases=["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;get#bt(){return this.grid}attach(e){super.attach(e),this.setupDelegatedDragListeners()}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:yr,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(){}onKeyDown(e){if(!this.config.enableKeyboard)return;if(!e.ctrlKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key)return;const t=this.#bt,i=t._focusRow,r=t._rows??this.sourceRows;if(i<0||i>=r.length)return;const n="ArrowUp"===e.key?"up":"down",o="up"===n?i-1:i+1;if(o<0||o>=r.length)return;const s=r[i];return!this.config.canMove||this.config.canMove(s,i,o,n)?(this.handleKeyboardMove(s,i,o,n,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 r=t<e?"up":"down",n=i[e];this.config.canMove&&!this.config.canMove(n,e,t,r)||this.executeMove(n,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 r=t<e?"up":"down";return this.config.canMove(i[e],e,t,r)}setupDelegatedDragListeners(){const e=this.gridElement;if(!e)return;const t=this.disconnectSignal;e.addEventListener("dragstart",e=>{const t=e,i=t.target.closest(".dg-row-drag-handle");if(!i)return;const r=i.closest(".data-grid-row");if(!r)return;const n=this.getRowIndex(r);n<0||(this.isDragging=!0,this.draggedRowIndex=n,t.dataTransfer&&(t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",String(n))),r.classList.add("dragging"))},{signal:t}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.clearDragClasses()},{signal:t}),e.addEventListener("dragover",e=>{const t=e;if(!this.isDragging||null===this.draggedRowIndex)return;const i=t.target.closest(".data-grid-row");if(!i)return;t.preventDefault();const r=this.getRowIndex(i);if(r<0||r===this.draggedRowIndex)return;const n=i.getBoundingClientRect(),o=n.top+n.height/2,s=t.clientY<o;this.dropRowIndex=s?r:r+1,i.classList.add("drop-target"),i.classList.toggle("drop-before",s),i.classList.toggle("drop-after",!s)},{signal:t}),e.addEventListener("dragleave",e=>{const t=e.target.closest(".data-grid-row");t&&t.classList.remove("drop-target","drop-before","drop-after")},{signal:t}),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],r=i<t?"up":"down";this.config.canMove&&!this.config.canMove(e,t,i,r)||this.executeMove(e,t,i,"drag")}},{signal:t})}handleKeyboardMove(e,t,i,r,n){this.pendingMove?this.pendingMove.currentIndex=i:this.pendingMove={originalIndex:t,currentIndex:i,row:e},this.lastFocusCol=n;const o=this.#bt,s=[...o._rows??this.sourceRows],[l]=s.splice(t,1);s.splice(i,0,l),o._rows=s,o._focusRow=i,o._focusCol=n,o.refreshVirtualWindow(!0),fe(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 r={row:i,fromIndex:e,toIndex:t,rows:[...this.sourceRows],source:"keyboard"};if(this.emitCancelable("row-move",r)){const i=[...this.sourceRows],[r]=i.splice(t,1);i.splice(e,0,r);const n=this.#bt;n._rows=i,n._focusRow=e,n._focusCol=this.lastFocusCol,n.refreshVirtualWindow(!0),fe(n)}}executeMove(e,t,i,r){const n=[...this.sourceRows],[o]=n.splice(t,1);n.splice(i,0,o);const s={row:e,fromIndex:t,toIndex:i,rows:n,source:r};if(!this.emitCancelable("row-move",s))if("flip"===this.animationType&&this.gridElement){const e=this.captureRowPositions();this.grid.rows=n,requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(e,t,i)})}else this.grid.rows=n}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 r=this.gridElement;if(!r||0===e.size)return;const n=Math.min(t,i),o=Math.max(t,i),s=[];if(r.querySelectorAll(".data-grid-row").forEach(r=>{const l=r,a=this.getRowIndex(l);if(a<0||a<n||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)`}),r.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 Ct{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:has(.selection)[data-selection-mode=row] .cell-focus,tbw-grid:has(.selection)[data-selection-mode=row] .row-focus,tbw-grid:has(.selection)[data-selection-mode=range] .cell-focus{outline: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-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;pendingRowKeyUpdate=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 r=this.rows[e];if(!r)return!1;return i(r,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.pendingRowKeyUpdate=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:r}=e,{mode:n,triggerOn:o="click"}=this.config;if(r.type!==o)return!1;const s=e.column,l=s&&fi(s);if("cell"===n){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.#rr()),this.requestAfterRender()),!1}if("row"===n){if(!this.isRowSelectable(t))return!1;const e=!1!==this.config.multiSelect,i=r.shiftKey&&e,n=(r.ctrlKey||r.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);n||this.selected.clear();for(let t=e;t<=i;t++)this.isRowSelectable(t)&&this.selected.add(t)}else if(n||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.#rr()),this.requestAfterRender(),!1}if("range"===n){if(l)return!1;if(!this.isCellSelectable(t,i))return!1;const e=r.shiftKey,n=(r.ctrlKey||r.metaKey)&&!1!==this.config.multiSelect;if(e&&this.cellAnchor){const e=_r(this.cellAnchor,{row:t,col:i}),r=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(r&&Ar(r,e))return!1;n?this.ranges.length>0?this.ranges[this.ranges.length-1]=e:this.ranges.push(e):this.ranges=[e],this.activeRange=e}else if(n){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&&Ar(this.ranges[0],e))return!1;this.ranges=[e],this.activeRange=e,this.cellAnchor={row:t,col:i}}return this.emit("selection-change",this.#rr()),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.#rr()),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.#rr()),this.requestAfterRender()}),!1;if("row"===t){const t=!1!==this.config.multiSelect;if("ArrowUp"===e.key||"ArrowDown"===e.key||"PageUp"===e.key||"PageDown"===e.key||(e.ctrlKey||e.metaKey)&&("Home"===e.key||"End"===e.key)){const i=e.shiftKey&&t;return i&&null===this.anchor&&(this.anchor=this.grid._focusRow),this.explicitSelection=!0,this.pendingRowKeyUpdate={shiftKey:i},queueMicrotask(()=>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&&fi(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,r=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&!1!==this.config.multiSelect,n={startRow:t,startCol:i,endRow:t,endCol:i};return!r&&1===this.ranges.length&&Ar(this.ranges[0],n)?(this.cellAnchor={row:t,col:i},!0):(this.cellAnchor={row:t,col:i},r||(this.ranges=[]),this.ranges.push(n),this.activeRange=n,this.emit("selection-change",this.#rr()),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&&fi(i)){const e=this.visibleColumns.findIndex(e=>!fi(e));e>=0&&(t=e)}const r=_r(this.cellAnchor,{row:e.rowIndex,col:t}),n=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return n&&Ar(n,r)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=r:this.ranges.push(r),this.activeRange=r,this.emit("selection-change",this.#rr()),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===kr))return e;const t=this.#nr(),i=e.findIndex(pi),r=i>=0?i+1:0;return[...e.slice(0,r),t,...e.slice(r)]}return e}#nr(){return{field:kr,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}}}#or(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const t=e.closest(".cell"),i=t?Q(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 r=i>0&&this.selected.size>=i,n=this.selected.size>0;t.checked=r,t.indeterminate=n&&!r}}#sr(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.#rr()))))}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.#rr()))}}}#lr(){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 r=e.querySelectorAll(".data-grid-row");if(r.forEach(e=>{e.classList.remove("selected","row-focus"),e.setAttribute("aria-selected","false"),i&&e.removeAttribute("data-selectable")}),"row"===t&&(J(e),r.forEach(e=>{const t=Q(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"),e.setAttribute("aria-selected","true")))}),this.config.checkbox&&this.#or(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){J(e);const t=this.ranges.map(Cr),i=(e,i)=>{for(const r of t)if(e>=r.startRow&&e<=r.endRow&&i>=r.startCol&&i<=r.endCol)return!0;return!1};e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),r=parseInt(e.getAttribute("data-col")??"-1",10);if(t>=0&&r>=0){const n=this.visibleColumns[r];if(n&&fi(n))return;i(t,r)&&(e.classList.add("selected"),e.setAttribute("aria-selected","true"),i(t-1,r)||e.classList.add("top"),i(t+1,r)||e.classList.add("bottom"),i(t,r-1)||e.classList.add("first"),i(t,r+1)||e.classList.add("last"))}})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root"),{mode:i}=this.config;if(this.pendingRowKeyUpdate&&"row"===i){const{shiftKey:e}=this.pendingRowKeyUpdate;this.pendingRowKeyUpdate=null;const t=this.grid._focusRow;if(e&&null!==this.anchor){this.selected.clear();const e=Math.min(this.anchor,t),i=Math.max(this.anchor,t);for(let t=e;t<=i;t++)this.isRowSelectable(t)&&this.selected.add(t)}else this.isRowSelectable(t)?(this.selected.clear(),this.selected.add(t),this.anchor=t):this.selected.clear();this.lastSelected=t,this.emit("selection-change",this.#rr())}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=_r(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.#rr())}this.#sr(i),this.gridElement.setAttribute("data-selection-mode",i),t&&t.classList.toggle("selecting",this.isDragging),this.#lr()}onScrollRender(){this.isSelectionEnabled()&&this.#lr()}getSelection(){return{mode:this.config.mode,ranges:this.#rr().ranges,anchor:this.cellAnchor}}getSelectedCells(){return function(e){const t=new Map;for(const i of e)for(const e of Sr(i))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return Er(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.#rr()),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.#rr()),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.#rr()),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 r=Math.max(0,Math.min(i.startRow,i.endRow)),n=Math.min(t.length-1,Math.max(i.startRow,i.endRow));for(let t=r;t<=n;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:Rr(this.ranges)}),this.requestAfterRender()}#rr(){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 r=[...t.selected].sort((e,t)=>e-t),n=[];let o=r[0],s=o;for(let e=1;e<r.length;e++)r[e]===s+1?s=r[e]:(n.push({from:{row:o,col:0},to:{row:s,col:i-1}}),o=r[e],s=o);return n.push({from:{row:o,col:0},to:{row:s,col:i-1}}),{mode:e,ranges:n}}return"range"===e&&t.ranges.length>0?{mode:e,ranges:Rr(t.ranges)}:{mode:e,ranges:[]}}(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}},e.ServerSidePlugin=class extends Ct{static manifest={incompatibleWith:[{name:"groupingRows",reason:"Row grouping requires the full dataset to compute group boundaries. ServerSidePlugin lazy-loads rows in blocks, so groups cannot be built client-side. Server-side grouping would require hierarchical loading (group headers first, then rows on expand)."},{name:"tree",reason:"TreePlugin requires the full hierarchy to flatten and manage expansion state. ServerSidePlugin lazy-loads rows in blocks and cannot provide nested children on demand. Server-side tree would require lazy child loading as nodes expand."},{name:"pivot",reason:"PivotPlugin requires the full dataset to compute aggregations. ServerSidePlugin lazy-loads rows in blocks, so pivot aggregation cannot be performed client-side."}]};name="serverSide";get defaultConfig(){return{pageSize:100,cacheBlockSize:100,maxConcurrentRequests:2}}dataSource=null;totalRowCount=0;loadedBlocks=new Map;loadingBlocks=new Set;lastRequestId=0;scrollDebounceTimer;managedRows=[];detach(){this.dataSource=null,this.totalRowCount=0,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedRows=[],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},r=function(e,t,i){const r=Tr(e,i),n=Tr(t-1,i),o=[];for(let s=r;s<=n;s++)o.push(s);return o}(i.startRow,i.endRow,t);for(const n of r)if(!this.loadedBlocks.has(n)&&!this.loadingBlocks.has(n)){if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2))break;this.loadingBlocks.add(n),Mr(this.dataSource,n,t,{}).then(e=>{this.loadedBlocks.set(n,e.rows),this.totalRowCount=e.totalRowCount,this.loadingBlocks.delete(n);const i=n*t;for(let t=0;t<e.rows.length;t++)i+t<this.managedRows.length&&(this.managedRows[i+t]=e.rows[t]);this.requestVirtualRefresh(),this.loadRequiredBlocks()}).catch(()=>{this.loadingBlocks.delete(n)})}}processRows(e){if(!this.dataSource)return[...e];const t=this.config.cacheBlockSize??100;for(;this.managedRows.length<this.totalRowCount;){const e=this.managedRows.length;this.managedRows.push({__loading:!0,__index:e})}this.managedRows.length=this.totalRowCount;for(let i=0;i<this.totalRowCount;i++){const e=Lr(i,t,this.loadedBlocks);e&&(this.managedRows[i]=e)}return this.managedRows}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(),this.managedRows=[];Mr(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.managedRows=[],this.requestRender())}purgeCache(){this.loadedBlocks.clear(),this.managedRows=[]}getTotalRowCount(){return this.totalRowCount}isRowLoaded(e){const t=Tr(e,this.config.cacheBlockSize??100);return this.loadedBlocks.has(t)}getLoadedBlockCount(){return this.loadedBlocks.size}},e.TreePlugin=class extends Ct{static manifest={incompatibleWith:[{name:"groupingRows",reason:"Both plugins transform the entire row model. TreePlugin flattens nested hierarchies while GroupingRowsPlugin groups flat rows with synthetic headers. Use one approach per grid."},{name:"pivot",reason:"PivotPlugin replaces the entire row and column structure with aggregated pivot data. Tree hierarchy cannot coexist with pivot aggregation."},{name:"serverSide",reason:"TreePlugin requires the full hierarchy to flatten and manage expansion state. ServerSidePlugin lazy-loads rows in blocks and cannot provide nested children on demand."}],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",r=t?.[i];if(Array.isArray(r)&&r.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 zr(t,i)}processRows(e){const t=e;if(!zr(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=Hr(i,this.config),this.initialExpansionDone=!0),this.flattenedRows=this.flattenTree(i,this.expandedKeys),this.rowKeyMap.clear(),this.keysToAnimate.clear();const r=new Set;for(const n of this.flattenedRows)this.rowKeyMap.set(n.key,n),r.add(n.key),!this.previousVisibleKeys.has(n.key)&&n.depth>0&&this.keysToAnimate.add(n.key);return this.previousVisibleKeys=r,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,r)=>{const n=e.__stableKey,o=void 0!==e.id?String(e.id):n??(t?`${t}-${r}`:String(r)),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 r=this.config.childrenField??"children",n=[];for(const o of e){const e=o.__stableKey??String(o.id??"?"),s=o[r],l=Array.isArray(s)&&s.length>0,a=t.has(e);n.push({key:e,data:o,depth:i,hasChildren:l,isExpanded:a,parentKey:i>0&&e.substring(0,e.lastIndexOf("-"))||null}),l&&a&&n.push(...this.flattenTree(s,t,i+1))}return n}sortTree(e,t,i){const r=this.config.childrenField??"children";return[...e].sort((e,r)=>{const n=e[t],o=r[t];return null==n&&null==o?0:null==n?-1:null==o?1:n>o?i:n<o?-i:0}).map(e=>{const n=e[r];return Array.isArray(n)&&n.length>0?{...e,[r]:this.sortTree(n,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],r=i.viewRenderer,n=()=>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}=n(),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",r){const t=r(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 r=this.rowKeyMap.get(i);return!!r&&(this.expandedKeys=Pr(this.expandedKeys,i),this.emit("tree-expand",{key:i,row:r.data,expanded:this.expandedKeys.has(i),depth:r.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=Pr(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.gridElement?.querySelector(".rows");if(!e)return;const t=this.animationStyle,i=!1!==t&&this.keysToAnimate.size>0,r="fade"===t?"tbw-tree-fade-in":"tbw-tree-slide-in";for(const n of e.querySelectorAll(".data-grid-row")){const e=n.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,o=this.flattenedRows[t];o?.hasChildren&&n.setAttribute("aria-expanded",String(o.isExpanded)),i&&o?.key&&this.keysToAnimate.has(o.key)&&(n.classList.add(r),n.addEventListener("animationend",()=>n.classList.remove(r),{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=Pr(this.expandedKeys,e),this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}expandAll(){this.expandedKeys=Hr(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=Fr(this.rows,e,this.config,this.expandedKeys),this.requestRender()}},e.UndoRedoPlugin=class extends Ct{static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];#ar=!1;#dr=null;#cr(e,t){const i=this.rows[e.rowIndex];if(i){try{const r=this.grid.getRowId(i);if(r)return void this.grid.updateRow(r,{[e.field]:t})}catch{}i[e.field]=t}}#hr(e){const t=this.grid,i=t._visibleColumns?.findIndex(t=>t.field===e.field)??-1;if(i<0)return;t._focusRow=e.rowIndex,t._focusCol=i;const r=t.findRenderedRowElement?.(e.rowIndex);if(!r)return;const n=r.querySelector(`.cell[data-col="${i}"]`);if(n?.classList.contains("editing")){const e=n.querySelector(ne);e?.focus({preventScroll:!0})}}#ur(e,t){if(this.#ar=!0,"compound"===e.type){const i="undo"===t?[...e.actions].reverse():e.actions;for(const e of i)this.#cr(e,"undo"===t?e.oldValue:e.newValue)}else this.#cr(e,"undo"===t?e.oldValue:e.newValue);this.#ar=!1}#gr(e){const t="compound"===e.type?e.actions[e.actions.length-1]:e;t&&this.#hr(t)}attach(e){super.attach(e),this.on("cell-edit-committed",e=>{this.#ar||this.recordEdit(e.rowIndex,e.field,e.oldValue,e.newValue)})}detach(){this.undoStack=[],this.redoStack=[],this.#dr=null}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){e.preventDefault();const t=Or({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#ur(t.action,"undo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.emit("undo",{action:t.action,type:"undo"}),this.#gr(t.action),this.requestRenderWithFocus()),!0}if(i){e.preventDefault();const t=Nr({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#ur(t.action,"redo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.emit("redo",{action:t.action,type:"redo"}),this.#gr(t.action),this.requestRenderWithFocus()),!0}return!1}recordEdit(e,t,i,r){const n=function(e,t,i,r){return{type:"cell-edit",rowIndex:e,field:t,oldValue:i,newValue:r,timestamp:Date.now()}}(e,t,i,r);if(this.#dr)return void this.#dr.push(n);const o=qr({undoStack:this.undoStack,redoStack:this.redoStack},n,this.config.maxHistorySize??100);this.undoStack=o.undoStack,this.redoStack=o.redoStack}beginTransaction(){this.#dr&&h("TBW111","Transaction already in progress. Call endTransaction() first."),this.#dr=[]}endTransaction(){const e=this.#dr;if(e||h("TBW112","No transaction in progress. Call beginTransaction() first."),this.#dr=null,0===e.length)return;const t=1===e.length?e[0]:{type:"compound",actions:e,timestamp:Date.now()};const i=qr({undoStack:this.undoStack,redoStack:this.redoStack},t,this.config.maxHistorySize??100);this.undoStack=i.undoStack,this.redoStack=i.redoStack}undo(){const e=Or({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#ur(e.action,"undo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.#gr(e.action),this.requestRenderWithFocus()),e.action}redo(){const e=Nr({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#ur(e.action,"redo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.#gr(e.action),this.requestRenderWithFocus()),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,this.#dr=null}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}},e.VisibilityPlugin=$r,e.builtInSort=D,e.createGrid=function(e){const t=document.createElement("tbw-grid");return e&&(t.gridConfig=e),t},e.defaultComparator=H,e.defaultEditorFor=Ut,e.defaultPasteHandler=Tt,e.printGridIsolated=mr,e.queryGrid=function(e,t,i){let r=document,n=!1;return"boolean"==typeof t?n=t:t&&(r=t,n=!!i),n?customElements.whenDefined(yt.tagName).then(()=>r.querySelector(e)):r.querySelector(e)},e.setFeatureResolver=function(e){ye=e},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=grid.all.umd.js.map
|