@toolbox-web/grid 2.5.0 → 2.6.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/README.md +15 -3
- 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/types.d.ts +47 -31
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/lib/plugins/column-virtualization/index.js.map +1 -1
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/multi-sort/index.js.map +1 -1
- package/lib/plugins/pinned-columns/index.js.map +1 -1
- package/lib/plugins/pinned-rows/PinnedRowsPlugin.d.ts +28 -4
- package/lib/plugins/pinned-rows/index.d.ts +3 -2
- package/lib/plugins/pinned-rows/index.js +1 -1
- package/lib/plugins/pinned-rows/index.js.map +1 -1
- package/lib/plugins/pinned-rows/pinned-rows.d.ts +29 -1
- package/lib/plugins/pinned-rows/types.d.ts +96 -9
- package/lib/plugins/pivot/index.js.map +1 -1
- package/lib/plugins/print/index.js.map +1 -1
- package/lib/plugins/reorder-columns/index.js.map +1 -1
- package/lib/plugins/reorder-rows/index.js.map +1 -1
- package/lib/plugins/responsive/index.js +1 -1
- package/lib/plugins/responsive/index.js.map +1 -1
- package/lib/plugins/row-drag-drop/index.js.map +1 -1
- package/lib/plugins/row-drag-drop/types.d.ts +7 -0
- package/lib/plugins/selection/index.js.map +1 -1
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/tooltip/index.js.map +1 -1
- package/lib/plugins/tree/index.js.map +1 -1
- package/lib/plugins/undo-redo/index.js.map +1 -1
- package/lib/plugins/visibility/VisibilityPlugin.d.ts +0 -11
- package/lib/plugins/visibility/index.d.ts +1 -2
- package/lib/plugins/visibility/index.js.map +1 -1
- package/lib/plugins/visibility/types.d.ts +32 -0
- package/package.json +1 -1
- package/public.d.ts +28 -67
- 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/pinned-rows.umd.js +1 -1
- package/umd/plugins/pinned-rows.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/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";const t={STRETCH:"stretch",FIXED:"fixed"},i={sortApplied:(e,t)=>`Sorted by ${e}, ${t}`,sortCleared:()=>"Sort cleared",filterApplied:e=>`Filter applied on ${e}`,filterCleared:e=>`Filter cleared from ${e}`,allFiltersCleared:()=>"All filters cleared",groupExpanded:(e,t)=>`Group ${e} expanded, ${t} rows`,groupCollapsed:e=>`Group ${e} collapsed`,selectionChanged:e=>`${e} rows selected`,editingStarted:e=>`Editing row ${e+1}`,editingCommitted:e=>`Row ${e+1} saved`,dataLoaded:e=>`${e} rows loaded`},r={mode:"reduced-motion",duration:200,easing:"ease-out"},n={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};function o(e,t){if(!e)return;const i="effectiveConfig"in e?e.effectiveConfig:void 0;if(!1===i?.a11y?.announcements)return;const r=e.querySelector?.(".tbw-sr-only");r&&(r.textContent="",requestAnimationFrame(()=>{r.textContent=t}))}function s(e,t,...r){const n=e&&"effectiveConfig"in e?e.effectiveConfig:void 0,o=n?.a11y?.messages?.[t];return o?o(...r):i[t](...r)}function l(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}const a="TBW041",d="TBW061",c="TBW062",u="TBW140";function h(e,t,i,r){return`${l(i,r)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}function g(e,t,i,r){throw new Error(h(e,t,i,r))}function p(e,t,i,r){console.warn(h(e,t,i,r))}function f(e,t,i,r){console.debug(h(e,t,i,r))}function w(e,t,i,r){console.error(h(e,t,i,r))}function m(e,t){if(!(e&&e.length||t&&t.length))return[];if(!e||!e.length)return t||[];if(!t||!t.length)return e;const i={},r=t;for(let s=0;s<r.length;s++){const e=r[s],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 n=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}),o=Object.keys(i);for(let s=0;s<o.length;s++)n.push(i[o[s]]);return n}function b(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 v(e){const i=e.effectiveConfig?.fitMode||e.fitMode||t.STRETCH;if(i!==t.STRETCH&&i!==t.FIXED)return;if(e.__didInitialAutoSize)return;if(!e.isConnected)return;const r=Array.from(e._headerRowEl?.children||[]);if(!r.length)return;let n=!1;const o=e._visibleColumns;for(let t=0;t<o.length;t++){const i=o[t];if(i.width)continue;const s=r[t];let l=s?s.scrollWidth:0;for(let r=0;r<e._rowPool.length;r++){const i=e._rowPool[r].children[t];if(i){const e=i.scrollWidth;e>l&&(l=e)}}l>0&&(i.width=l+2,i.__autoSized=!0,n=!0)}n&&x(e),e.__didInitialAutoSize=!0}const y=/^(?:\d+(?:\.\d+)?(?:px|%|fr|em|rem|ch|vw|vh|vmin|vmax)|calc\(.+\)|min-content|max-content|minmax\(.+\)|fit-content\(.+\)|auto)$/i;function C(e,t){return"number"==typeof e?`${e}px`:(y.test(e)||p("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 x(e){const i=e.effectiveConfig?.fitMode||e.fitMode||t.STRETCH;e._gridTemplate=i===t.STRETCH?e._visibleColumns.map(e=>{if(null!=e.width)return C(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?C(e.width,e.field):"max-content").join(" "),e.style.setProperty("--tbw-column-template",e._gridTemplate)}const R={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"},E={FIELD:"data-field",GROUP_KEY:"data-group-key"},S={ROOT:`.${R.ROOT}`,HEADER:`.${R.HEADER}`,HEADER_ROW:`.${R.HEADER_ROW}`,HEADER_CELL:`.${R.HEADER_CELL}`,ROWS_VIEWPORT:`.${R.ROWS_VIEWPORT}`,ROWS_CONTAINER:`.${R.ROWS_CONTAINER}`,DATA_ROW:`.${R.DATA_ROW}`,DATA_CELL:`.${R.DATA_CELL}`,GROUP_ROW:`.${R.GROUP_ROW}`,CELL_BY_FIELD:e=>`.${R.DATA_CELL}[${E.FIELD}="${e}"]`,SELECTED_ROWS:`.${R.DATA_ROW}.${R.SELECTED}`,EDITING_CELL:`.${R.DATA_CELL}.${R.EDITING}`},_=/{{\s*([^}]+)\s*}}/g,A="__DG_EMPTY__",k=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,T="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join("")),I=new RegExp(`__(proto|defineGetter|defineSetter)|${T.slice(3).join("|")}|this\\b`);const M=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".split("|")),L=/^on\w+$/i,P=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),D=/^\s*(javascript|vbscript|data|blob):/i;function F(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(M.has(e)){t.push(r);continue}if("svg"===e||"http://www.w3.org/2000/svg"===r.namespaceURI){if(Array.from(r.attributes).some(e=>L.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();L.test(e)?i.push(t.name):(P.has(e)&&D.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 H(e,t){const i=function(e){const t=[];let i=0;for(;i<e.length;){const r=e[i];if(" "!==r){if(r>="0"&&r<="9"||"."===r&&i+1<e.length&&e[i+1]>="0"&&e[i+1]<="9"){const r=i;for(;i<e.length&&(e[i]>="0"&&e[i]<="9"||"."===e[i]);)i++;t.push({type:"num",v:Number(e.slice(r,i))});continue}if("'"===r){let r="";for(i++;i<e.length&&"'"!==e[i];)r+=e[i++];if(i>=e.length)return null;i++,t.push({type:"str",v:r});continue}if(r>="a"&&r<="z"||r>="A"&&r<="Z"||"_"===r||"$"===r){const r=i;for(;i<e.length&&/[\w$.]/.test(e[i]);)i++;t.push({type:"id",v:e.slice(r,i)});continue}if(i+2<e.length){const r=e.slice(i,i+3);if("==="===r||"!=="===r){t.push({type:"op",v:r}),i+=3;continue}}if(i+1<e.length){const r=e.slice(i,i+2);if("=="===r||"!="===r||"<="===r||">="===r||"&&"===r||"||"===r){t.push({type:"op",v:r}),i+=2;continue}}if(!"+-*/%<>!?:(),".includes(r))return null;t.push({type:"op",v:r}),i++}else i++}return t}(e);if(!i)return;const r=i;let n=0;function o(){return r[n]}function s(){return r[n++]}function l(e,t){const i=o();return!!i&&(i.type===e&&(void 0===t||i.v===t))}function a(){const e=function(){let e=d();for(;l("op","||");)s(),e=e||d();return e}();if(l("op","?")){s();const t=a();if(!l("op",":"))return;s();const i=a();return e?t:i}return e}function d(){let e=c();for(;l("op","&&");)s(),e=e&&c();return e}function c(){let e=u();for(;;){const t=o();if(!t||"op"!==t.type)break;if("==="===t.v)s(),e=e===u();else if("!=="===t.v)s(),e=e!==u();else if("=="===t.v)s(),e=e==u();else{if("!="!==t.v)break;s(),e=e!=u()}}return e}function u(){let e=h();for(;;){const t=o();if(!t||"op"!==t.type)break;if("<"===t.v)s(),e=e<h();else if(">"===t.v)s(),e=e>h();else if("<="===t.v)s(),e=e<=h();else{if(">="!==t.v)break;s(),e=e>=h()}}return e}function h(){let e=g();for(;;){const t=o();if(!t||"op"!==t.type)break;if("+"===t.v)s(),e+=g();else{if("-"!==t.v)break;s(),e-=g()}}return e}function g(){let e=p();for(;;){const t=o();if(!t||"op"!==t.type)break;if("*"===t.v)s(),e*=p();else if("/"===t.v)s(),e/=p();else{if("%"!==t.v)break;s(),e%=p()}}return e}function p(){return l("op","!")?(s(),!p()):f()}function f(){const e=o();if(e){if("num"===e.type)return s(),e.v;if("str"===e.type)return s(),e.v;if("id"===e.type)return s(),function(e){if("value"===e)return t.value;if(e.startsWith("row.")){const i=e.slice(4);return t.row?t.row[i]:void 0}return"row"===e?t.row:void 0}(e.v);if("op"===e.type&&"("===e.v){s();const e=a();return l("op",")")&&s(),e}return"op"===e.type&&"-"===e.v?(s(),-f()):void 0}}const w=a();return n<r.length?void 0:w}function G(e,t){if(!e||-1===e.indexOf("{{"))return e;const i=[],r=e.replace(_,(e,r)=>{const n=function(e,t){if(e=(e||"").trim(),!e)return A;if(O.test(e))return A;if("value"===e)return null==t.value?A: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?A:String(r)}if(e.length>80)return A;if(!k.test(e)||I.test(e))return A;const i=e.match(/\./g);if(i&&i.length>1)return A;try{const i=H(e,t),r=null==i?"":String(i);return O.test(r)?A:r||A}catch{return A}}(r,t);return i.push({expr:r.trim(),result:n}),n}),n=(o=r)?o.replace(new RegExp(A,"g"),"").replace(/Reflect\.[^<>{}\s]+|\bProxy\b|ownKeys\([^)]*\)/g,""):o;var o;const s=i.length&&i.every(e=>""===e.result||e.result===A);return O.test(e)||s?"":n}const O=/Reflect|Proxy|ownKeys/;function N(e){if(O.test(e.textContent||"")){for(const t of e.childNodes)t.nodeType===Node.TEXT_NODE&&O.test(t.textContent||"")&&(t.textContent="");O.test(e.textContent||"")&&(e.textContent="")}}function q(e){if(O.test(e)){const e=()=>"";return e.__blocked=!0,e}const t=t=>G(e,t);return t.__blocked=!1,t}function z(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase()}class ${static dependencies;static manifest;aliases;version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},i={};for(const r of Object.keys(t))i[r]=this;for(const r of e){const e=r.userConfig;for(const[n,o]of Object.entries(e)){if(void 0===o)continue;if(!(n in t)){t[n]=o,i[n]=r;continue}if(t[n]===o)continue;const e=i[n]?.constructor.name??this.constructor.name,s=r.constructor.name,l=h("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${n}" supplied by both ${e} and ${s}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(l)}}Object.assign(this.userConfig,t)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=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)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(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.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...n,...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}setIcon(e,t,i){e.dataset.icon=z(t),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const r=this.#t(t,i);void 0!==r?"string"==typeof r?e.innerHTML=F(r):r instanceof HTMLElement&&(e.innerHTML="",e.appendChild(r.cloneNode(!0))):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const i=document.createElement("span");i.setAttribute("part","sort-indicator"),i.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(i,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(i,"sortNone"));const r=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return r?e.insertBefore(i,r):e.appendChild(i),i}warn(e,t){void 0!==t?console.warn(h(e,t,this.gridElement.id,this.name)):console.warn(`${l(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(h(e,t,this.gridElement.id,this.name))}}const B=new WeakMap;function W(e,t,i=-1){if(!t.valueAccessor)return e?.[t.field];if("object"!=typeof e||null===e)return t.valueAccessor({row:e,column:t,rowIndex:i});const r=t.field;let n=B.get(e);if(n){if(n.has(r))return n.get(r)}else n=new Map,B.set(e,n);const o=t.valueAccessor({row:e,column:t,rowIndex:i});return n.set(r,o),o}function K(e,t){e&&(t?B.get(e)?.delete(t):B.delete(e))}function V(e,t,i){const r=i.find(e=>e.field===t.field),n=r?.sortComparator,{field:o,direction:s}=t,l=[...e];return n?r?.valueAccessor?l.sort((e,t)=>n(W(e,r),W(t,r),e,t)*s):l.sort((e,t)=>n(e[o],t[o],e,t)*s):r?.valueAccessor?U(l,r,s):j(l,o,s),l}function j(e,t,i){e.sort((e,r)=>{const n=Y(e,r);if(0!==n)return n;const o=e[t],s=r[t];return null==o&&null==s?0:null==o?-i:null==s||o>s?i:o<s?-i:0})}function U(e,t,i){e.sort((e,r)=>{const n=Y(e,r);if(0!==n)return n;const o=W(e,t),s=W(r,t);return null==o&&null==s?0:null==o?-i:null==s||o>s?i:o<s?-i:0})}function Y(e,t){const i=!0===e?.__loading;return i===(!0===t?.__loading)?0:i?1:-1}function X(e,t,i,r){const n=r.find(e=>e.field===t),o=n?.sortComparator;o?n?.valueAccessor?e.sort((e,t)=>o(W(e,n),W(t,n),e,t)*i):e.sort((e,r)=>o(e[t],r[t],e,r)*i):n?.valueAccessor?U(e,n,i):j(e,t,i)}function Z(e,t,i,r){e._rows=t,e.__rowRenderEpoch++;for(let n=0;n<e._rowPool.length;n++)e._rowPool[n].__epoch=-1;le(e),e.refreshVirtualWindow(!0),Q(e,i,r)}function Q(e,t,i){const r={field:t.field,direction:i};e.dispatchEvent(new CustomEvent("sort-change",{detail:r})),e._pluginManager?.emitPluginEvent?.("sort-change",r),o(e,s(e,0===i?"sortCleared":"sortApplied",t.header??t.field,1===i?"ascending":"descending")),e.requestStateChange?.()}function J(e){return e._pluginManager?._hasRowStructurePlugins??!1}function ee(e,t){if(e._sortState&&e._sortState.field===t.field)if(1===e._sortState.direction)te(e,t,-1);else{if(e._sortState=null,J(e))return e._requestSchedulerPhase(4,"sort-clear"),void Q(e,t,0);e.__rowRenderEpoch++;for(let t=0;t<e._rowPool.length;t++)e._rowPool[t].__epoch=-1;e._rows=e.__originalOrder.slice(),e.__originalOrder=[],le(e);const i=e._headerRowEl?.querySelectorAll('[role="columnheader"].sortable');if(i)for(let t=0;t<i.length;t++){const r=i[t];r.getAttribute("aria-sort")&&("ascending"!==r.getAttribute("aria-sort")&&"descending"!==r.getAttribute("aria-sort")||e._sortState)||r.setAttribute("aria-sort","none")}e.refreshVirtualWindow(!0),Q(e,t,0)}else e._sortState||(e.__originalOrder=e._rows.slice()),te(e,t,1)}function te(e,t,i){if(e._sortState={field:t.field,direction:i},J(e))return e._requestSchedulerPhase(4,"sort-apply"),void Q(e,t,i);const r={field:t.field,direction:i},n=e._columns,o=e.effectiveConfig?.sortHandler??V;if(o===V)return X(e._rows,r.field,i,n),void Z(e,e._rows,t,i);const s=o(e._rows,r,n);s&&"function"==typeof s.then?s.then(r=>{Z(e,r,t,i)}):Z(e,s,t,i)}function ie(e,t){return!1!==e.effectiveConfig?.sortable&&!0===t.sortable}function re(e,t){return!1!==e.effectiveConfig?.resizable&&!1!==t.resizable}function ne(e,t){const i=document.createElement("span");b(i,"sort-indicator");const r=e._sortState?.field===t.field?e._sortState.direction:0,n=1===r?"sortAsc":-1===r?"sortDesc":"sortNone";i.dataset.icon=z(n);const o=e.icons?.[n];return void 0!==o&&function(e,t){"string"==typeof t?e.innerHTML=F(t):t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}(i,o),i}function oe(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 se(e,t,i,r){r.classList.add(R.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)||ee(e,t)}),r.addEventListener("keydown",i=>{if("Enter"===i.key||" "===i.key){if(i.preventDefault(),e._dispatchHeaderClick?.(i,t,r))return;ee(e,t)}})}function le(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",b(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:()=>ie(e,i)?ne(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=F(t);i.firstChild;)e.appendChild(i.firstChild)}else t instanceof Node&&e.appendChild(t)}(n,s),ie(e,i)&&se(e,i,0,n),re(e,i)&&(n.classList.add("resizable"),n.appendChild(oe(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=F(s):s instanceof Node&&l.appendChild(s),n.appendChild(l),ie(e,i)&&(se(e,i,0,n),n.appendChild(ne(e,i))),re(e,i)&&(n.classList.add("resizable"),n.appendChild(oe(e,r,n)))}else if(i.__headerTemplate)Array.from(i.__headerTemplate.childNodes).forEach(e=>n.appendChild(e.cloneNode(!0))),ie(e,i)&&(se(e,i,0,n),n.appendChild(ne(e,i))),re(e,i)&&(n.classList.add("resizable"),n.appendChild(oe(e,r,n)));else{const t=document.createElement("span");t.textContent=o,n.appendChild(t),ie(e,i)&&(se(e,i,0,n),n.appendChild(ne(e,i))),re(e,i)&&(n.classList.add("resizable"),n.appendChild(oe(e,r,n)))}t.appendChild(n)}),t.querySelectorAll(`.cell.${R.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 ae(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}}const de={STYLE:1,VIRTUALIZATION:2,HEADER:3,ROWS:4,COLUMNS:5,FULL:6};class ce{#i;#r=0;#n=0;#o=null;#s=null;#l=null;#a=!1;constructor(e){this.#i=e}requestPhase(e,t){e>this.#r&&(this.#r=e),0===this.#n&&(this.#d(),this.#n=requestAnimationFrame(()=>this.#c()))}whenReady(){return this.#o?this.#o:Promise.resolve()}setInitialReadyResolver(e){this.#l=e}cancel(){0!==this.#n&&(cancelAnimationFrame(this.#n),this.#n=0),this.#r=0,this.#s&&(this.#s(),this.#s=null,this.#o=null)}get isPending(){return 0!==this.#r}get pendingPhase(){return this.#r}#d(){this.#o||(this.#o=new Promise(e=>{this.#s=e}))}#c(){if(this.#n=0,!this.#i._schedulerIsConnected)return this.#r=0,void(this.#s&&(this.#s(),this.#s=null,this.#o=null));const e=this.#r;this.#r=0,e>=de.COLUMNS&&this.#i._schedulerMergeConfig(),e>=de.ROWS&&this.#i._schedulerProcessRows(),e>=de.COLUMNS&&(this.#i._schedulerProcessColumns(),this.#i._schedulerUpdateTemplate()),e>=de.HEADER&&this.#i._schedulerRenderHeader(),e>=de.VIRTUALIZATION&&this.#i.refreshVirtualWindow(!0,!0),e>=de.STYLE&&this.#i._schedulerAfterRender(),!this.#a&&this.#l&&(this.#a=!0,this.#l()),this.#s&&(this.#s(),this.#s=null,this.#o=null)}}class ue{#u;#h;#g;#p;#f;#w={};#m={};#b=!0;#v=[];#y;#C;#x;#R;#i;#E;constructor(e){this.#i=e}get original(){return this.#w}get effective(){return this.#m}get columns(){return this.#m.columns??[]}set columns(e){this.#m.columns=e}get lightDomColumnsCache(){return this.#p}set lightDomColumnsCache(e){this.#p=e}get originalColumnNodes(){return this.#f}set originalColumnNodes(e){this.#f=e}get lightDomTitle(){return this.#E}set lightDomTitle(e){this.#E=e}get initialColumnState(){return this.#R}set initialColumnState(e){this.#R=e}get sourcesChanged(){return this.#b}markSourcesChanged(){this.#b=!0}setGridConfig(e){this.#u=e,this.#b=!0,this.#p=void 0}getGridConfig(){return this.#u}setColumns(e){this.#h=e,this.#b=!0}getColumns(){return this.#h}setFitMode(e){this.#g=e,this.#b=!0}getFitMode(){return this.#g}merge(){const e=(this.#m.columns?.length??0)>0;if(!this.#b&&e)return;const t=this.#S();this.#b=!1,this.#w=t,Object.freeze(this.#w),this.#w.columns&&Object.freeze(this.#w.columns),this.#m=this.#_(this.#w),this.#A()}#_(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}#A(){const e=this.#m;if(this.#k(),"number"==typeof e.rowHeight&&e.rowHeight>0&&(this.#i._virtualization.rowHeight=e.rowHeight),"fixed"===e.fitMode){this.columns.forEach(e=>{null==e.width&&(e.width=80)})}this.#i._applyAnimationConfig(e)}#k(){const e=this.#m.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))}}#S(){const e=this.#u?{...this.#u}:{},t=Array.isArray(e.columns)?[...e.columns]:[],i=(this.#p??[]).map(e=>({...e}));let r=m(t,i);this.#h&&this.#h.length&&(r=m(this.#h,i));const n=this.#i.sourceRows;if(0===r.length&&n.length){r=ae(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=q(e.__viewTemplate.innerHTML)),e.__editorTemplate&&!e.__compiledEditor&&(e.__compiledEditor=q(e.__editorTemplate.innerHTML))}),e.columns=r),this.#g&&(e.fitMode=this.#g),e.fitMode||(e.fitMode="stretch"),this.#T(e),e.columnState&&!this.#R&&(this.#R=e.columnState),e}#T(e){e.shell=e.shell?{...e.shell}:{},e.shell.header=e.shell.header?{...e.shell.header}:{};const t=this.#i._shellState.lightDomTitle;t&&(this.#E=t),this.#E&&!e.shell.header.title&&(e.shell.header.title=this.#E);const i=this.#i._shellState.lightDomHeaderContent;i?.length>0&&(e.shell.header.lightDomContent=i),this.#i._shellState.hasToolButtonsContainer&&(e.shell.header.hasToolButtonsContainer=!0);const r=this.#i._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.#i._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.#i._shellState.toolbarContents,s=Array.from(o.values()),l=this.#u?.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.#I();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.#i._sortState={field:e.field,direction:"asc"===e.sort.direction?1:-1})}else this.#i._sortState=null;for(const s of t)if(s.applyColumnState)for(const t of e.columns)s.applyColumnState(t.field,t)}resetState(e){this.#R=void 0,this.#i._sortState=null,this.#m=this.#_(this.#w),this.#A();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)}#I(){const e=new Map,t=this.#i._sortState;return t&&e.set(t.field,{direction:1===t.direction?"asc":"desc",priority:0}),e}requestStateChange(e){this.#C&&clearTimeout(this.#C),this.#C=setTimeout(()=>{this.#C=void 0;const t=this.collectState(e);this.#i._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.#i._emit("column-visibility",{field:e,visible:t,visibleColumns:i.filter(e=>!e.hidden).map(e=>e.field)}),this.#i._clearRowPool(),this.#i._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.#i._emit("column-visibility",{visibleColumns:e.map(e=>e.field)}),this.#i._clearRowPool(),this.#i._setup())}getAllColumns(){return this.columns.map(e=>({field:e.field,header:e.header||e.field,visible:!e.hidden,lockVisible:e.lockVisible,utility:!0===e.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,this.#i._invalidateVisibleColumnsCache(),le(this.#i),x(this.#i),this.#i._requestSchedulerPhase(de.COLUMNS,"configManager")}parseLightDomColumns(e){this.#p||(this.#f=Array.from(e.querySelectorAll("tbw-grid-column")),this.#p=this.#f.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);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"),u=e.querySelector("tbw-grid-column-header");d&&(r.__viewTemplate=d),c&&(r.__editorTemplate=c),u&&(r.__headerTemplate=u);const h=globalThis.DataGridElement,g=h?.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.#p=void 0}#M=new Map;registerLightDomHandler(e,t){this.#M.set(e.toLowerCase(),t)}unregisterLightDomHandler(e){this.#M.delete(e.toLowerCase())}observeLightDOM(e){this.#y&&this.#y.disconnect();const t=new Set,i=()=>{this.#x=void 0;for(const e of t){const t=this.#M.get(e);t?.()}t.clear()};this.#y=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.#M.has(i)&&t.add(i)}if("attributes"===i.type&&i.target.nodeType===Node.ELEMENT_NODE){const e=i.target.tagName.toLowerCase();this.#M.has(e)&&t.add(e)}}t.size>0&&!this.#x&&(this.#x=setTimeout(i,0))}),this.#y.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["title","field","header","width","hidden","id","icon","tooltip","order"]})}onChange(e){this.#v.push(e)}notifyChange(){for(const e of this.#v)e()}dispose(){this.#y?.disconnect(),this.#v=[],this.#C&&clearTimeout(this.#C),this.#x&&(clearTimeout(this.#x),this.#x=void 0)}}function he(){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 ge(e){return`<span role="checkbox" aria-checked="${e}" aria-label="${e}">${e?"🗹":"☐"}</span>`}function pe(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 fe(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 we(e){e&&e.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function me(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 be(e){return"rtl"===me(e)}function ve(e,t){const i=t.renderer||t.viewRenderer;if(i)return i;if(!t.type)return;const r=e.__frameworkAdapter;if(r?.getTypeDefault){const i=r.getTypeDefault(t.type,e._hostElement);if(i?.renderer)return i.renderer}}function ye(e,t){if(t.format)return t.format;if(!t.type)return;const i=e.__frameworkAdapter;if(i?.getTypeDefault){const r=i.getTypeDefault(t.type,e._hostElement);if(r?.format)return r.format}}const Ce='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function xe(e){return(e.__editingCellCount??0)>0}function Re(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing");e.querySelectorAll(`.cell.${R.EDITING}`).forEach(e=>e.classList.remove(R.EDITING))}const Ee=document.createElement("template");Ee.innerHTML='<div class="cell" role="gridcell" part="cell"></div>';const Se=document.createElement("template");function _e(){return Ee.content.firstElementChild.cloneNode(!0)}function Ae(){return Se.content.firstElementChild.cloneNode(!0)}function ke(e){e.__cellDisplayCache=void 0,e.__cellCacheEpoch=void 0,e.__hasSpecialColumns=void 0}function Te(e,t,i,r){const n=t.children,o=e._visibleColumns,s=o.length,l=n.length,a=s<l?s:l,u=e._focusRow,h=e._focusCol,g=e._hasAfterCellRenderHook?.()??!1;let f=e.__hasSpecialColumns;if(void 0===f){f=!1;const t=e.__frameworkAdapter;for(let i=0;i<s;i++){const r=o[i];if(r.__viewTemplate||r.__compiledView||r.renderer||r.viewRenderer||r.externalView||r.format||r.cellClass||"date"===r.type||"boolean"===r.type||r.type&&t?.getTypeDefault?.(r.type,e._hostElement)?.renderer||r.type&&t?.getTypeDefault?.(r.type,e._hostElement)?.format){f=!0;break}}e.__hasSpecialColumns=f}const w=String(r);if(f){for(let s=0;s<a;s++){if(o[s].externalView){if(!n[s].querySelector("[data-external-view]"))return void Ie(e,t,i,r)}}for(let s=0;s<a;s++){const l=o[s],a=n[s];a.getAttribute("data-row")!==w&&a.setAttribute("data-row",w);const f=a.classList.contains(R.EDITING);if(!f){const e=u===r&&h===s;e!==a.classList.contains("cell-focus")&&(a.classList.toggle("cell-focus",e),a.setAttribute("aria-selected",String(e)))}const b=l.cellClass;if(b){const t=a.getAttribute("data-dynamic-classes");if(t){const e=t.split(" ");for(let t=0;t<e.length;t++)e[t]&&a.classList.remove(e[t])}try{const e=b(W(i,l,r),i,l),t="string"==typeof e?e.split(/\s+/):e;if(t&&t.length>0){let e="";for(let i=0;i<t.length;i++){const r=t[i];r&&"string"==typeof r&&(a.classList.add(r),e+=(e?" ":"")+r)}a.setAttribute("data-dynamic-classes",e)}else a.removeAttribute("data-dynamic-classes")}catch(m){p(d,`cellClass callback error for column '${l.field}': ${m}`,e.id),a.removeAttribute("data-dynamic-classes")}}if(f)continue;const v=ve(e,l);if(v){const n=W(i,l,r),o=v({row:i,value:n,field:l.field,column:l,grid:e,cellEl:a});"string"==typeof o?(e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=F(o)):o instanceof Node?o.parentElement!==a&&(e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML="",a.appendChild(o)):null==o&&(e.__frameworkAdapter?.releaseCell?.(a),a.textContent=null==n?"":String(n)),g&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:s,value:n,cellElement:a,rowElement:t});continue}if(l.__compiledView){const n=W(i,l,r),o=l.__compiledView({row:i,value:n,field:l.field,column:l});l.__compiledView.__blocked?a.textContent="":(a.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=F(o),N(a)),g&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:s,value:n,cellElement:a,rowElement:t});continue}if(l.__viewTemplate){const n=W(i,l,r),o=l.__viewTemplate.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(o)?a.textContent="":(a.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=F(G(o,{row:i,value:n})),N(a)),g&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:s,value:n,cellElement:a,rowElement:t});continue}if(l.externalView)continue;const y=W(i,l,r);let C;a.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(a);const x=ye(e,l);if(x){try{const e=x(y,i);C=null==e?"":String(e)}catch(m){p(c,`Format error in column '${l.field}': ${m}`,e.id),C=null==y?"":String(y)}a.textContent=C}else"date"===l.type?(C=pe(y),a.textContent=C):"boolean"===l.type?a.innerHTML=ge(!!y):(C=null==y?"":String(y),a.textContent=C);g&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:s,value:y,cellElement:a,rowElement:t})}}else for(let d=0;d<a;d++){const s=n[d];if(s.classList.contains(R.EDITING))continue;s.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(s);const l=o[d],a=W(i,l,r);s.textContent=null==a?"":String(a),s.getAttribute("data-row")!==w&&s.setAttribute("data-row",w);const c=u===r&&h===d;c!==s.classList.contains("cell-focus")&&(s.classList.toggle("cell-focus",c),s.setAttribute("aria-selected",String(c))),g&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:d,value:a,cellElement:s,rowElement:t})}}function Ie(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,a=e._focusCol,u=e._hasAfterCellRenderHook?.()??!1,h=document.createDocumentFragment();for(let f=0;f<s;f++){const n=o[f],s=_e();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=W(i,n,r);const m=ye(e,n);if(m)try{w=m(w,i)}catch(g){p(c,`Format error in column '${n.field}': ${g}`,e.id)}const b=n.__compiledView,v=n.__viewTemplate,y=ve(e,n),C=n.externalView;let x=!1;if(y){const t=y({row:i,value:w,field:n.field,column:n,grid:e,cellEl:s});"string"==typeof t?(s.innerHTML=F(t),x=!0):t instanceof Node?t.parentElement!==s&&(s.textContent="",s.appendChild(t)):null==t&&(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,grid:e};if(t.mount)try{t.mount({placeholder:r,context:o,spec:t})}catch(g){p("TBW063",`External view mount error for column '${n.field}': ${g}`,e.id)}else queueMicrotask(()=>{try{e.dispatchEvent(new CustomEvent("mount-external-view",{bubbles:!0,composed:!0,detail:{placeholder:r,spec:t,context:o}}))}catch(g){p("TBW064",`External view event dispatch error for column '${n.field}': ${g}`,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?"":F(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=F(G(e,{row:i,value:w})),x=!0)}else m?s.textContent=null==w?"":String(w):"date"===n.type?s.textContent=pe(w):"boolean"===n.type?s.innerHTML=ge(!!w):s.textContent=null==w?"":String(w);if(x){N(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&&a===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(W(i,n,r),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(g){p(d,`cellClass callback error for column '${n.field}': ${g}`,e.id)}u&&e._afterCellRender?.({row:i,rowIndex:r,column:n,colIndex:f,value:w,cellElement:s,rowElement:t}),h.appendChild(s)}t.appendChild(h)}function Me(e,t,i){if(t.target?.closest(".resize-handle"))return;const r=fe(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(R.EDITING)){n&&(we(e._bodyEl??e),o.classList.add("cell-focus"));const i=t.target,r=o.contains(i)&&i.matches(Ce)?i:o.querySelector(Ce);try{r?.focus({preventScroll:!0})}catch{}return}De(e)}}}function Le(e){"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit()}function Pe(e){if(!e)return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t||!!e.isContentEditable}function De(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),we(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(R.EDITING)){const e=s.querySelector(Ce);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})}}}Se.innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const Fe=new WeakMap;function He(e,t){const i=fe(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,we(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 Ge(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,u,h,g,p;return s&&(d=parseInt(s.getAttribute("data-row")??"-1",10),c=parseInt(s.getAttribute("data-col")??"-1",10),d>=0&&c>=0&&(u=e._rows[d],p=e._visibleColumns[c],h=p?.field,g=u&&h?u[h]:void 0)),{type:r,row:u,rowIndex:void 0!==d&&d>=0?d:void 0,colIndex:void 0!==c&&c>=0?c:void 0,field:h,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 Oe(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;if((!Pe(a)||"Home"!==t.key&&"End"!==t.key)&&!(Pe(a)&&("ArrowUp"===t.key||"ArrowDown"===t.key)&&"INPUT"===a.tagName&&"number"===a.type||Pe(a)&&("ArrowLeft"===t.key||"ArrowRight"===t.key)||Pe(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&&(e._activeEditRows===e._focusRow&&Le(e),e._focusRow-=1,e._focusCol=r):e._focusCol<r?e._focusCol+=1:(Le(e),e._focusRow<i&&(e._focusRow+=1,e._focusCol=0)),void De(e);case"ArrowDown":n&&Le(e),e._focusRow=Math.min(i,e._focusRow+1),t.preventDefault();break;case"ArrowUp":n&&Le(e),e._focusRow=Math.max(0,e._focusRow-1),t.preventDefault();break;case"ArrowRight":{const i=be(e);e._focusCol=i?Math.max(0,e._focusCol-1):Math.min(r,e._focusCol+1),t.preventDefault();break}case"ArrowLeft":{const i=be(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&&Le(e),e._focusRow=0,e._focusCol=0):e._focusCol=0,t.preventDefault(),void De(e,{forceScrollLeft:!0});case"End":return t.ctrlKey||t.metaKey?(n&&Le(e),e._focusRow=i,e._focusCol=r):e._focusCol=r,t.preventDefault(),void De(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}});if(e.dispatchEvent(d),d.defaultPrevented)return void t.preventDefault();break}default:return}De(e)}}(e,t),{signal:r}),i.addEventListener("mousedown",t=>function(e,t,i){const r=Ge(e,t,i,"mousedown");e._dispatchCellMouseDown?.(r)&&Fe.set(e,!0)}(e,i,t),{signal:r}),document.addEventListener("mousemove",t=>function(e,t,i){if(!Fe.get(e))return;const r=Ge(e,t,i,"mousemove");e._dispatchCellMouseMove?.(r)}(e,i,t),{signal:r}),document.addEventListener("mouseup",t=>function(e,t,i){if(!Fe.get(e))return;const r=Ge(e,t,i,"mouseup");e._dispatchCellMouseUp?.(r),Fe.set(e,!1)}(e,i,t),{signal:r})}let Ne;class qe{#i;#L=new Set;#P=new Map;constructor(e){this.#i=e}focusCell(e,t){const i=this.#i,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)),De(i))}get focusedCell(){const e=this.#i;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.#i._virtualization;if(!i.enabled)return;const r=i.container;if(!r)return;const n=this.#i._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 u=i.viewportEl?.clientHeight??r.clientHeight??0;if(u<=0)return;const h=r.scrollTop,g=a+d,p=h+u;let f;switch(s){case"start":f=a;break;case"center":f=a-u/2+d/2;break;case"end":f=g-u;break;default:if(a>=h&&g<=p)return;f=a<h?a:g-u}f=Math.max(0,f),"smooth"===l?r.scrollTo({top:f,behavior:"smooth"}):r.scrollTop=f}scrollToRowById(e,t){const i=this.#i._getRowEntry(e);i&&this.scrollToRow(i.index,t)}registerExternalFocusContainer(e){if(this.#L.has(e))return;this.#L.add(e);const t=new AbortController,i=t.signal,r=this.#i;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.#P.set(e,()=>t.abort())}unregisterExternalFocusContainer(e){this.#L.delete(e);const t=this.#P.get(e);t&&(t(),this.#P.delete(e))}containsFocus(e){const t=e??document.activeElement;return!!t&&(!!this.#i.contains(t)||this.isInExternalFocusContainer(t))}isInExternalFocusContainer(e){for(const t of this.#L)if(t.contains(e))return!0;return!1}destroy(){for(const e of this.#P.values())e();this.#P.clear(),this.#L.clear()}}const ze="function"==typeof requestIdleCallback;function $e(e){ze?cancelIdleCallback(e):clearTimeout(e)}function Be(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 We(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()}function Ke(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],u="number"==typeof c?.width?c.width:void 0,h=c?.__renderedWidth??u??a.getBoundingClientRect().width;t={startX:i.clientX,colIndex:s,startWidth:h},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 Ve="data-animating",je={change:"--tbw-row-change-duration",insert:"--tbw-row-insert-duration",remove:"--tbw-row-remove-duration"},Ue={change:500,insert:300,remove:200};function Ye(e,t){const i=je[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 Ue[t]}function Xe(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(Ve),e.offsetWidth,e.setAttribute(Ve,t);const r=Ye(e,t);setTimeout(()=>{"remove"!==t&&e.removeAttribute(Ve),i?.()},r)}(r,i,()=>e(!0))}):Promise.resolve(!1)}function Ze(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 Qe(e,t,i){const r=Ze(e,i);return void 0===r&&g("TBW040",'Cannot determine row ID. Configure getRowId in gridConfig or ensure rows have an "id" property.',t),r}class Je{#i;constructor(e){this.#i=e}resolveRowId(e){return Qe(e,this.#i.id,this.#i.effectiveConfig?.getRowId)}getRow(e){return this.#i._getRowEntry(e)?.row}getRowEntry(e){return this.#i._getRowEntry(e)}updateRow(e,t,i="api"){const r=this.#i,n=r._getRowEntry(e);n||g(a,`Row with ID "${e}" not found. Ensure the row exists and getRowId is correctly configured.`,r.id);const{row:o,index:s}=n,l=[];for(const[a,d]of Object.entries(t)){const e=o[a];e!==d&&(l.push({field:a,oldValue:e,newValue:d}),o[a]=d,K(o,a))}for(const{field:a,oldValue:d,newValue:c}of l)r.dispatchEvent(new CustomEvent("cell-change",{detail:{row:o,rowId:e,rowIndex:s,field:a,oldValue:d,newValue:c,changes:t,source:i},bubbles:!0,composed:!0}));l.length>0&&(ke(r),r._requestSchedulerPhase(de.VIRTUALIZATION,"updateRow"),r._emitDataChange())}updateRows(e,t="api"){const i=this.#i;let r=!1;for(const{id:n,changes:o}of e){const e=i._getRowEntry(n);e||g(a,`Row with ID "${n}" not found. Ensure the row exists and getRowId is correctly configured.`,i.id);const{row:s,index:l}=e;for(const[a,d]of Object.entries(o)){const e=s[a];e!==d&&(r=!0,s[a]=d,K(s,a),i.dispatchEvent(new CustomEvent("cell-change",{detail:{row:s,rowId:n,rowIndex:l,field:a,oldValue:e,newValue:d,changes:o,source:t},bubbles:!0,composed:!0})))}}r&&(ke(i),i._requestSchedulerPhase(de.VIRTUALIZATION,"updateRows"),i._emitDataChange())}async insertRow(e,t,i=!0){const r=this.#i,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]),ke(r),r._rebuildRowIdMap(),r.__rowRenderEpoch++;for(let s=0;s<r._rowPool.length;s++)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 Xe(r,n,"insert"))}async removeRow(e,t=!0){const i=this.#i,r=i._rows[e];if(!r)return;t&&await Xe(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}}ke(i),i._rebuildRowIdMap(),i.__rowRenderEpoch++;for(let l=0;l<i._rowPool.length;l++)i._rowPool[l].__epoch=-1;return i.refreshVirtualWindow(!0),i._emitDataChange(),t&&requestAnimationFrame(()=>{const e=i.querySelectorAll('[data-animating="remove"]');for(let t=0;t<e.length;t++)e[t].removeAttribute("data-animating")}),r}async applyTransaction(e,t=!0){const i=this.#i,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 Xe(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,K(t,r),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){ke(i),i._rebuildRowIdMap(),i.__rowRenderEpoch++;for(let e=0;e<i._rowPool.length;e++)i._rowPool[e].__epoch=-1;i.refreshVirtualWindow(!0)}else s&&(ke(i),i._requestSchedulerPhase(de.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 Xe(i,t,"insert")}}if(t&&r.updated.length>0)for(const l of r.updated){const e=i._rows.indexOf(l);e>=0&&await Xe(i,e,"change")}return t&&r.removed.length>0&&requestAnimationFrame(()=>{const e=i.querySelectorAll('[data-animating="remove"]');for(let t=0;t<e.length;t++)e[t].removeAttribute("data-animating")}),r}#D=null;#F=[];#H=null;applyTransactionAsync(e){return this.#D||(this.#D={add:[],update:[],remove:[]}),e.add&&this.#D.add.push(...e.add),e.update&&this.#D.update.push(...e.update),e.remove&&this.#D.remove.push(...e.remove),new Promise(e=>{this.#F.push(e),null===this.#H&&(this.#H=requestAnimationFrame(()=>{this.#H=null;const e=this.#D,t=this.#F;this.#D=null,this.#F=[],this.applyTransaction(e,!1).then(e=>{for(const i of t)i(e)})}))})}}function et(e,t){if(t)for(const i in t){const r=t[i];null!=r&&e.setAttribute(i,r)}}function tt(e,t,i){const r=document.createElement(e);return et(r,t),r}function it(e,t){const i=document.createElement("div");return e&&(i.className=e),et(i,t),i}function rt(e,t,i){const r=document.createElement("button");return e&&(r.className=e),et(r,t),r}const nt=document.createElement("template");function ot(){return nt.content.cloneNode(!0)}function st(e){const t=document.createDocumentFragment(),i=it(e.hasShell?`${R.ROOT} has-shell`:R.ROOT);if(e.hasShell&&e.shellHeader&&e.shellBody)i.appendChild(e.shellHeader),i.appendChild(e.shellBody);else{const e=it("tbw-grid-content");e.appendChild(ot()),i.appendChild(e)}return t.appendChild(i),t}function lt(e){const t=it("tbw-shell-header",{part:"shell-header",role:"presentation"});if(e.title){const i=it("tbw-shell-title");i.textContent=e.title,t.appendChild(i)}const i=it("tbw-shell-content",{part:"shell-content",role:"presentation","data-light-dom-header-content":""});t.appendChild(i);const r=it("tbw-shell-toolbar",{part:"shell-toolbar",role:"presentation"});for(const n of e.configButtons)n.hasRender&&r.appendChild(it("tbw-toolbar-content-slot",{"data-toolbar-content":n.id}));for(const n of e.apiButtons)n.hasRender&&r.appendChild(it("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(it("tbw-toolbar-separator")),e.hasPanels){const t=rt(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.dataset.icon="tool-panel",void 0!==e.toolPanelIcon&&(t.innerHTML=F(e.toolPanelIcon)),r.appendChild(t)}return t.appendChild(r),t}function at(e){const t=it("tbw-shell-body"),i=e.panels.length>0,r=1===e.panels.length,n=it("tbw-grid-content");n.appendChild(ot());let o=null;if(i){o=tt("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(it("tbw-tool-panel-resize",{"data-resize-handle":"","data-handle-position":t,"aria-hidden":"true"}));const i=it("tbw-tool-panel-content",{role:"presentation"}),n=it("tbw-accordion");for(const o of e.panels){const t=it(`tbw-accordion-section${o.isExpanded?" expanded":""}${r?" single":""}`,{"data-section":o.id}),i=rt("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=tt("span",{class:"tbw-accordion-icon"});e.innerHTML=F(o.icon),i.appendChild(e)}const s=tt("span",{class:"tbw-accordion-title"});if(s.textContent=o.title,i.appendChild(s),!r){const t=tt("span",{class:"tbw-accordion-chevron","data-icon":"expand"});void 0!==e.expandIcon&&(t.innerHTML=F(e.expandIcon)),i.appendChild(t)}t.appendChild(i),t.appendChild(it("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}function dt(e){return e?"string"==typeof e?F(e):e.outerHTML:""}function ct(e){return!!e?.header?.title||(!!e?.header?.toolbarContents?.length||(!!e?.toolPanels?.length||(!!e?.headerContents?.length||(!!e?.header?.lightDomContent?.length||!!e?.header?.hasToolButtonsContainer))))}function ut(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 ht(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 gt(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 p("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=F(r.innerHTML.trim());d=t=>{const i=document.createElement("div");return i.innerHTML=e,t.appendChild(i),()=>i.remove()}}const u=t.toolPanels.get(n);if(u){if(c){u.render=d,u.order=a,u.icon=s,u.tooltip=l;const e=t.panelCleanups.get(n);e&&(e(),t.panelCleanups.delete(n))}return}const h={id:n,title:o,icon:s,tooltip:l,order:a,render:d};t.toolPanels.set(n,h),t.lightDomToolPanelIds.add(n),r.style.display="none"})}function pt(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 ft(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 wt(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 mt(e,t){const i=e.querySelector("[data-panel-toggle]");i&&(i.classList.toggle("active",t.isPanelOpen),i.setAttribute("aria-pressed",String(t.isPanelOpen)))}function bt(e,t){const i=e.querySelector(".tbw-tool-panel");i&&(i.classList.toggle("open",t.isPanelOpen),t.isPanelOpen||(i.style.width=""))}function vt(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 yt(e,t,i){const r=void 0!==i?.toolPanel?dt(i.toolPanel):void 0,n=void 0!==i?.expand?dt(i.expand):void 0,o=void 0!==i?.collapse?dt(i.collapse):void 0,s=[...e.header?.toolbarContents??[]].sort((e,t)=>(e.order??0)-(t.order??0)),l=[...e.toolPanels??[]].sort((e,t)=>(e.order??100)-(t.order??100));return{headerOptions:{title:e.header?.title??void 0,hasPanels:l.length>0,isPanelOpen:t.isPanelOpen,toolPanelIcon:r,configButtons:s.map(e=>({id:e.id,hasElement:!1,hasRender:!!e.render})),apiButtons:[]},bodyOptions:{position:e.toolPanel?.position??"right",isPanelOpen:t.isPanelOpen,expandIcon:n,collapseIcon:o,panels:l.map(e=>({id:e.id,title:e.title,icon:dt(e.icon),isExpanded:t.expandedSections.has(e.id)}))}}}function Ct(e,t,i,r){const n=ct(t),o=[],s=["tbw-grid-header","tbw-grid-tool-buttons","tbw-grid-tool-panel","tbw-grid-column","tbw-grid-detail","tbw-grid-responsive-card"];for(const l of s){e.querySelectorAll(`:scope > ${l}`).forEach(e=>o.push(e))}e.replaceChildren();for(const l of o)e.appendChild(l);if(n){const{headerOptions:n,bodyOptions:o}=yt(t,i,r),s=st({hasShell:!0,shellHeader:lt(n),shellBody:at(o)});e.appendChild(s)}else{const t=st({hasShell:!1});e.appendChild(t)}return n}function xt(e,t,i){const r=e.querySelector(`[data-section="${t}"]`);r&&r.classList.toggle("expanded",i)}nt.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 Rt="tbw-grid-styles";let Et="";const St=new Map;function _t(){const e=function(){let e=document.getElementById(Rt);return e||(e=document.createElement("style"),e.id=Rt,e.setAttribute("data-tbw-grid","true"),document.head.appendChild(e)),e}(),t=Array.from(St.values()).join("\n");e.textContent=`${Et}\n\n/* Plugin Styles */\n${t}`}async function At(e){if(Et)return;if("string"==typeof e&&e.length>0)return Et=e,void _t();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){p("TBW120",`Failed to extract grid.css from document stylesheets: ${e}`)}return null}();t?(Et=t,_t()):"undefined"!=typeof process&&"test"===process.env?.NODE_ENV||p("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 kt(e){e.startY=null,e.startX=null,e.lastY=null,e.lastX=null,e.lastTime=null,e.locked=!1}function Tt(e){e.momentumRaf&&(cancelAnimationFrame(e.momentumRaf),e.momentumRaf=0)}function It(e,t){if(null!==e.lastTime){performance.now()-e.lastTime>60&&(e.velocityY=0,e.velocityX=0)}(Math.abs(e.velocityY)>.1||Math.abs(e.velocityX)>.1)&&function(e,t){const i=.95,r=1;let n=performance.now();const o=()=>{const s=performance.now(),l=s-n;n=s;const a=l/16,d=Math.pow(i,a);e.velocityY*=d,e.velocityX*=d;const c=16*e.velocityY,u=16*e.velocityX,h=Math.abs(c)>=r,g=Math.abs(u)>=r;h&&(t.fauxScrollbar.scrollTop+=c),g&&t.scrollArea&&(t.scrollArea.scrollLeft+=u),e.momentumRaf=h||g?requestAnimationFrame(o):0};e.momentumRaf=requestAnimationFrame(o)}(e,t),kt(e)}function Mt(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){Tt(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){const{scrollTop:e,scrollHeight:t,clientHeight:i}=r.fauxScrollbar;if(o>0&&e<t-i||o<0&&e>0?r.fauxScrollbar.scrollTop+=o:0!==o&&window.scrollBy(0,o),r.scrollArea){const{scrollLeft:e,scrollWidth:t,clientWidth:i}=r.scrollArea;s>0&&e<t-i||s<0&&e>0?r.scrollArea.scrollLeft+=s:0!==s&&window.scrollBy(s,0)}return!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:u}=r.fauxScrollbar,h=c-u>0;let g=!1;if(r.scrollArea){const{scrollWidth:e,clientWidth:t}=r.scrollArea;g=e-t>0}return!!(d&&h||!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,It(t,i))},{passive:!0,signal:r}),e.addEventListener("pointercancel",e=>{e.pointerId===t.activePointerId&&(t.activePointerId=null,kt(t))},{passive:!0,signal:r}),e.addEventListener("lostpointercapture",e=>{e.pointerId===t.activePointerId&&(t.activePointerId=null,kt(t))},{passive:!0,signal:r})}const Lt=[{property:"editable",pluginName:"editing",level:"column",description:"",isUsed:e=>!0===e||"function"==typeof e},{property:"editor",pluginName:"editing",level:"column",description:""},{property:"editorParams",pluginName:"editing",level:"column",description:""},{property:"group",pluginName:"groupingColumns",level:"column",description:""},{property:"pinned",pluginName:"pinnedColumns",level:"column",description:"",isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e}],Pt=[{property:"rowEditable",pluginName:"editing",level:"config",description:"",isUsed:e=>"function"==typeof e},{property:"columnGroups",pluginName:"groupingColumns",level:"config",description:"",isUsed:e=>Array.isArray(e)&&e.length>0}];function Dt(e){return`import { ${Ft(e)}Plugin } from '@toolbox-web/grid/plugins/${t=e,t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}';`;var t}function Ft(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ht(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 Ot(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 Nt(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 qt(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 zt(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 u=n[c],h=l?.(u,c);if(void 0!==h){const e=i[c];return void((!e.measured||Math.abs(e.height-h)>1)&&(Nt(i,c,h),d=!0))}const g=e.offsetHeight;if(g>0){const e=i[c];(!e.measured||Math.abs(e.height-g)>1)&&(Nt(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,u,g,a),d=!0)}});const c=d?function(e){let t=0;for(const i of e)i.measured&&t++;return t}(i):0,u=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:u}}class $t{#i;state;constructor(e,t){this.#i=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.#i._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;return a=i.variableHeights&&i.positionCache?function(e){if(0===e.length)return 0;const t=e[e.length-1];return t.offset+t.height}(i.positionCache):e*i.rowHeight,a+s+l}initializePositionCache(){const e=this.state;if(!e.variableHeights)return;const t=this.#i,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=Ot(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.#i._rows;if(e<0||e>=r.length)return;const n=r[e];let o=t;void 0===o&&(o=this.#i._getPluginRowHeight(n,e)),void 0===o&&(o=i.rowHeight);const s=i.positionCache[e];if(s&&!(Math.abs(s.height-o)<1)&&(Nt(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.#i,n=r._bodyEl;if(!n)return;const o=n.querySelectorAll(".data-grid-row"),s=r.effectiveConfig?.getRowId,l=r._rows,a=zt({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.#i,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 u;e&&i.variableHeights&&this.initializePositionCache();const h=i.positionCache;i.variableHeights&&h&&h.length>0?(u=qt(h,c),-1===u&&(u=0)):u=Math.floor(c/d),u-=u%2,u<0&&(u=0);const g=r._adjustPluginVirtualStart(u,c,d);let p;if(void 0!==g&&g<u&&(u=g,u-=u%2,u<0&&(u=0)),i.variableHeights&&h&&h.length>0){const e=a+3*d;let t=0;for(p=u;p<o&&t<e;)t+=h[p].height,p++;const i=Math.ceil(a/d)+3;p-u<i&&(p=Math.min(u+i,o))}else{p=u+(Math.ceil(a/d)+3)}p>o&&(p=o);const f=i.start,w=i.end;if(!e&&u===f&&p===w)return!1;i.start=u,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(de.VIRTUALIZATION,"stale-refs-retry"),!1;if(e&&i.totalHeightEl){const e=this.calculateTotalSpacerHeight(o);i.totalHeightEl.style.height=`${e}px`}let b;b=i.variableHeights&&h&&h[u]?h[u].offset:u*d;const v=-(c-b);return n.style.transform=`translateY(${v}px)`,r._renderVisibleRows(u,p,r.__rowRenderEpoch),e&&i.variableHeights&&this.measureRenderedRowHeights(u,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 Bt{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;_hasProcessRows=!1;_hasRowStructurePlugins=!1;#G=new Map;eventListeners=new Map;queryHandlers=new Map;attachAll(e){const t=this.#O(e);for(const i of t)this.attach(i)}#O(e){if(e.length<2)return e;const t=new Map,i=new Map,r=[];for(const n of e){const e=n.constructor,o=t.get(e);if(!o){t.set(e,n),r.push(n);continue}const s=i.get(o)??[];s.push(n),i.set(o,s)}if(0===i.size)return r;for(const[n,o]of i)n.mergeConfigsFrom(o);return r}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??`${Ft(r)}Plugin requires ${Ft(e)}Plugin`,o=Dt(e);n&&g("TBW020",`Plugin dependency error:\n\n${t}.\n\n → Add the plugin to your gridConfig.plugins array BEFORE ${Ft(r)}Plugin:\n ${o}\n plugins: [new ${Ft(e)}Plugin(), new ${Ft(r)}Plugin()]`,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),e.attach(this.grid),this.#N();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)}}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,this._hasProcessRows=!1,this.#G.clear()}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){if(!this._hasProcessRows)return e;let t=e;for(const i of this.#q("processRows")){const e=i.processRows(t);e!==t&&(t=e)}return t}processColumns(e){let t=[...e];for(const i of this.#q("processColumns"))t=i.processColumns(t);return t}beforeRender(){for(const e of this.plugins)e.beforeRender?.()}afterRender(){for(const e of this.#q("afterRender"))e.afterRender()}afterCellRender(e){for(const t of this.#q("afterCellRender"))t.afterCellRender(e)}hasAfterCellRenderHook(){return this._hasAfterCellRender}afterRowRender(e){for(const t of this.#q("afterRowRender"))t.afterRowRender(e)}hasAfterRowRenderHook(){return this._hasAfterRowRender}#N(){this._hasAfterCellRender=this.plugins.some(e=>"function"==typeof e.afterCellRender),this._hasAfterRowRender=this.plugins.some(e=>"function"==typeof e.afterRowRender),this._hasProcessRows=this.plugins.some(e=>"function"==typeof e.processRows),this._hasRowStructurePlugins=this.plugins.some(e=>!0===e.constructor.manifest?.modifiesRowStructure),this.#G.clear()}#q(e){let t=this.#G.get(e);if(t)return t;t=this.plugins.filter(t=>e in t&&"function"==typeof t[e]);const i=t=>{const i=t.constructor.manifest?.hookPriority;if(!i)return 0;return i[e]??0};return t.some(e=>0!==i(e))&&t.sort((e,t)=>i(e)-i(t)),this.#G.set(e,t),t}onScrollRender(){for(const e of this.#q("onScrollRender"))e.onScrollRender()}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);void 0!==i&&t.push(i)}return t}for(const r of this.plugins){const i=r.handleQuery?.(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){w("TBW024",`Error in plugin event handler for "${e}": ${r}`,this.grid.getAttribute("id")??void 0)}}onKeyDown(e){for(const t of this.#q("onKeyDown"))if(t.onKeyDown(e))return!0;return!1}onCellClick(e){for(const t of this.#q("onCellClick"))if(t.onCellClick(e))return!0;return!1}onRowClick(e){for(const t of this.#q("onRowClick"))if(t.onRowClick(e))return!0;return!1}onHeaderClick(e){for(const t of this.#q("onHeaderClick"))if(t.onHeaderClick(e))return!0;return!1}onScroll(e){for(const t of this.#q("onScroll"))t.onScroll(e)}onCellMouseDown(e){for(const t of this.#q("onCellMouseDown"))if(t.onCellMouseDown(e))return!0;return!1}onCellMouseMove(e){for(const t of this.#q("onCellMouseMove"))if(t.onCellMouseMove(e))return!0;return!1}onCellMouseUp(e){for(const t of this.#q("onCellMouseUp"))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 Wt extends HTMLElement{static tagName="tbw-grid";static version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";static#z=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#$(){return this}#B=!1;#o;#s;#W=[];get#m(){return this.#K?.effective??{}}#V=!1;#j=!1;#U={rows:!1,columns:!1,gridConfig:!1,fitMode:!1};#Y;#X=0;#Z=null;#Q=!1;#J=!1;#ee=0;#te;#ie={startY:null,startX:null,lastY:null,lastX:null,lastTime:null,velocityY:0,velocityX:0,momentumRaf:0,locked:!1,activePointerId:null};#re;#ne;#oe;#se;#le={scrollTop:0,scrollLeft:0,scrollHeight:0,scrollWidth:0,clientHeight:0,clientWidth:0};#ae;#de;#ce;#ue;#he;#ge;get _pluginManager(){return this.#ae}#pe=!1;#fe;#we;#R;#K;#me=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}}();#be;#ve;#ye;#Ce=!1;#xe=new Set;#Re=new Map;#Ee;#Se=new Map;#_e=!1;_rows=[];#Ae=[];get _columns(){return this.#m.columns??[]}set _columns(e){this.#m.columns=e,this.#ke=void 0}#ke;get _visibleColumns(){return this.#ke??=this._columns.filter(e=>!e.hidden)}_invalidateVisibleColumnsCache(){this.#ke=void 0}_headerRowEl;_bodyEl;_rowPool=[];_resizeController;get _virtualization(){return this.#ue.state}set _virtualization(e){Object.assign(this.#ue.state,e)}_focusRow=0;_focusCol=0;_restoreFocusAfterRender=!1;_sortState=null;_gridTemplate="";__rowRenderEpoch=0;__didInitialAutoSize=!1;get __lightDomColumnsCache(){return this.#K?.lightDomColumnsCache}set __lightDomColumnsCache(e){this.#K&&(this.#K.lightDomColumnsCache=e)}get __originalColumnNodes(){return this.#K?.originalColumnNodes}set __originalColumnNodes(e){this.#K&&(this.#K.originalColumnNodes=e)}__originalOrder=[];__frameworkAdapter;__rowsBodyEl=null;get rows(){return this._rows}set rows(e){const t=Array.isArray(e)?e:[],i=this.#W;this.#W=t,i!==t&&this.#Te("rows")}get sourceRows(){return this.#W}set sourceRows(e){this.#W=Array.isArray(e)?e:[]}get columns(){return[...this._columns]}set columns(e){const t=this.#K?.getColumns();this.#K?.setColumns(e),t!==e&&this.#Te("columns")}get gridConfig(){return this.#m}set gridConfig(e){e&&this.__frameworkAdapter?.processConfig&&(e=this.__frameworkAdapter.processConfig(e));const t=this.#K?.getGridConfig();this.#K?.setGridConfig(e),t!==e&&(this.#K.clearLightDomCache(),this.#Te("gridConfig"))}get fitMode(){return this.#m.fitMode??"stretch"}set fitMode(e){const t=this.#K?.getFitMode();this.#K?.setFitMode(e),t!==e&&this.#Te("fitMode")}get loading(){return this.#Ce}set loading(e){const t=this.#Ce;this.#Ce=e,t!==e&&(e?(this.setAttribute("loading",""),this.setAttribute("aria-busy","true")):(this.removeAttribute("loading"),this.removeAttribute("aria-busy")),this.#Ie())}setRowLoading(e,t){const i=this.#xe.has(e);t?this.#xe.add(e):this.#xe.delete(e),i!==t&&this.#Me(e,t)}setCellLoading(e,t,i){let r=this.#Re.get(e);const n=r?.has(t)??!1;i?(r||(r=new Set,this.#Re.set(e,r)),r.add(t)):(r?.delete(t),0===r?.size&&this.#Re.delete(e)),n!==i&&this.#Le(e,t,i)}isRowLoading(e){return this.#xe.has(e)}isCellLoading(e,t){return this.#Re.get(e)?.has(t)??!1}clearAllLoading(){this.loading=!1;for(const e of this.#xe)this.#Me(e,!1);this.#xe.clear();for(const[e,t]of this.#Re)for(const i of t)this.#Le(e,i,!1);this.#Re.clear()}get effectiveConfig(){return this.#m}get disconnectSignal(){return this.#re||(this.#re=new AbortController),this.#re.signal}constructor(){super(),this.#Pe(),this.#o=new Promise(e=>this.#s=e),this.#ue=new $t(this),this.#he=new qe(this),this.#ge=new Je(this),this.#Y=new ce(this),this.#Y.setInitialReadyResolver(()=>this.#s?.()),this.#be=function(e,t){let i=!1;const r={get isInitialized(){return i},setInitialized(e){i=e},get isPanelOpen(){return e.isPanelOpen},get expandedSections(){return[...e.expandedSections]},openToolPanel(){if(e.isPanelOpen)return;if(0===e.toolPanels.size)return void p("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;mt(i,e),bt(i,e),wt(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;mt(i,e),bt(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 p("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),xt(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),xt(n,t,!1);const o=n.querySelector(`[data-section="${t}"] .tbw-accordion-content`);o&&(o.innerHTML="")}e.expandedSections.add(i),xt(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)?p("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)?p("TBW074",`Header content "${r.id}" already registered`,t.id):(e.headerContents.set(r.id,r),i&&ft(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)?p("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.#me,this),this.#K=new ue(this)}async#Pe(){await At('@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);--tbw-icon-expand: "▶";--tbw-icon-collapse: "▼";--tbw-icon-sort-asc: "▲";--tbw-icon-sort-desc: "▼";--tbw-icon-sort-none: "⇅";--tbw-icon-submenu-arrow: "▶";--tbw-icon-drag-handle: "⋮⋮";--tbw-icon-tool-panel: "☰";--tbw-icon-filter: "";--tbw-icon-filter-active: "";--tbw-icon-print: "🖨️";--tbw-icon-expand-mask: none;--tbw-icon-collapse-mask: none;--tbw-icon-sort-asc-mask: none;--tbw-icon-sort-desc-mask: none;--tbw-icon-sort-none-mask: none;--tbw-icon-submenu-arrow-mask: none;--tbw-icon-drag-handle-mask: none;--tbw-icon-tool-panel-mask: none;--tbw-icon-filter-mask: url("data:image/svg+xml,%3Csvg viewBox=\'0 0 16 16\' width=\'12\' height=\'12\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Cpath 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\'/%3E%3C/svg%3E");--tbw-icon-filter-active-mask: var(--tbw-icon-filter-mask);--tbw-icon-print-mask: none}}\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 [data-icon=expand]:empty:before{content:var(--tbw-icon-expand)}tbw-grid [data-icon=collapse]:empty:before{content:var(--tbw-icon-collapse)}tbw-grid [data-icon=sort-asc]:empty:before{content:var(--tbw-icon-sort-asc)}tbw-grid [data-icon=sort-desc]:empty:before{content:var(--tbw-icon-sort-desc)}tbw-grid [data-icon=sort-none]:empty:before{content:var(--tbw-icon-sort-none)}tbw-grid [data-icon=submenu-arrow]:empty:before{content:var(--tbw-icon-submenu-arrow)}tbw-grid [data-icon=drag-handle]:empty:before{content:var(--tbw-icon-drag-handle)}tbw-grid [data-icon=tool-panel]:empty:before{content:var(--tbw-icon-tool-panel)}tbw-grid [data-icon=print]:empty:before{content:var(--tbw-icon-print)}tbw-grid [data-icon=filter]:empty:before{content:var(--tbw-icon-filter)}tbw-grid [data-icon=filter-active]:empty:before{content:var(--tbw-icon-filter-active)}tbw-grid [data-icon]:empty:before{display:inline-block;vertical-align:middle;-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center}tbw-grid [data-icon=expand]:empty:before{-webkit-mask-image:var(--tbw-icon-expand-mask);mask-image:var(--tbw-icon-expand-mask)}tbw-grid [data-icon=collapse]:empty:before{-webkit-mask-image:var(--tbw-icon-collapse-mask);mask-image:var(--tbw-icon-collapse-mask)}tbw-grid [data-icon=sort-asc]:empty:before{-webkit-mask-image:var(--tbw-icon-sort-asc-mask);mask-image:var(--tbw-icon-sort-asc-mask)}tbw-grid [data-icon=sort-desc]:empty:before{-webkit-mask-image:var(--tbw-icon-sort-desc-mask);mask-image:var(--tbw-icon-sort-desc-mask)}tbw-grid [data-icon=sort-none]:empty:before{-webkit-mask-image:var(--tbw-icon-sort-none-mask);mask-image:var(--tbw-icon-sort-none-mask)}tbw-grid [data-icon=submenu-arrow]:empty:before{-webkit-mask-image:var(--tbw-icon-submenu-arrow-mask);mask-image:var(--tbw-icon-submenu-arrow-mask)}tbw-grid [data-icon=drag-handle]:empty:before{-webkit-mask-image:var(--tbw-icon-drag-handle-mask);mask-image:var(--tbw-icon-drag-handle-mask)}tbw-grid [data-icon=tool-panel]:empty:before{-webkit-mask-image:var(--tbw-icon-tool-panel-mask);mask-image:var(--tbw-icon-tool-panel-mask)}tbw-grid [data-icon=print]:empty:before{-webkit-mask-image:var(--tbw-icon-print-mask);mask-image:var(--tbw-icon-print-mask)}tbw-grid [data-icon=filter]:empty:before,tbw-grid [data-icon=filter-active]:empty:before{width:var(--tbw-icon-size, 1em);height:var(--tbw-icon-size, 1em);background:currentColor}tbw-grid [data-icon=filter]:empty:before{-webkit-mask-image:var(--tbw-icon-filter-mask);mask-image:var(--tbw-icon-filter-mask)}tbw-grid [data-icon=filter-active]:empty:before{-webkit-mask-image:var(--tbw-icon-filter-active-mask);mask-image:var(--tbw-icon-filter-active-mask)}.tbw-context-menu [data-icon]:empty:before{display:inline-block;width:1em;height:1em;vertical-align:middle}.tbw-context-menu [data-icon=submenu-arrow]:empty:before{content:var(--tbw-icon-submenu-arrow, "▶")}}\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)}@media(hover:hover){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.#ae?.getPlugin(e)}getPluginByName(e){return this.#ae?.getPluginByName(e)}requestRender(){this.#Y.requestPhase(de.ROWS,"plugin:requestRender")}requestColumnsRender(){this.#Y.requestPhase(de.COLUMNS,"plugin:requestColumnsRender")}requestRenderWithFocus(){this._restoreFocusAfterRender=!0,this.#Y.requestPhase(de.ROWS,"plugin:requestRenderWithFocus")}updateTemplate(){x(this)}requestAfterRender(){this.#Y.requestPhase(de.STYLE,"plugin:requestAfterRender")}requestVirtualRefresh(){this._virtualization.start=-1,this.refreshVirtualWindow(!1)}#De(){this.#ae=new Bt(this);const e=this.#m?.plugins,t=Array.isArray(e)?e:[],i=this.#m?.features;let r=[];i&&Ne&&(r=Ne(i));const n=r.length>0?[...r,...t]:t;this.#ae.attachAll(n)}#Fe(){!function(e){let t=!1;for(const{name:i,styles:r}of e)St.has(i)||(St.set(i,r),t=!0);t&&_t()}(this.#ae?.getPluginStyles()??[])}#He(){const e=this.#m?.plugins,t=Array.isArray(e)?e:[],i=this.#m?.features??void 0,r=i!==this.#ce;if((this.#de===t||void 0!==this.#de&&this.#de.length===t.length&&this.#de.every((e,i)=>e===t[i]))&&!r)return void(this.#de=t);this.#ae&&this.#ae.detachAll();for(const o of this.#me.toolPanels.keys()){const e=this.#me.lightDomToolPanelIds.has(o),t=this.#me.apiToolPanelIds.has(o);if(!e&&!t){const e=this.#me.panelCleanups.get(o);e&&(e(),this.#me.panelCleanups.delete(o)),this.#me.toolPanels.delete(o)}}for(const o of this.#me.headerContents.keys()){if(this.#me.apiHeaderContentIds.has(o))continue;const e=this.#me.headerContentCleanups.get(o);e&&(e(),this.#me.headerContentCleanups.delete(o)),this.#me.headerContents.delete(o)}this.#De(),this.#Fe(),this.#de=t,this.#ce=i,this.#Ge(),this.#Oe();const n=this.#Q;if(this.#Q=this.#ae?.getAll().some(e=>e.onScroll)??!1,!n&&this.#Q){const e=this.#$.querySelector(".tbw-grid-content")??this.#$.querySelector(".tbw-grid-root");this.#Ne(e)}}#qe(){this.#ae?.detachAll()}#Oe(){if(!this.#ae)return;const e=this.#ae.getToolPanels();for(const{panel:i}of e)this.#me.toolPanels.has(i.id)||this.#me.toolPanels.set(i.id,i);const t=this.#ae.getHeaderContents();for(const{content:i}of t)this.#me.headerContents.has(i.id)||this.#me.headerContents.set(i.id,i)}#ze(){const e=Wt.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",Wt.version),this.id||(this.id="tbw-grid-"+ ++Wt.#z),this._rows=Array.isArray(this.#W)?[...this.#W]:[],this.#re&&(this.#re.abort(),this.#pe=!1),this.#re=new AbortController,this.#se&&($e(this.#se),this.#se=void 0),this.#$e(),this.#K.parseLightDomColumns(this),this.#K.merge(),this.#De();const e=this.#m?.plugins;var t,i;this.#de=Array.isArray(e)?e:[],this.#ce=this.#m?.features??void 0,this.#Oe(),this.#B||(this.#Be(),this.#Fe(),this.#B=!0),this.#We(),this.#se=(t=()=>{this.#Ke()},i={timeout:100},ze?requestIdleCallback(t,i):window.setTimeout(()=>{const e=Date.now();t({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-e))})},1))}disconnectedCallback(){this.#se&&($e(this.#se),this.#se=void 0),this.#ee&&(clearTimeout(this.#ee),this.#ee=0),this.#qe(),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.#me),this.#be.setInitialized(!1),this.#ve?.(),this.#ve=void 0,this.#ye?.(),this.#ye=void 0,Tt(this.#ie),this.#re&&(this.#re.abort(),this.#re=void 0),this.#fe?.abort(),this.#fe=void 0,this.#pe=!1,this._resizeController&&this._resizeController.dispose(),this.#ne&&(this.#ne.disconnect(),this.#ne=void 0),this.#oe&&(this.#oe.disconnect(),this.#oe=void 0,this.#Ve=!1),ke(this),this.#je.clear(),this._virtualization.heightCache?.byKey.clear(),this.#de=void 0,this.#ce=void 0;for(let e=0;e<this._rowPool.length;e++)this._rowPool[e].remove();this._rowPool.length=0,this.__rowsBodyEl=null,this.#V=!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{p("TBW130",`Invalid JSON for '${e}' attribute: ${i}`,this.id)}else"fit-mode"===e&&(this.fitMode=i)}#We(){const e=this.#$.querySelector(".tbw-grid-content")??this.#$.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.#be.isInitialized){ft(this.#$,this.#me),pt(this.#$,this.#m?.shell,this.#me);const e=this.#m?.shell?.toolPanel?.defaultOpen;e&&this.#me.toolPanels.has(e)&&(this.openToolPanel(),this.#me.expandedSections.add(e)),this.#me.isPanelOpen&&(bt(this.#$,this.#me),wt(this.#$,this.#me,(this.#m,this.#m)),mt(this.#$,this.#me))}if(this.setAttribute("data-upgraded",""),this.#V=!0,this._resizeController=Ke(this),this.#Ue(),this.#Ne(e),this.#pe)return;this.#pe=!0;const t=this.disconnectSignal;Oe(this,this,this.#$,t),this.#Ge(),queueMicrotask(()=>this.#Ye()),this.#Y.requestPhase(de.FULL,"afterConnect")}#Ge(){const e=this.#m.rowHeight,t=this.#ae.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.#ue.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.#Xe())}#Xe(){if(this.#ae.hasRowHeightPlugin())return;const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;if(e.style.getPropertyValue("--tbw-row-height"))return;const t=this.#Ze(),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.#Y.requestPhase(de.VIRTUALIZATION,"measureRowHeight"))}#Ze(){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}#Qe(){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.#ue.initializePositionCache(),this._virtualization.totalHeightEl){const e=this.#ue.calculateTotalSpacerHeight(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}}#Ne(e){this.#fe?.abort(),this.#fe=new AbortController;const t=this.#fe.signal,i=e?.querySelector(".faux-vscroll"),r=e?.querySelector(".rows");if(this._virtualization.container=i??this,this.#Q=this.#ae?.getAll().some(e=>e.onScroll)??!1,i&&r){i.addEventListener("scroll",()=>{if(!this._virtualization.enabled&&!this.#Q)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=qt(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.#Z=e,this.#X||(this.#X=requestAnimationFrame(()=>{this.#X=0,null!==this.#Z&&(this.#Je(this.#Z),this.#Z=null)}))},{passive:!0,signal:t});const e=this.#$.querySelector(".tbw-scroll-area");this.#we=e,this._virtualization.scrollAreaEl=e,e&&this.#Q&&e.addEventListener("scroll",()=>{const t=this.#le;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.#ae?.onScroll(t)},{passive:!0,signal:t});const n=this.#$.querySelector(".tbw-grid-content"),o=this.#we;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}),Mt(n,this.#ie,{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(R.EDITING))return;const i=e.target;i.draggable||i.closest('[draggable="true"]')||e.preventDefault(),He(n,t)},{signal:s}),o.addEventListener("click",e=>{const t=e.target.closest(".data-grid-row");if(t&&Me(n,e,t),!document.activeElement?.closest(`.cell.${R.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&&Me(n,e,t)},{signal:s})),this.#ne?.disconnect(),this._virtualization.viewportEl&&(this.#ne=new ResizeObserver(()=>{this.#et(),this.#Y.requestPhase(de.VIRTUALIZATION,"resize-observer")}),this.#ne.observe(this._virtualization.viewportEl)),this.#$.addEventListener("focusin",()=>{this.dataset.hasFocus=""},{signal:t}),this.#$.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.#$.contains(t)||this.#he.isInExternalFocusContainer(t))||delete this.dataset.hasFocus},{signal:t})}#Ve=!1;#tt(){if(this.#Ve)return;const e=this._bodyEl?.querySelector(".data-grid-row");e&&(this.#Ve=!0,this.#oe?.disconnect(),this.#oe=new ResizeObserver(()=>{this.#Xe()}),this.#oe.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)}#it(e,t){this.#V&&this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}_emitDataChange(){this.#it("data-change",{rowCount:this._rows.length,sourceRowCount:this.#W.length}),function(e,t,i){if(i===t.lastAnnouncedSourceCount)return;const r=t.lastAnnouncedSourceCount;t.lastAnnouncedSourceCount=i,0===i&&r<0||o(e,s(e,"dataLoaded",i))}(this,this.#rt,this.#W.length)}#Ye(){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))})})}#Te(e){this.#U[e]=!0,this.#j||(this.#j=!0,queueMicrotask(()=>this.#nt()))}#nt(){if(!this.#j||!this.#V)return void(this.#j=!1);const e=this.#U;if(this.#j=!1,this.#U={rows:!1,columns:!1,gridConfig:!1,fitMode:!1},e.gridConfig)return this.#ot(),void(e.rows&&this.#st());e.columns&&this.#lt(),e.rows&&this.#st(),e.fitMode&&this.#at()}#st(){this._rows=Array.isArray(this.#W)?[...this.#W]:[],this.#_e=!0,this.#Y.requestPhase(de.ROWS,"applyRowsUpdate")}#dt(){this.#_e&&this._rebuildRowIdMap()}_rebuildRowIdMap(){this.#_e=!1,this.#Se.clear();const e=this.#m.getRowId;for(let t=0;t<this._rows.length;t++){const i=Ze(this._rows[t],e);void 0!==i&&this.#Se.set(i,{row:this._rows[t],index:t})}}#lt(){ke(this),this.#K.merge(),this.#Ue()}#at(){this.#K.merge();if("fixed"===this.#m.fitMode)this.__didInitialAutoSize=!1,v(this);else{for(let e=0;e<this._columns.length;e++){const t=this._columns[e];!t.__userResized&&t.__autoSized&&delete t.width}x(this)}}#ot(){ut(this,this.#me),ht(this,this.#me);const e=!!this.#$.querySelector(".has-shell"),t=!!this.#$.querySelector(".tbw-tool-panel"),i=this.#$.querySelectorAll(".tbw-accordion-section").length,r=this.#$.querySelector(".tbw-tool-panel")?.dataset.position??"right";this.#K.parseLightDomColumns(this),this.#K.merge(),this.#He(),this.#Ge(),gt(this,this.#me,this.#ze()),this.#K.markSourcesChanged(),this.#K.merge();const n=ct(this.#m?.shell),o=(this.#m?.shell?.toolPanels?.length??0)>0,s=this.#m?.shell?.toolPanels?.length??0,l=this.#m?.shell?.toolPanel?.position??"right";if(e!==n||!t&&o||t&&s!==i||t&&r!==l)return vt(this.#me),this.#Be(),this.#Fe(),this.#We(),void this._rebuildRowIdMap();e&&this.#ct(),this.#me.isPanelOpen&&wt(this.#$,this.#me,(this.#m,this.#m)),this._rebuildRowIdMap(),this.#Y.requestPhase(de.COLUMNS,"applyGridConfigUpdate")}#ct(){const e=this.#$.querySelector(".tbw-shell-header");if(!e)return;const t=this.#m.shell?.header?.title??this.#me.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()}#ut(){if(this.__rowRenderEpoch++,this.#ae){const e=this.#Ae.length>0?this.#Ae:this._columns,t=e.filter(e=>!e.hidden),i=e.filter(e=>e.hidden),r=this.#ae.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.#ht(e,r,i)}else this._columns=[...e]}}#ht(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}#gt(){ke(this);const e=this.#W;if(!Array.isArray(e))return this._rows=[],this._rebuildRowIdMap(),this._virtualization.variableHeights&&this.#ue.initializePositionCache(),void this._emitDataChange();if(!this._sortState&&this.#m.initialSort){const{field:e,direction:t}=this.#m.initialSort;this._columns.find(t=>t.field===e)&&(this._sortState={field:e,direction:"desc"===t?-1:1})}this._sortState&&(this.__originalOrder=this._rows);const t=function(e,t,i=!1){if(!e._sortState)return t;const r=e.effectiveConfig?.sortHandler??V;if(r===V)return i||(e.__originalOrder=t.slice()),X(t,e._sortState.field,e._sortState.direction,e._columns),t;i||(e.__originalOrder=t);const n=r(t,e._sortState,e._columns);return n&&"function"==typeof n.then?t:n}(this,this._sortState?[...e]:e,!0),i=this.#ae?.processRows(t)??t;this._rows=i,this._rebuildRowIdMap(),this._emitDataChange()}#pt(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.#te||(this.#te=(e,t,i)=>this.#ae?.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=Ae();e._rowPool.push(t)}if(e._rowPool.length>o){const t=e.__frameworkAdapter,i=t?.releaseCell;for(let r=o;r<e._rowPool.length;r++){const n=e._rowPool[r];if(i){const e=n.children;for(let r=0;r<e.length;r++){const n=e[r];n.firstElementChild&&i.call(t,n)}}n.parentNode===s&&n.remove()}e._rowPool.length=o}const c=n&&!1!==e.__hasRenderRowPlugins,u=e._hasAfterRowRenderHook?.()??!1,h=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=xe(w),n=x&&!C||e._activeEditRows===i;t&&!n?(w.__isCustomRow&&(w.className="data-grid-row",w.setAttribute("role","row"),w.__isCustomRow=!1),Re(w),Ie(e,w,o,i),w.__epoch=r,w.__rowDataRef=o):t&&n?(Te(e,w,o,i),w.__rowDataRef=o):(w.__isCustomRow&&(w.className="data-grid-row",w.setAttribute("role","row"),w.__isCustomRow=!1),Ie(e,w,o,i),w.__epoch=r,w.__rowDataRef=o)}else if(C){const t=xe(w),n=e._activeEditRows===i;t&&!n?(Re(w),Ie(e,w,o,i),w.__epoch=r,w.__rowDataRef=o):(Te(e,w,o,i),w.__rowDataRef=o)}else{const t=xe(w),n=x||e._activeEditRows===i;t&&!n?(Re(w),Ie(e,w,o,i),w.__epoch=r,w.__rowDataRef=o):Te(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");if(t){const e=t.split(" ");for(let t=0;t<e.length;t++)e[t]&&w.classList.remove(e[t])}try{const e=_(o),t="string"==typeof e?e.split(/\s+/):e;if(t&&t.length>0){let e="";for(let i=0;i<t.length;i++){const r=t[i];r&&"string"==typeof r&&(w.classList.add(r),e+=(e?" ":"")+r)}w.setAttribute("data-dynamic-classes",e)}else w.removeAttribute("data-dynamic-classes")}catch(g){p("TBW060",`rowClass callback error: ${g}`,e.id),w.removeAttribute("data-dynamic-classes")}}if(h){const e=h(o,i);void 0!==e&&e>0?w.style.setProperty("--tbw-row-height",`${e}px`):w.style.removeProperty("--tbw-row-height")}u&&e._afterRowRender?.({row:o,rowIndex:i,rowElement:w}),w.parentNode!==s&&s.appendChild(w)}}(this,e,t,i,this.#te),this.#xe.size>0)for(const r of this.#xe)this.#Me(r,!0)}#rt={rowCount:-1,colCount:-1,ariaLabel:void 0,ariaDescribedBy:void 0,lastAnnouncedSourceCount:-1};_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.#rt,this.__rowsBodyEl,this._bodyEl,e,t)}_requestSchedulerPhase(e,t){this.#Y.requestPhase(e,t)}_getPluginRowHeight(e,t){return this.#ae?.getRowHeight?.(e,t)}_adjustPluginVirtualStart(e,t,i){return this.#ae?.adjustVirtualStart(e,t,i)}_afterPluginRender(){this.#ae?.afterRender()}_emitPluginEvent(e,t){this.#ae?.emitPluginEvent(e,t)}_schedulerMergeConfig(){this.#K.parseLightDomColumns(this),this.#K.merge(),this.#He(),function(e,t,i){const r=Lt,n=Pt,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];if((a.isUsed?a.isUsed(i):void 0!==i)&&!Ht(t,a.pluginName)){const e=a.description||`the "${a.property}" ${a.level} property`;s(a.pluginName,e,Dt(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)&&!Ht(t,e.pluginName)){const t=a.field||"<unknown>",i=e.description||`the "${e.property}" ${e.level} property`;s(e.pluginName,i,Dt(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 ${Ft(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 ${Ft(t)}Plugin(), ...]`)}g([...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.#m,this.#ae?.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=`[${Ft(n.name)}Plugin] Configuration warning: ${t.message}`;"error"===t.severity?i.push(e):r.push(e)}}}if(r.length>0&&he())for(const n of r)p("TBW004",n,t);i.length>0&&g("TBW003",`Configuration error:\n\n${i.join("\n\n")}`,t)}(this.#ae?.getPlugins()??[],this.id),function(e,t){if(!he())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),p("TBW022",`${Ft(n.name)}Plugin and ${Ft(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.#ae?.getPlugins()??[],this.id),this.#ft(),this.#Ae=[...this._columns]}_schedulerProcessColumns(){this.#ut()}_schedulerProcessRows(){this.#gt()}_schedulerRenderHeader(){le(this)}_schedulerUpdateTemplate(){x(this)}_schedulerAfterRender(){this.#ae?.afterRender(),this._virtualization.enabled&&this._virtualization.totalHeightEl&&queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const e=this.#ue.calculateTotalSpacerHeight(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`});"fixed"!==this.#m.fitMode||this.__didInitialAutoSize||(this.__didInitialAutoSize=!0,v(this)),this._restoreFocusAfterRender&&(this._restoreFocusAfterRender=!1,De(this)),this._virtualization.enabled&&!this.#Ve&&this.#tt(),this.#J&&(this.#J=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.#Qe()})})),this.#Ce&&this.#Ie()}get _schedulerIsConnected(){return this.isConnected&&this.#V}get _hostElement(){return this}get _renderRoot(){return this.#$}_emit(e,t){this.#it(e,t)}get _accordionIcons(){return{expand:this.#m?.icons?.expand??n.expand,collapse:this.#m?.icons?.collapse??n.collapse}}get _shellState(){return this.#me}_clearRowPool(){const e=this.__frameworkAdapter,t=e?.releaseCell;if(t)for(let i=0;i<this._rowPool.length;i++){const r=this._rowPool[i].children;for(let i=0;i<r.length;i++){const n=r[i];n.firstElementChild&&t.call(e,n)}}this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++}_setup(){this.#Ue()}_applyAnimationConfig(e){this.#pt(e)}#ft(){!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.#rt,this.__rowsBodyEl,this.#m,this.#me)}#Ie(){const e=this.querySelector(".tbw-grid-root");var t;e&&(this.#Ce?(this.#Ee||(this.#Ee=function(e){const t=document.createElement("div");return t.className="tbw-loading-overlay",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.appendChild(Be("large",e)),t}(this.#m?.loadingRenderer)),function(e,t){e.appendChild(t)}(e,this.#Ee)):(t=this.#Ee,t?.remove()))}#Me(e,t){this.#dt();const i=this.#Se.get(e);if(!i)return;const r=this.findRenderedRowElement?.(i.index);r&&We(r,t)}#Le(e,t,i){this.#dt();const r=this.#Se.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)}#Ue(){if(this.isConnected&&this._headerRowEl&&this._bodyEl){if(this.#K.parseLightDomColumns(this),this.#R){const e=this.#R;this.#R=void 0,this.#K.merge();const t=this.#ae?.getAll()??[];this.#K.applyState(e,t)}this._bodyEl&&(this._bodyEl.style.display="",this._bodyEl.style.gridTemplateColumns=""),this.#Y.requestPhase(de.FULL,"setup")}}#Je(e){const t=this._virtualization.container,i=this.#we,r=i?.scrollLeft??0,n=t?.scrollHeight??0,o=i?.scrollWidth??0,s=t?.clientHeight??0,l=i?.clientWidth??0;if(this.refreshVirtualWindow(!1)&&this.#ae?.onScrollRender(),this._virtualization.variableHeights&&(this.#ee&&clearTimeout(this.#ee),this.#ee=window.setTimeout(()=>{this.#ee=0,this.#ue.measureRenderedRowHeights(this._virtualization.start,this._virtualization.end)},100)),this.#Q){const t=this.#le;t.scrollTop=e,t.scrollLeft=r,t.scrollHeight=n,t.scrollWidth=o,t.clientHeight=s,t.clientWidth=l,this.#ae?.onScroll(t)}this.#it("tbw-scroll",{scrollTop:e,scrollHeight:n,clientHeight:s,direction:"vertical"})}findHeaderRow(){return this.#$.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.#ae?.onCellClick(d)??!1;return this.#it("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.#ae?.onRowClick(n)??!1;return this.#it("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.#ae?.onHeaderClick(r)??!1}_dispatchKeyDown(e){return this.#ae?.onKeyDown(e)??!1}_getHorizontalScrollOffsets(e,t){return this.#ae?.getHorizontalScrollOffsets(e,t)??{left:0,right:0}}query(e,t){return this.#ae?.queryPlugins({type:e,context:t})??[]}_dispatchCellMouseDown(e){return this.#ae?.onCellMouseDown(e)??!1}_dispatchCellMouseMove(e){this.#ae?.onCellMouseMove(e)}_dispatchCellMouseUp(e){this.#ae?.onCellMouseUp(e)}_afterCellRender(e){this.#ae?.afterCellRender(e)}_hasAfterCellRenderHook(){return this.#ae?.hasAfterCellRenderHook()??!1}_afterRowRender(e){this.#ae?.afterRowRender(e)}_hasAfterRowRenderHook(){return this.#ae?.hasAfterRowRenderHook()??!1}async ready(){return this.#o}async forceLayout(){return 0===this.#Y.pendingPhase&&this.#Y.requestPhase(de.FULL,"forceLayout"),this.#Y.whenReady()}async getConfig(){return Object.freeze({...this.#m||{}})}getRowId(e){return Qe(e,this.id,this.#m.getRowId)}getRow(e){return this.#ge.getRow(e)}_getRowEntry(e){return this.#dt(),this.#Se.get(e)}updateRow(e,t,i="api"){this.#ge.updateRow(e,t,i)}updateRows(e,t="api"){this.#ge.updateRows(e,t)}animateRow(e,t){return Xe(this,e,t)}animateRows(e,t){return function(e,t,i){return Promise.all(t.map(t=>Xe(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):Xe(e,o,i)}(this,e,t)}async insertRow(e,t,i=!0){return this.#ge.insertRow(e,t,i)}async removeRow(e,t=!0){return this.#ge.removeRow(e,t)}async applyTransaction(e,t=!0){return this.#ge.applyTransaction(e,t)}applyTransactionAsync(e){return this.#ge.applyTransactionAsync(e)}focusCell(e,t){this.#he.focusCell(e,t)}get focusedCell(){return this.#he.focusedCell}scrollToRow(e,t){this.#he.scrollToRow(e,t)}scrollToRowById(e,t){this.#he.scrollToRowById(e,t)}setColumnVisible(e,t){const i=this.#K.setColumnVisible(e,t);return i&&this.requestStateChange(),i}toggleColumnVisibility(e){const t=this.#K.toggleColumnVisibility(e);return t&&this.requestStateChange(),t}isColumnVisible(e){return this.#K.isColumnVisible(e)}showAllColumns(){this.#K.showAllColumns(),this.requestStateChange()}getAllColumns(){return this.#K.getAllColumns()}setColumnOrder(e){this.#K.setColumnOrder(e),this.requestStateChange()}getColumnOrder(){return this.#K.getColumnOrder()}getColumnState(){const e=this.#ae?.getAll()??[];return this.#K.collectState(e)}get columnState(){return this.getColumnState()}applyColumnState(e){e&&(this.#B?this.#wt(e):(this.#R=e,this.#K.initialColumnState=e))}#wt(e){const t=this._columns,i=this._sortState,r=this.#ae?.getAll()??[];this.#K.applyState(e,r);if(!e.columns.some(e=>void 0!==e.sort)&&this.#mt(t,i))return this.#ke=void 0,x(this),void this.#Y.requestPhase(de.STYLE,"column-width");this.#Ue()}#mt(e,t){const i=this._columns,r=this._sortState;if(t?.field!==r?.field||t?.direction!==r?.direction)return!1;if(e.length!==i.length)return!1;for(let n=0;n<e.length;n++){const t=e[n],r=i[n];if(t.field!==r.field)return!1;if(!!t.hidden!=!!r.hidden)return!1}return!0}get sortModel(){return this._sortState?{field:this._sortState.field,direction:1===this._sortState.direction?"asc":"desc"}:null}sort(e,t){if(null===e){if(!this._sortState)return;const e=this._sortState.field;this._sortState=null,this.__rowRenderEpoch++;for(let t=0;t<this._rowPool.length;t++)this._rowPool[t].__epoch=-1;return this._rows=this.__originalOrder.slice(),this.__originalOrder=[],le(this),this.refreshVirtualWindow(!0),this.dispatchEvent(new CustomEvent("sort-change",{detail:{field:e,direction:0}})),this._pluginManager?.emitPluginEvent?.("sort-change",{field:e,direction:0}),void this.requestStateChange?.()}const i=this._columns.find(t=>t.field===e);i&&(t?(this._sortState||(this.__originalOrder=this._rows.slice()),te(this,i,"desc"===t?-1:1)):ee(this,i))}requestStateChange(){const e=this.#ae?.getAll()??[];this.#K.requestStateChange(e)}resetColumnState(){this.#R=void 0,this.__originalOrder=[];const e=this.#ae?.getAll()??[];this.#K.resetState(e),this.#K.merge(),this.#Ue()}get isToolPanelOpen(){return this.#be.isPanelOpen}get defaultRowHeight(){return this._virtualization.rowHeight}get expandedToolPanelSections(){return this.#be.expandedSections}openToolPanel(){this.#be.openToolPanel()}closeToolPanel(){this.#be.closeToolPanel()}toggleToolPanel(){this.#be.toggleToolPanel()}toggleToolPanelSection(e){this.#be.toggleToolPanelSection(e)}getToolPanels(){return this.#be.getToolPanels()}registerToolPanel(e){this.#me.apiToolPanelIds.add(e.id),this.#be.registerToolPanel(e)}unregisterToolPanel(e){this.#me.apiToolPanelIds.delete(e),this.#be.unregisterToolPanel(e)}getHeaderContents(){return this.#be.getHeaderContents()}registerHeaderContent(e){this.#me.apiHeaderContentIds.add(e.id),this.#be.registerHeaderContent(e)}unregisterHeaderContent(e){this.#me.apiHeaderContentIds.delete(e),this.#be.unregisterHeaderContent(e)}getToolbarContents(){return this.#be.getToolbarContents()}registerToolbarContent(e){this.#be.registerToolbarContent(e)}unregisterToolbarContent(e){this.#be.unregisterToolbarContent(e)}#bt=!1;refreshShellHeader(){this.#bt||(this.#bt=!0,queueMicrotask(()=>{if(this.#bt=!1,!this.isConnected)return;this.#$e(),this.#K.markSourcesChanged(),this.#K.merge(),vt(this.#me);(function(e,t,i,r){const n=e.querySelector(`.${R.ROOT}`),o=n?.querySelector(".tbw-grid-content");if(!n||!o)return Ct(e,t,i,r);o.remove();const s=ct(t);if(n.replaceChildren(),s){n.className=`${R.ROOT} has-shell`;const{headerOptions:e,bodyOptions:s}=yt(t,i,r),l=lt(e),a=at(s),d=a.querySelector(".tbw-grid-content");d&&d.replaceWith(o),n.appendChild(l),n.appendChild(a)}else n.className=R.ROOT,n.appendChild(o);return s})(this.#$,this.#m?.shell,{isPanelOpen:this.#me.isPanelOpen,expandedSections:this.#me.expandedSections},this.#m?.icons)&&(this.#vt(),this.#be.setInitialized(!0)),this.#yt()}))}#yt(){const e=this.#$.querySelector(".tbw-grid-content")??this.#$.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.#be.isInitialized){ft(this.#$,this.#me),pt(this.#$,this.#m?.shell,this.#me);const e=this.#m?.shell?.toolPanel?.defaultOpen;e&&this.#me.toolPanels.has(e)&&(this.openToolPanel(),this.#me.expandedSections.add(e)),this.#me.isPanelOpen&&(bt(this.#$,this.#me),wt(this.#$,this.#me,(this.#m,this.#m)),mt(this.#$,this.#me))}this._resizeController=Ke(this),this.#Ne(e),this.#Y.requestPhase(de.COLUMNS,"shellRefresh")}#je=new Map;registerStyles(e,t){let i=this.#je.get(e);i||(i=new CSSStyleSheet,this.#je.set(e,i)),i.replaceSync(t),this.#Ct()}unregisterStyles(e){this.#je.delete(e)&&this.#Ct()}getRegisteredStyles(){return Array.from(this.#je.keys())}#Ct(){const e=Array.from(this.#je.values()),t=document.adoptedStyleSheets.filter(e=>!Array.from(this.#je.values()).includes(e));document.adoptedStyleSheets=[...t,...e]}registerExternalFocusContainer(e){this.#he.registerExternalFocusContainer(e)}unregisterExternalFocusContainer(e){this.#he.unregisterExternalFocusContainer(e)}containsFocus(e){return this.#he.containsFocus(e)}#$e(){ut(this,this.#me),ht(this,this.#me),gt(this,this.#me,this.#ze())}#xt(){const e=this.#$.querySelector(".tbw-shell-header");if(!e)return;vt(this.#me);const t=function(e,t,i){const r=e?.header?.title??t.lightDomTitle??"",n=!!r;let o="";void 0!==i&&(o="string"==typeof i?F(i):i.outerHTML);const 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,u=t.toolPanels.size>0,h=c&&u,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(h&&(p+='<div class="tbw-toolbar-separator"></div>'),u){const e=t.isPanelOpen;p+=`<button class="${e?"tbw-toolbar-btn active":"tbw-toolbar-btn"}" data-panel-toggle data-icon="tool-panel" 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.#m.shell,this.#me,this.#m.icons?.toolPanel),i=document.createElement("div");i.innerHTML=t;const r=i.firstElementChild;r&&(e.replaceWith(r),this.#vt(),pt(this.#$,this.#m?.shell,this.#me))}#Ke(){const e=()=>{const e=this.#me.lightDomTitle,t=this.#me.hasToolButtonsContainer;this.#$e();const i=this.#me.lightDomTitle,r=this.#me.hasToolButtonsContainer;(i&&!e||r&&!t)&&(this.#K.markSourcesChanged(),this.#K.merge(),this.#xt())},t=()=>{this.__lightDomColumnsCache=void 0,this.#Ue()};this.#K.registerLightDomHandler("tbw-grid-header",e),this.#K.registerLightDomHandler("tbw-grid-tool-buttons",e),this.#K.registerLightDomHandler("tbw-grid-tool-panel",e),this.#K.registerLightDomHandler("tbw-grid-column",t),this.#K.registerLightDomHandler("tbw-grid-detail",t),this.#K.observeLightDOM(this)}refreshColumns(){this.__lightDomColumnsCache=void 0,ke(this),this.#K.parseLightDomColumns(this);const e=this.#me.lightDomTitle,t=this.#me.hasToolButtonsContainer;this.#$e();const i=this.#me.lightDomTitle,r=this.#me.hasToolButtonsContainer;(i&&!e||r&&!t)&&(this.#K.markSourcesChanged(),this.#K.merge(),this.#xt()),this.#Y.requestPhase(de.COLUMNS,"refreshColumns")}#et(){this.#ue.updateCachedGeometry()}refreshVirtualWindow(e=!1,t=!1){return this.#ue.refreshVirtualWindow(e,t)}invalidateRowHeight(e,t){this.#ue.invalidateRowHeight(e,t)}#Be(){this.#$e(),this.#K.markSourcesChanged(),this.#K.merge();const e=this.#m?.shell;Ct(this.#$,e,{isPanelOpen:this.#me.isPanelOpen,expandedSections:this.#me.expandedSections},this.#m?.icons)&&(this.#vt(),this.#be.setInitialized(!0))}#vt(){!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.#$,this.#m,this.#me,{onPanelToggle:()=>this.toggleToolPanel(),onSectionToggle:e=>this.toggleToolPanelSection(e)}),this.#ve?.(),this.#ve=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 u=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`},h=()=>{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",u),document.removeEventListener("mouseup",h)},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",u),document.addEventListener("mouseup",h)};return n.addEventListener("mousedown",g),()=>{n.removeEventListener("mousedown",g),document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",h)}}(this.#$,this.#m?.shell,e=>{this.style.setProperty("--tbw-tool-panel-width",`${e}px`)}),this.#ye?.(),this.#ye=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.#m?.shell,this.#me,()=>this.closeToolPanel())}}customElements.get(Wt.tagName)||customElements.define(Wt.tagName,Wt),globalThis.DataGridElement=Wt;function Kt(e,t,i=!0){let r=e;if(i&&(r=r.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.utility)),t?.length){const e=new Set(t);r=r.filter(t=>e.has(t.field))}return r}function Vt(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}function jt(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 Ut(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 Yt(e){if(null==e)return 100;if("number"==typeof e)return e;const t=parseFloat(e);return isNaN(t)?100:t}function Xt(e){return e.map(e=>Yt(e.width))}function Zt(e){const t=[];let i=0;for(const r of e)t.push(i),i+=Yt(r.width);return t}function Qt(e){return e.reduce((e,t)=>e+Yt(t.width),0)}function Jt(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 ei="@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 ti(e,t){return("function"==typeof e?e(t):e).filter(e=>!0!==e.hidden&&("function"!=typeof e.hidden||!e.hidden(t)))}function ii(e,t){return!0===e.disabled||"function"==typeof e.disabled&&e.disabled(t)}function ri(e,t,i,r){const n=document.createElement("div");n.className="tbw-context-menu",n.setAttribute("role","menu");const o=e.some(e=>!e.separator&&e.icon);for(const s of e){if(s.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",s.cssClass&&e.classList.add(s.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",s.id),e.setAttribute("tabindex","-1");const l=ii(s,t);if(l&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),s.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=F(s.icon),e.appendChild(t)}else if(o){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=s.name,e.appendChild(a),s.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(s.shortcut))s.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=s.shortcut,t.appendChild(e)}e.appendChild(t)}if(s.subMenu?.length){const n=document.createElement("span");n.className="tbw-context-menu-arrow",n.dataset.icon=z("submenuArrow"),void 0!==r&&("string"==typeof r?n.innerHTML=F(r):r instanceof HTMLElement&&n.appendChild(r.cloneNode(!0))),e.appendChild(n),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!s.subMenu)return;const n=ri(ti(s.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||!s.action||s.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),i(s)}),n.appendChild(e)}return n}const ni="getContextMenuItems";let oi=null,si=null,li=0;const ai=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:e=>{const t=e.grid;t?.query?.("clipboard:copy")}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:e=>{const t=e.grid;t?.query?.("export:csv")}}];class di extends ${static manifest={queries:[{type:ni,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:ai}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),li++}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","--tbw-icon-submenu-arrow"];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 di.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(!si&&"undefined"!=typeof document&&ei&&(si=document.createElement("style"),si.id="tbw-context-menu-styles",si.textContent=ei,document.head.appendChild(si)),!oi){oi=new AbortController;const e=oi.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(){li--,li>0||(oi&&(oi.abort(),oi=null),si&&(si.remove(),si=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(ni,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=ti(this.config.items??ai,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=ri(o,e,t=>{t.action&&t.action(e),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.grid?.gridConfig?.icons?.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,u=0;if(d){const e=d.getBoundingClientRect();c=e.left+e.width/2,u=e.bottom}const h=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:h};return this.openMenuAt(g,c,u,!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 ci(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 ui="__tbw_null__";function hi(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 ci(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?ui:"",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===ui?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 gi(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 pi{#Rt=new Map;#Et;constructor(e){this.#Et=e}setInvalid(e,t,i=""){let r=this.#Rt.get(e);r||(r=new Map,this.#Rt.set(e,r)),r.set(t,i),this.#Et(e,t,!0)}clearInvalid(e,t){const i=this.#Rt.get(e);i&&(i.delete(t),0===i.size&&this.#Rt.delete(e)),this.#Et(e,t,!1)}clearRowInvalid(e){const t=this.#Rt.get(e);if(t){const i=Array.from(t.keys());this.#Rt.delete(e),i.forEach(t=>this.#Et(e,t,!1))}}clearAllInvalid(){const e=Array.from(this.#Rt.entries());this.#Rt.clear(),e.forEach(([e,t])=>{t.forEach((t,i)=>this.#Et(e,i,!1))})}isCellInvalid(e,t){return this.#Rt.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#Rt.get(e)?.get(t)}hasInvalidCells(e){const t=this.#Rt.get(e);return!!t&&t.size>0}getInvalidFields(e){return new Map(this.#Rt.get(e)??[])}}function fi(e,t,i){const r=e.get(t);return!!r&&!wi(r,i)}function wi(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(!wi(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(!wi(i[e],r[e]))return!1;return!0}return!1}function mi(e,t,i){e.set(t,structuredClone(i))}function bi(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 vi{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 fi(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&&fi(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&&!wi(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)&&fi(this.baselines,e,t),hasBaseline:this.baselines.has(e)}}markPristine(e,t){mi(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&&mi(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&&fi(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&&fi(this.baselines,i,r)&&t.push(i)}for(const i of this.newRowIds)t.push(i);return t}revertRow(e,t){const i=bi(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&&bi(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 yi='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function Ci(e){return"string"==typeof e&&("__proto__"!==e&&"constructor"!==e&&"prototype"!==e)}function xi(e){}function Ri(e,t){return!1===e.onBeforeEditClose?.(t)}function Ei(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:u,editorValueCallbacks:h}=e;let g;try{g=a.getRowId?.(t)}catch{}const f=g?e=>a.updateRow(g,e,"cascade"):xi,w=Ci(r.field)?t[r.field]:void 0;o.classList.add("editing"),u.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=g?a._getRowEntry(g):void 0,s=o?.row??t,l=o?.index??i;e.commitCellValue(l,r,n,s)},y=()=>{if(b=!0,Ci(r.field)){const e=g?a._getRowEntry(g):void 0;(e?.row??t)[r.field]=w}},C=document.createElement("div");C.className="tbw-editor-host",o.firstElementChild&&a.__frameworkAdapter?.releaseCell?.(o),o.innerHTML="",o.appendChild(C),C.addEventListener("keydown",t=>{if(!t.defaultPrevented){if("Enter"===t.key){const e=t.target;if(e&&"true"===e.getAttribute?.("aria-expanded")&&e.hasAttribute?.("aria-controls"))return}if("Enter"===t.key){if(d){t.stopPropagation(),t.preventDefault();const e=C.querySelector("input,textarea,select");return void(e&&v(gi(e,r,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=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 i=r.getTypeDefault(t.type,e._hostElement);if(i?.editor)return i.editor}}(a,x)??hi(r),S=w,_=`${i}:${r.field}`,A=[];h.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),u=i.__compiledEditor;u?c.innerHTML=u({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(!Ci(t))return"";const i=r[t];return null==i?"":String(i)})||"")});const h=c.querySelector("input,textarea,select");if(h){h instanceof HTMLInputElement&&"checkbox"===h.type?h.checked=!!n:h.value=String(n??"");let t=!1;h.addEventListener("blur",()=>{t||o(gi(h,i,n))}),h.addEventListener("keydown",r=>{const l=r;if("Enter"===l.key){if(Ri(e.config,l))return;l.stopPropagation(),l.preventDefault(),t=!0,o(gi(h,i,n)),e.exitRowEdit(a,!1)}if("Escape"===l.key){if(Ri(e.config,l))return;l.stopPropagation(),l.preventDefault(),s(),e.exitRowEdit(a,!0)}}),h instanceof HTMLInputElement&&"checkbox"===h.type&&h.addEventListener("change",()=>o(h.checked)),l||setTimeout(()=>h.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(yi);e?.focus({preventScroll:!0})})}else if("function"==typeof E){const i=E({row:t,rowId:g??"",value:S,field:r.field,column:r,commit:v,cancel:y,updateRow:f,onValueChange:k,grid:e.grid});if("string"==typeof i)C.innerHTML=i,function(e,t,i,r){const n=e.querySelector("input,textarea,select");n&&(n.addEventListener("blur",()=>{i(gi(n,t,r))}),n instanceof HTMLInputElement&&"checkbox"===n.type?n.addEventListener("change",()=>i(n.checked)):n instanceof HTMLSelectElement&&n.addEventListener("change",()=>i(gi(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(i instanceof Node){C.appendChild(i);i instanceof HTMLInputElement||i instanceof HTMLSelectElement||i instanceof HTMLTextAreaElement?k(e=>{i instanceof HTMLInputElement&&"checkbox"===i.type?i.checked=!!e:i.value=String(e??"")}):o.setAttribute("data-editor-managed","")}else!i&&C.hasChildNodes()&&o.setAttribute("data-editor-managed","");s||queueMicrotask(()=>{const e=C.querySelector(yi);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:g??"",value:S,field:r.field,column:r,commit:v,cancel:y,updateRow:f,onValueChange:k,grid:e.grid};if(E.mount)try{E.mount({placeholder:i,context:n,spec:E})}catch(T){p("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 _i(e,t,i,r={}){const n=r.delimiter??",",o=r.newline??"\n",s=r.quoteStrings??!0,l=[],a=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)});l.push(e.join(n))}for(const d of e){const e=t.map(e=>{let t=W(d,e);return i.processCell&&(t=i.processCell(t,e.field,d)),Si(t,s)});l.push(e.join(n))}return a+l.join(o)}function Ai(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 ki(e){return JSON.stringify(Ti(e))}function Ti(e){if(null==e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Ti);const t={};for(const i of Object.keys(e).sort())t[i]=Ti(e[i]);return t}class Ii{#St=new Map;#_t=0;register(e){const t=ki(e),i=this.#St.get(t);if(i)return i.id;this.#_t++;const r=`s${this.#_t}`;return this.#St.set(t,{id:r,style:e}),r}getStyleId(e){return this.#St.get(ki(e))?.id}get size(){return this.#St.size}toXml(){if(0===this.#St.size)return"";let e="\n<Styles>";for(const{id:t,style:i}of this.#St.values())e+=Mi(t,i);return e+="\n</Styles>",e}}function Mi(e,t){let i=`\n<Style ss:ID="${e}">`;if(t.font&&(i+="<Font",t.font.name&&(i+=` ss:FontName="${t.font.name}"`),t.font.size&&(i+=` ss:Size="${t.font.size}"`),t.font.bold&&(i+=' ss:Bold="1"'),t.font.italic&&(i+=' ss:Italic="1"'),t.font.color&&(i+=` ss:Color="${t.font.color}"`),i+="/>"),t.fill){const e=t.fill.pattern??"Solid";i+=`<Interior ss:Color="${t.fill.color}" ss:Pattern="${e}"/>`}return t.numberFormat&&(i+=`<NumberFormat ss:Format="${t.numberFormat}"/>`),t.alignment&&(i+="<Alignment",t.alignment.horizontal&&(i+=` ss:Horizontal="${t.alignment.horizontal}"`),t.alignment.vertical&&(i+=` ss:Vertical="${t.alignment.vertical}"`),t.alignment.wrapText&&(i+=' ss:WrapText="1"'),i+="/>"),t.borders&&(i+="<Borders>",t.borders.top&&(i+=Li("Top",t.borders.top)),t.borders.bottom&&(i+=Li("Bottom",t.borders.bottom)),t.borders.left&&(i+=Li("Left",t.borders.left)),t.borders.right&&(i+=Li("Right",t.borders.right)),i+="</Borders>"),i+="</Style>",i}function Li(e,t){let i=`<Border ss:Position="${e}" ss:LineStyle="Continuous" ss:Weight="${function(e){switch(e){case"Thin":return 1;case"Medium":return 2;case"Thick":return 3}}(t.style)}"`;return t.color&&(i+=` ss:Color="${t.color}"`),i+="/>",i}function Pi(e,t,i,r,n){if(t.cellStyle){const o=t.cellStyle(i,r,n);if(o)return e.register(o)}const o=t.columnStyles?.[r];return o?e.getStyleId(o):t.defaultStyle?e.getStyleId(t.defaultStyle):void 0}function Di(e,t){const i=Math.min(t.length,50);let r=(e.header??e.field).length;for(let n=0;n<i;n++){const i=t[n][e.field],o=null==i?0:String(i).length;o>r&&(r=o)}return r+2}function Fi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Hi(e,t,i){const r=i.excelStyles,n=r?function(e){const t=new Ii;if(e.headerStyle&&t.register(e.headerStyle),e.defaultStyle&&t.register(e.defaultStyle),e.columnStyles)for(const i of Object.values(e.columnStyles))t.register(i);return t}(r):void 0;let o='<?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">';if(n){if(r.cellStyle)for(const i of e)for(const e of t){const t=W(i,e),o=r.cellStyle(t,e.field,i);o&&n.register(o)}o+=n.toXml()}o+='\n<Worksheet ss:Name="Sheet1">\n<Table>',r&&(o+=function(e,t,i){const r=i.columnWidths,n=i.autoFitColumns;if(!r&&!n)return"";let o="";for(const s of e){let e=r?.[s.field];null==e&&n&&(e=Di(s,t)),o+=null!=e?`\n<Column ss:Width="${7*e}"/>`:"\n<Column/>"}return o}(t,e,r));const s=r?.headerStyle&&n?n.getStyleId(r.headerStyle):void 0;if(!1!==i.includeHeaders){o+="\n<Row>";for(const e of t){const t=e.header||e.field;o+=`<Cell${s?` ss:StyleID="${s}"`:""}><Data ss:Type="String">${Fi(i.processHeader?i.processHeader(t,e.field):t)}</Data></Cell>`}o+="</Row>"}for(const l of e){o+="\n<Row>";for(const e of t){let t=W(l,e);i.processCell&&(t=i.processCell(t,e.field,l));let s="String",a="";null==t?a="":"number"!=typeof t||isNaN(t)?t instanceof Date?(s="DateTime",a=t.toISOString()):a=Fi(String(t)):(s="Number",a=String(t));const d=n&&r?Pi(n,r,t,e.field,l):void 0;o+=`<Cell${d?` ss:StyleID="${d}"`:""}><Data ss:Type="${s}">${a}</Data></Cell>`}o+="</Row>"}return o+="\n</Table>\n</Worksheet>\n</Workbook>",o}const Gi="(Blank)";function Oi(e){if("number"==typeof e)return e;if(e instanceof Date)return e.getTime();const t=Number(e);if(!isNaN(t))return t;return new Date(e).getTime()}function Ni(e,t,i=!1,r){if(!t.length)return e;const n=t.map(e=>function(e,t,i){const r=e.field,n=e.operator,o=i?e=>i(e[r],e):e=>e[r];if("blank"===n)return e=>{const t=o(e);return null==t||""===t||"number"==typeof t&&isNaN(t)};if("notBlank"===n)return e=>{const t=o(e);return null!=t&&""!==t&&!("number"==typeof t&&isNaN(t))};if(i&&("notIn"===n||"in"===n)){const t=e.value;if("notIn"===n){if(!Array.isArray(t))return()=>!0;const e=new Set(t);return t=>{const n=i(t[r],t),o=Array.isArray(n)?n:null!=n?[n]:[];return 0===o.length?!e.has(Gi):!o.some(t=>e.has(t))}}if(!Array.isArray(t))return()=>!1;const o=new Set(t);return e=>{const t=i(e[r],e),n=Array.isArray(t)?t:null!=t?[t]:[];return 0===n.length?o.has(Gi):n.some(e=>o.has(e))}}if("notIn"===n){if(!Array.isArray(e.value))return()=>!0;const t=new Set(e.value);return e=>{const i=e[r];return null==i||""===i?!t.has(Gi):!t.has(i)}}if("in"===n){if(!Array.isArray(e.value))return()=>!1;const t=new Set(e.value);return e=>{const i=e[r];return null==i||""===i?t.has(Gi):t.has(i)}}const s="number"===e.type&&!i,l=e=>null==e||""===e||"number"==typeof e&&isNaN(e);if("greaterThan"===n){const t=Oi(e.value);return s?e=>{const i=e[r];return!l(i)&&i>t}:e=>{const i=o(e);if(l(i))return!1;const r=Oi(i);return!isNaN(r)&&r>t}}if("greaterThanOrEqual"===n){const t=Oi(e.value);return s?e=>{const i=e[r];return!l(i)&&i>=t}:e=>{const i=o(e);if(l(i))return!1;const r=Oi(i);return!isNaN(r)&&r>=t}}if("lessThan"===n){const t=Oi(e.value);return s?e=>{const i=e[r];return!l(i)&&i<t}:e=>{const i=o(e);if(l(i))return!1;const r=Oi(i);return!isNaN(r)&&r<t}}if("lessThanOrEqual"===n){const t=Oi(e.value);return s?e=>{const i=e[r];return!l(i)&&i<=t}:e=>{const i=o(e);if(l(i))return!1;const r=Oi(i);return!isNaN(r)&&r<=t}}if("between"===n){const t=Oi(e.value),i=Oi(e.valueTo);return s?e=>{const n=e[r];return!l(n)&&(n>=t&&n<=i)}:e=>{const r=o(e);if(l(r))return!1;const n=Oi(r);return!isNaN(n)&&n>=t&&n<=i}}const a=t?String(e.value):String(e.value).toLowerCase();return"contains"===n?t?e=>{const t=o(e);return null!=t&&String(t).includes(a)}:e=>{const t=o(e);return null!=t&&String(t).toLowerCase().includes(a)}:"notContains"===n?t?e=>{const t=o(e);return null!=t&&!String(t).includes(a)}:e=>{const t=o(e);return null!=t&&!String(t).toLowerCase().includes(a)}:"equals"===n?t?e=>{const t=o(e);return null!=t&&String(t)===a}:e=>{const t=o(e);return null!=t&&String(t).toLowerCase()===a}:"notEquals"===n?t?e=>{const t=o(e);return null!=t&&String(t)!==a}:e=>{const t=o(e);return null!=t&&String(t).toLowerCase()!==a}:"startsWith"===n?t?e=>{const t=o(e);return null!=t&&String(t).startsWith(a)}:e=>{const t=o(e);return null!=t&&String(t).toLowerCase().startsWith(a)}:"endsWith"===n?t?e=>{const t=o(e);return null!=t&&String(t).endsWith(a)}:e=>{const t=o(e);return null!=t&&String(t).toLowerCase().endsWith(a)}:()=>!0}(e,i,r?.get(e.field)));return 1===n.length?e.filter(n[0]):e.filter(e=>{for(let t=0;t<n.length;t++)if(!n[t](e))return!1;return!0})}function qi(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(Gi),[...r].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t)))}const zi="__tbw_expander";function $i(e){return e.field===zi}function Bi(e){return!0===e.utility}function Wi(e){return e?e.toISOString().split("T")[0]:""}function Ki(e){return e?"string"==typeof e?e:"number"==typeof e?Wi(new Date(e)):"":""}function Vi(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)=>"number"==typeof e&&"number"==typeof t?e-t:d(e).localeCompare(d(t)));const c=document.createElement("div");c.className="tbw-filter-search";const u=document.createElement("input");u.type="text",u.placeholder="Search...",u.className="tbw-filter-search-input",u.value=o.get(s)??"",c.appendChild(u),e.appendChild(c);const h=document.createElement("div");h.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),h.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(h);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:"number"==typeof e&&"number"==typeof t?e-t: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(u.value),e.appendChild(b),u.addEventListener("input",()=>{clearTimeout(S),S=setTimeout(()=>{o.set(s,u.value),E(u.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 ji(e,t){if("number"==typeof e)return e;if("string"==typeof e){const i=parseFloat(e);return isNaN(i)?t:i}return t}class Ui extends ${static manifest={events:[{type:"filter-change",description:"Emitted when filter criteria change. Broadcast to both DOM consumers and plugin bus."}],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}getDataRows(){const e=this.sourceRows;if(e.length>0)return e;const t=this.rows;return 0===t.length?t:t.filter(e=>null!=e&&!0!==e.__loading)}getFilterValues(){const e=this.grid.effectiveConfig?.columns;if(!e)return;let t;for(const i of e)if(i.field)if(i.filterValue)t||(t=new Map),t.set(i.field,i.filterValue);else if(i.valueAccessor){t||(t=new Map);const e=i;t.set(i.field,(t,i)=>W(i,e))}return t}filters=new Map;cachedResult=null;cacheKey=null;cachedInputSpot=null;openPanelField=null;panelElement=null;panelAnchorElement=null;panelButtonElement=null;searchText=new Map;excludedValues=new Map;panelAbortController=null;globalStylesInjected=!1;columnLookup=null;columnLookupRef=null;getColumnByField(e){const t=this.grid.effectiveConfig?.columns;if(!t)return;let i=this.columnLookup;if(t!==this.columnLookupRef||!i){i=new Map;for(const e of t)e.field&&i.set(e.field,e);this.columnLookup=i,this.columnLookupRef=t}return i.get(e)}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.getColumnByField(i),r=e?.filterValue??(e?.valueAccessor?(t,i)=>W(i,e):void 0);t.push({field:i,filterValue:r})}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(Gi),r.set(n,[...o].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t))));return r}(this.getDataRows(),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.getDataRows();if(!i||0===i.length)return void this.excludedValues.delete(e);const r=t.value,n=new Set(r.map(e=>null==e?Gi: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.columnLookup=null,this.columnLookupRef=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("filter:get-model"===e.type){if(!this.filters.size)return;return Object.fromEntries(this.filters)}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){if(!this.filters.size)return e;const t=[...this.filters.values()];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;if(!o)for(const[l,a]of this.filters)"set"===a.type&&"in"===a.operator&&this.syncExcludedValues(l,a);const s=Ni(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(Bi(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");return o.classList.toggle("active",n),e.classList.toggle("filtered",n),n?e.setAttribute("aria-description","Filtered"):e.removeAttribute("aria-description"),void(t!==n&&this.setIcon(o,n?"filterActive":"filter"))}o=document.createElement("button"),o.className="tbw-filter-btn",o.setAttribute("aria-label",`Filter ${i.header??r}`),this.setIcon(o,n?"filterActive":"filter"),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 s=e.querySelector(".resize-handle");s?e.insertBefore(o,s):e.appendChild(o)})}setFilter(e,t,i){if(null===t)this.filters.delete(e),this.syncExcludedValues(e,null);else{const i={...t,field:e};this.filters.set(e,i),this.syncExcludedValues(e,i)}if(this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,i?.silent)this.emitPluginEvent("filter-change",{filters:[...this.filters.values()]});else{this.broadcast("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.();const i=this.getColumnByField(e)?.header??e;o(this.gridElement,s(this.gridElement,null===t?"filterCleared":"filterApplied",i))}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.emitPluginEvent("filter-change",{filters:[...this.filters.values()]}):(this.broadcast("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.()),this.requestRender()}clearAllFilters(e){this.filters.clear(),this.excludedValues.clear(),this.searchText.clear(),this.applyFiltersInternal(e?.silent),e?.silent||o(this.gridElement,s(this.gridElement,"allFiltersCleared"))}clearFieldFilter(e,t){if(this.filters.delete(e),this.excludedValues.delete(e),this.searchText.delete(e),this.applyFiltersInternal(t?.silent),!t?.silent){const t=this.getColumnByField(e)?.header??e;o(this.gridElement,s(this.gridElement,"filterCleared",t))}}isFieldFiltered(e){return this.filters.has(e)}getFilteredRowCount(){return this.cachedResult?.length??this.rows.length}getActiveFilters(){return this.getFilters()}getUniqueValues(e){const t=this.getColumnByField(e),i=t?.filterValue;return qi(this.getDataRows(),e,i)}getStaleFilters(){const e=[];for(const[t,i]of this.filters){if("set"!==i.type)continue;const r=this.getUniqueValues(t);if("notIn"===i.operator&&Array.isArray(i.value)){const t=new Set(i.value);0===r.filter(e=>!t.has(e)).length&&e.push(i)}else if("in"===i.operator&&Array.isArray(i.value)){const t=new Set(i.value);0===r.filter(e=>t.has(e)).length&&e.push(i)}}return e}getBlankMode(e){const t=this.filters.get(e);return"blank"===t?.operator?"blanksOnly":"notBlank"===t?.operator?"nonBlanksOnly":"all"}toggleBlankFilter(e,t){if("all"===t){const t=this.filters.get(e);if(t?.valueTo&&"object"==typeof t.valueTo){const i=t.valueTo;this.setFilter(e,i)}else this.setFilter(e,null);return}const i=this.filters.get(e),r=i&&"blank"!==i.operator&&"notBlank"!==i.operator?{type:i.type,operator:i.operator,value:i.value,valueTo:i.valueTo}:i?.valueTo;this.setFilter(e,{type:i?.type??"text",operator:"blanksOnly"===t?"blank":"notBlank",value:"",valueTo:r})}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);right:anchor(right);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,i.classList.add("active"),this.panelButtonElement=i,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=t.filterValue??(t.valueAccessor?(e,i)=>W(i,t):void 0),o=qi(this.getDataRows(),e,n);document.body.appendChild(r),this.positionPanel(r,i),this.renderPanelContent(e,t,r,o),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?Gi: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.filterType??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,u=ji(s?.min??l?.min,d),h=ji(s?.max??l?.max,c),g=s?.step??l?.step??1,p=r.get(n);let f=u,w=h;const m="blank"===p?.operator;"between"===p?.operator?(f=ji(p.value,u),w=ji(p.valueTo,h)):"greaterThanOrEqual"===p?.operator?f=ji(p.value,u):"lessThanOrEqual"===p?.operator&&(w=ji(p.value,h));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(u),C.max=String(h),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(u),S.max=String(h),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(u),T.max=String(h),T.step=String(g),T.value=String(f);const I=document.createElement("input");I.type="range",I.className="tbw-filter-range-thumb tbw-filter-range-thumb-max",I.min=String(u),I.max=String(h),I.step=String(g),I.value=String(w),_.appendChild(A),_.appendChild(k),_.appendChild(T),_.appendChild(I),e.appendChild(_);const M=document.createElement("label");M.className="tbw-filter-blank-option";const L=document.createElement("input");L.type="checkbox",L.className="tbw-filter-blank-checkbox",L.checked=m;const P=document.createTextNode("Blank");M.appendChild(L),M.appendChild(P);const D=e=>{C.disabled=e,S.disabled=e,T.disabled=e,I.disabled=e,b.classList.toggle("tbw-filter-disabled",e),_.classList.toggle("tbw-filter-disabled",e)};D(m),L.addEventListener("change",()=>{D(L.checked)}),e.appendChild(M);const F=()=>{const e=parseFloat(T.value),t=parseFloat(I.value),i=h-u,r=(e-u)/i*100,n=(t-u)/i*100;k.style.left=`${r}%`,k.style.width=n-r+"%"};T.addEventListener("input",()=>{const e=Math.min(parseFloat(T.value),parseFloat(I.value));T.value=String(e),C.value=String(e),F()}),I.addEventListener("input",()=>{const e=Math.max(parseFloat(I.value),parseFloat(T.value));I.value=String(e),S.value=String(e),F()}),C.addEventListener("input",()=>{const e=parseFloat(C.value);let t=Number.isFinite(e)?e:u;t=Math.max(u,Math.min(t,parseFloat(S.value))),T.value=String(t),F()}),S.addEventListener("input",()=>{const e=parseFloat(S.value);let t=Number.isFinite(e)?e:h;t=Math.min(h,Math.max(t,parseFloat(C.value))),I.value=String(t),F()}),F();const H=document.createElement("div");H.className="tbw-filter-buttons";const G=document.createElement("button");G.className="tbw-filter-apply-btn",G.textContent="Apply",G.addEventListener("click",()=>{if(L.checked)return void t.applyTextFilter("blank","");const e=parseFloat(C.value),i=parseFloat(S.value),r=Number.isFinite(e)?e:u,n=Number.isFinite(i)?i:h;r!==u||n!==h?t.applyTextFilter("between",r,n):t.clearFilter()}),H.appendChild(G);const O=document.createElement("button");O.className="tbw-filter-clear-btn",O.textContent="Clear Filter",O.addEventListener("click",()=>{t.clearFilter()}),H.appendChild(O),e.appendChild(H)}(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,u=Ki(s?.min)||Ki(l?.min)||Wi(d),h=Ki(s?.max)||Ki(l?.max)||Wi(c),g=r.get(n);let p="",f="";const w="blank"===g?.operator;"between"===g?.operator?(p=Ki(g.value)||"",f=Ki(g.valueTo)||""):"greaterThanOrEqual"===g?.operator?p=Ki(g.value)||"":"lessThanOrEqual"===g?.operator&&(f=Ki(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",u&&(y.min=u),h&&(y.max=h),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",u&&(E.min=u),h&&(E.max=h),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 I=document.createElement("button");I.className="tbw-filter-apply-btn",I.textContent="Apply",I.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(I);const M=document.createElement("button");M.className="tbw-filter-clear-btn",M.textContent="Clear Filter",M.addEventListener("click",()=>{t.clearFilter()}),T.appendChild(M),e.appendChild(T)}(i,l,r,this.filters):Vi(i,l,r,o,{caseSensitive:this.config.caseSensitive,debounceMs:this.config.debounceMs},this.searchText)}}setupPanelCloseHandler(e,t){this.panelAbortController=new AbortController;const{signal:i}=this.panelAbortController;setTimeout(()=>{i.aborted||document.addEventListener("click",i=>{e.contains(i.target)||i.target===t||this.closeFilterPanel()},{signal:i})},0)}closeFilterPanel(){const e=this.panelElement;if(e&&(e.remove(),this.panelElement=null),this.panelAnchorElement&&(this.panelAnchorElement.style.anchorName="",this.panelAnchorElement=null),this.panelButtonElement){const e=this.openPanelField;e&&this.filters.has(e)||this.panelButtonElement.classList.remove("active"),this.panelButtonElement=null}this.openPanelField=null,this.panelAbortController?.abort(),this.panelAbortController=null}static supportsAnchorPositioning=null;static checkAnchorPositioningSupport(){return null===Ui.supportsAnchorPositioning&&(Ui.supportsAnchorPositioning=CSS.supports("anchor-name","--test")),Ui.supportsAnchorPositioning}positionPanel(e,t){const i=t.closest(".header-row")??t;if(i.style.anchorName="--tbw-filter-anchor",this.panelAnchorElement=i,Ui.checkAnchorPositioningSupport()){i.style.anchorName="",t.style.anchorName="--tbw-filter-anchor",this.panelAnchorElement=t;const r=i.getBoundingClientRect().bottom-t.getBoundingClientRect().bottom;return e.style.marginTop=`${r+4}px`,void requestAnimationFrame(()=>{const i=e.getBoundingClientRect(),r=t.getBoundingClientRect();i.top<r.top&&e.classList.add("tbw-filter-panel-above")})}const r=i.getBoundingClientRect(),n=t.getBoundingClientRect();e.style.position="fixed",e.style.top=`${r.bottom+4}px`,e.style.left=`${n.right}px`,requestAnimationFrame(()=>{const t=e.getBoundingClientRect();e.style.left=n.right-t.width+"px";n.right-t.width<8&&(e.style.left=`${n.left}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){const n=this.getColumnByField(e),o=n?.filterType??n?.type??"text";this.filters.set(e,{field:e,type:o,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.emitPluginEvent("filter-change",{filters:t}):(this.broadcast("filter-change",{filters:t,filteredRowCount:i.length,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.()),this.requestRender()};return void(i&&"function"==typeof i.then?i.then(r):r(i))}e?this.emitPluginEvent("filter-change",{filters:t}):(this.broadcast("filter-change",{filters:t,filteredRowCount:0,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.()),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 Yi(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,u=t[t.length-1];u&&!u.implicit&&u.id===a?u.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){const t=function(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}(e),i=function(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}(e,t);return{merged:i,embedded:t}}function Zi(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 Qi(e,t,i){return i?.valueAccessor?W(e,i):e?.[t]}function Ji(e){return null==e||""===e||"number"==typeof e&&isNaN(e)}const er={sum:(e,t,i)=>{let r=0;for(let n=0;n<e.length;n++){const o=Qi(e[n],t,i);if(Ji(o))continue;const s=Number(o);isNaN(s)||(r+=s)}return r},avg:(e,t,i)=>{if(!e.length)return 0;let r=0,n=0;for(let o=0;o<e.length;o++){const s=Qi(e[o],t,i);if(Ji(s))continue;const l=Number(s);isNaN(l)||(r+=l,n++)}return n>0?r/n:0},count:e=>e.length,min:(e,t,i)=>{if(!e.length)return 0;let r=1/0;for(let n=0;n<e.length;n++){const o=Qi(e[n],t,i);if(Ji(o))continue;const s=Number(o);isNaN(s)||s<r&&(r=s)}return r===1/0?0:r},max:(e,t,i)=>{if(!e.length)return 0;let r=-1/0;for(let n=0;n<e.length;n++){const o=Qi(e[n],t,i);if(Ji(o))continue;const s=Number(o);isNaN(s)||s>r&&(r=s)}return r===-1/0?0:r},first:(e,t,i)=>e[0]?Qi(e[0],t,i):void 0,last:(e,t,i)=>e.length?Qi(e[e.length-1],t,i):void 0},tr=new Map,ir={register(e,t){tr.set(e,t)},unregister(e){tr.delete(e)},get(e){if(void 0!==e)return"function"==typeof e?e:tr.get(e)??er[e]},run(e,t,i,r){const n=this.get(e);return n?n(t,i,r):void 0},has:e=>tr.has(e)||e in er,list:()=>[...Object.keys(er),...tr.keys()]},rr={sum:e=>{let t=0;for(let i=0;i<e.length;i++)t+=e[i];return t},avg:e=>{if(!e.length)return 0;let t=0;for(let i=0;i<e.length;i++)t+=e[i];return t/e.length},count:e=>e.length,min:e=>{if(!e.length)return 0;let t=e[0];for(let i=1;i<e.length;i++)e[i]<t&&(t=e[i]);return t},max:e=>{if(!e.length)return 0;let t=e[0];for(let i=1;i<e.length;i++)e[i]>t&&(t=e[i]);return t},first:e=>e[0]??0,last:e=>e[e.length-1]??0};function nr({rows:e,config:t,expanded:i,initialExpanded:r,groupSortDirections:n}){const o=t.groupOn;if("function"!=typeof o)return[];const s={key:"__root__",value:null,depth:-1,rows:[],children:new Map};if(e.forEach(e=>{let t=o(e);null==t||!1===t?t=["__ungrouped__"]:Array.isArray(t)||(t=[t]);let i=s;t.forEach((t,r)=>{const n=null==t?"∅":String(t),o="__root__"===i.key?n:i.key+"||"+n;let s=i.children.get(n);s||(s={key:o,value:t,depth:r,rows:[],children:new Map,parent:i},i.children.set(n,s)),s.rows.push(e),i=s})}),1===s.children.size&&s.children.has("__ungrouped__")){if(s.children.get("__ungrouped__").rows.length===e.length)return[]}const l=new Map;for(let h=0;h<e.length;h++)l.set(e[h],h);const a=new Set([...i,...r??[]]),d=e=>{const t=[...e.children.values()],i=e===s?0:e.depth+1,r=n?.get(i)??1;return t.sort((e,t)=>{const i=e.value,n=t.value;return null==i&&null==n?0:null==i?r:null==n?-r:i>n?r:i<n?-r:0}),t},c=[],u=e=>{if(e===s){for(const t of d(e))u(t);return}const t=a.has(e.key);if(c.push({kind:"group",key:e.key,value:e.value,depth:e.depth,rows:e.rows,expanded:t}),t)if(e.children.size)for(const i of d(e))u(i);else e.rows.forEach(e=>c.push({kind:"data",row:e,rowIndex:l.get(e)??-1}))};return u(s),c}function or(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}function sr({groups:e,expanded:t,groupRows:i,loadingGroups:r,parentPath:n=[]}){const o=[],s=n.length;for(const l of e){const e=[...n,l.key],a=t.has(l.key),d=i.get(l.key)??[],c=r.has(l.key);if(o.push({kind:"group",key:l.key,value:l.value,depth:s,rows:d,expanded:a}),a)if(l.children?.length){const n=sr({groups:l.children,expanded:t,groupRows:i,loadingGroups:r,parentPath:e});o.push(...n)}else c?o.push({kind:"data",row:{__loading:!0,__groupKey:l.key},rowIndex:-1}):d.forEach((e,t)=>{o.push({kind:"data",row:e,rowIndex:t})})}return o}function lr(e,t,i=[]){for(const r of e){const e=[...i,r.key];if(r.key===t)return e;if(r.children?.length){const i=lr(r.children,t,e);if(i.length>0)return i}}return[]}function ar(e,t){return e.has(t)?e.delete(t):e.add(t),e}function dr(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 cr extends ${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}}}";static dependencies=[{name:"serverSide",required:!1,reason:"Fetches detail data via datasource:fetch-children on expand"}];get#At(){return this.grid}get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,animation:"slide"}}attach(e){super.attach(e),this.parseLightDomDetail(),this.on("datasource:children",e=>{const t=e;if("master-detail"!==t.context?.source)return;t.claimed=!0;const i=t.context.row;if(i&&this.expandedRows.has(i)){this.detailDataMap.set(i,t.rows),this.loadingDetails.delete(i);const e=this.detailElements.get(i);e&&(e.remove(),this.detailElements.delete(i),this.measuredDetailHeights.delete(i)),this.requestRender()}})}parseLightDomDetail(){const e=this.gridElement;if(!e)return;const t=e.querySelector("tbw-grid-detail");if(!t)return;const i=this.#At.__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)=>F(G(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.#kt(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)}#kt(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;loadingDetails=new Set;detailDataMap=new Map;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:cr.DEFAULT_DETAIL_HEIGHT}toggleAndEmit(e,t){if(e?.__isGroupRow)return;this.expandedRows=ar(this.expandedRows,e);const i=this.expandedRows.has(e);if(i){if(this.rowsToAnimate.add(e),!this.detailDataMap.has(e)){const i=this.grid?.query?.("datasource:is-active",null);i&&(this.loadingDetails.add(e),this.grid.query("datasource:fetch-children",{context:{source:"master-detail",row:e,rowIndex:t}}))}}else this.loadingDetails.delete(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(),this.loadingDetails.clear(),this.detailDataMap.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($i)}(t);if(i)return t;const r=(n=this.name,{field:zi,header:"",width:32,resizable:!1,sortable:!1,filterable:!1,lockPosition:!0,utility:!0,meta:{expanderColumn:!0,expanderPlugin:n}});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,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.#Tt())}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusCol,i=this.grid._focusRow,r=this.visibleColumns[t];if(!r||!$i(r))return;const n=this.rows[i];return n?(e.preventDefault(),this.toggleAndEmit(n,i),this.requestRenderWithFocus(),!0):void 0}afterRender(){this.#It(),this.#Tt()}#It(){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.#Tt()}#Tt(){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.#At.__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=dr(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.#kt(i,e,d)})}}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){return e.add(t),e}(this.expandedRows,t),this.requestRender())}collapse(e){const t=this.rows[e];t&&(this.expandedRows=function(e,t){return e.delete(t),e}(this.expandedRows,t),this.requestRender())}toggle(e){const t=this.rows[e];t&&!t.__isGroupRow&&(this.expandedRows=ar(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}getDetailData(e){const t=this.rows[e];return t?this.detailDataMap.get(t):void 0}isDetailLoading(e){const t=this.rows[e];return!!t&&this.loadingDetails.has(t)}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.#At;"function"==typeof e.refreshColumns?e.refreshColumns():this.requestRender()}}}function ur(e,t){const i=!0===e?.__loading;return i===(!0===t?.__loading)?0:i?1:-1}function hr(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 gr(e,t){const i=e.findIndex(e=>e.field===t);return i>=0?i+1:void 0}function pr(e,t){return e.find(e=>e.field===t)?.direction}function fr(e){return e.pinned??e.meta?.pinned}function wr(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 mr(e,t){const i=fr(e);return!!i&&"left"===wr(i,t)}function br(e,t){const i=fr(e);return!!i&&"right"===wr(i,t)}function vr(e){for(let t=0;t<e.length;t++)if(null!=e[t].pinned||null!=e[t].meta?.pinned)return!0;return!1}function yr(e,t){const i={groupEndAdjustments:{addGroupEnd:new Set,removeGroupEnd:new Set},leftOffsets:new Map,rightOffsets:new Map,splitGroups:[]},r=Array.from(e.querySelectorAll(".header-row .cell"));if(!r.length)return i;const n=me(e),o=new Map,s=new Map;let l=0;for(const u of t)if(mr(u,n)){const t=r.find(e=>e.getAttribute("data-field")===u.field);t&&(o.set(u.field,l),t.classList.add(R.STICKY_LEFT),t.style.position="sticky",t.style.left=l+"px",e.querySelectorAll(`.data-grid-row .cell[data-field="${u.field}"]`).forEach(e=>{e.classList.add(R.STICKY_LEFT),e.style.position="sticky",e.style.left=l+"px"}),l+=t.offsetWidth)}let a=0;for(const u of[...t].reverse())if(br(u,n)){const t=r.find(e=>e.getAttribute("data-field")===u.field);t&&(s.set(u.field,a),t.classList.add(R.STICKY_RIGHT),t.style.position="sticky",t.style.right=a+"px",e.querySelectorAll(`.data-grid-row .cell[data-field="${u.field}"]`).forEach(e=>{e.classList.add(R.STICKY_RIGHT),e.style.position="sticky",e.style.right=a+"px"}),a+=t.offsetWidth)}const d=[],c=function(e,t,i,r,n){const o={addGroupEnd:new Set,removeGroupEnd:new Set},s=Array.from(e.querySelectorAll(".header-group-row .header-group-cell"));if(!s.length)return o;for(const l of s){const e=l.style.gridColumn;if(!e)continue;const s=e.match(/^(\d+)\s*\/\s*span\s+(\d+)$/);if(!s)continue;const a=parseInt(s[1],10)-1,d=a+parseInt(s[2],10)-1,c=t.slice(a,d+1);if(!c.length)continue;const u=c.every(e=>mr(e,r)),h=c.every(e=>br(e,r));if(u){const e=c[0].field,t=i.find(t=>t.getAttribute("data-field")===e);t&&(l.classList.add(R.STICKY_LEFT),l.style.position="sticky",l.style.left=t.style.left)}else if(h){const e=c[c.length-1].field,t=i.find(t=>t.getAttribute("data-field")===e);t&&(l.classList.add(R.STICKY_RIGHT),l.style.position="sticky",l.style.right=t.style.right)}else if(l.classList.contains("implicit-group"))xr(l,c,a,i,r,o);else{const e=c.some(e=>mr(e,r)),t=c.some(e=>br(e,r));(e||t)&&Rr(l,c,a,i,r,o,n)}}return o}(e,t,r,n,d);if(c.addGroupEnd.size>0||c.removeGroupEnd.size>0){for(const t of c.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 c.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{groupEndAdjustments:c,leftOffsets:o,rightOffsets:s,splitGroups:d}}function Cr(e,t){return mr(e,t)?"left":br(e,t)?"right":"none"}function xr(e,t,i,r,n,o){const s=[];for(let d=0;d<t.length;d++){const e=Cr(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(R.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(R.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 Rr(e,t,i,r,n,o,s){const l=[];for(let y=0;y<t.length;y++){const e=Cr(t[y],n),r=l[l.length-1];r&&r.state===e?r.cols.push(t[y]):l.push({state:e,cols:[t[y]],colStart:i+y})}if(l.length<=1)return;const a=e.parentElement;if(!a)return;const d=e.textContent||"",c=e.getAttribute("data-group")||"",u=e.nextSibling;a.removeChild(e);const h=l.findIndex(e=>"left"===e.state);let g=-1;for(let y=l.length-1;y>=0;y--)if("right"===l[y].state){g=y;break}const p=h>=0?h:g,f=h>=0&&h+1<l.length?h+1:g>=0&&g-1>=0?g-1:-1;let w,m,b,v="";for(let y=0;y<l.length;y++){const t=l[y],i=document.createElement("div");if(i.className=e.className,i.setAttribute("data-group",c),i.style.gridColumn=`${t.colStart+1} / span ${t.cols.length}`,"left"===t.state){const e=t.cols[0].field,n=r.find(t=>t.getAttribute("data-field")===e);n&&(i.classList.add(R.STICKY_LEFT),i.style.position="sticky",i.style.left=n.style.left,n.style.left),y===p&&(i.style.borderRightStyle="none",w=i,v=t.cols[t.cols.length-1].field)}else if("right"===t.state){const e=t.cols[t.cols.length-1].field,n=r.find(t=>t.getAttribute("data-field")===e);n&&(i.classList.add(R.STICKY_RIGHT),i.style.position="sticky",i.style.right=n.style.right),y===p&&(i.style.borderLeftStyle="none",w=i,v=t.cols[0].field)}if(y===f){i.style.overflow="visible";const e=document.createElement("span");e.textContent=d,e.style.position="relative",e.style.zIndex="36",e.style.display="block",e.style.overflow="hidden",e.style.textOverflow="ellipsis",e.style.whiteSpace="nowrap",i.appendChild(e),m=i,b=e}u?a.insertBefore(i,u):a.appendChild(i)}w&&m&&b&&v&&s.push({groupId:c,label:d,pinnedFragment:w,scrollableFragment:m,floatLabel:b,pinnedField:v,isTransferred:!1,floatOffset:0})}function Er(e){e.querySelectorAll(`.${R.STICKY_LEFT}, .${R.STICKY_RIGHT}`).forEach(e=>{e.classList.remove(R.STICKY_LEFT,R.STICKY_RIGHT),e.style.position="",e.style.left="",e.style.right=""})}const Sr="canMoveColumn";function _r(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=Lr(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 Ar(e){const t=document.createElement("div");return t.className=`tbw-aggregation-rows tbw-aggregation-rows-${e}`,t.setAttribute("role","presentation"),t}function kr(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?Tr(t,o,i,r):Ir(t,o,i,r),e.appendChild(t)}}function Tr(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}=Mr(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 Ir(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}=Mr(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 Mr(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=ir.get(o.aggFunc);e&&(r=e(i,t.field,t)),n=o.formatter}else{const e=ir.get(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 Lr(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 Pr(e,t,i,r,n){const o=i?.sourceRows,s=i?.rows,l=Array.isArray(o)?o.length:e.length,a=Array.isArray(s)?s.length:e.length,d=l>0?l:a;return{totalRows:d,filteredRows:n?.cachedResult?.length??(a<l?a:d),selectedRows:r?.selected?.size??0,columns:t,rows:e,grid:i}}function Dr(e){return"function"==typeof e?e:function(e){return rr[e]??rr.sum}(e)}function Fr(e,t){return[...e,t].join("|")}function Hr(e,t){const i=t.rowGroupFields??[],r=t.columnGroupFields??[],n=t.valueFields??[],o=function(e,t,i="asc"){if(0===t.length)return["value"];const r=new Set;for(const o of e){const e=t.map(e=>String(o[e]??"")).join("|");r.add(e)}const n=[...r].sort();return"desc"===i?n.reverse():n}(e,r,t.sortColumns),s=Gr(e,i,r,o,n,0,"");t.sortRows&&zr(s,t.sortRows,n);const 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=Fr([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 Gr(e,t,i,r,n,o,s){const l=[];if(0===t.length){const t=Or(e,i,r,n),a=Nr(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,u=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[h,g]of u){const e=s?`${s}|${h}`:h,t=Or(g,i,r,n),a=Nr(t);let u;c&&(u=Gr(g,d,i,r,n,o+1,e)),l.push({rowKey:e,rowLabel:h||"(blank)",depth:o,values:t,total:a,isGroup:c,children:u,rowCount:g.length})}return l}function Or(e,t,i,r){const n={};if(0===t.length){for(const t of r){const i=[];for(let n=0;n<e.length;n++){const r=e[n][t.field];if(null==r||""===r)continue;const o=Number(r);isNaN(o)||i.push(o)}const r=Dr(t.aggFunc);n[Fr(["value"],t.field)]=i.length>0?r(i):null}return n}const o=new Map;for(let s=0;s<e.length;s++){const i=e[s];let r=String(i[t[0]]??"");for(let e=1;e<t.length;e++)r+="|",r+=String(i[t[e]]??"");const n=o.get(r);n?n.push(i):o.set(r,[i])}for(const s of i){const e=o.get(s);if(e&&0!==e.length)for(const t of r){const i=[];for(let n=0;n<e.length;n++){const r=e[n][t.field];if(null==r||""===r)continue;const o=Number(r);isNaN(o)||i.push(o)}const r=Dr(t.aggFunc);n[Fr([s],t.field)]=i.length>0?r(i):null}else for(const t of r)n[Fr([s],t.field)]=null}return n}function Nr(e){let t=0;for(const i of Object.values(e))t+=i??0;return t}function qr(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}function zr(e,t,i){const r="desc"===t.direction?-1:1;e.sort((e,n)=>{if("value"===t.by){if(t.valueField??i[0]?.field){return((e.total??0)-(n.total??0))*r}}return e.rowLabel.localeCompare(n.rowLabel)*r});for(const n of e)n.children?.length&&zr(n.children,t,i)}function $r(e,t,i){if(0===t.length)return;const r=new Set(i.map(e=>e.field)),n=t.map(e=>"value"===e.by?e.valueField?t=>((e,t)=>{if(null!=e.values[t])return"number"==typeof e.values[t]?e.values[t]:0;if(r.has(t)){const i=`|${t}`;let r=0,n=!1;for(const t of Object.keys(e.values))t.endsWith(i)&&(r+="number"==typeof e.values[t]?e.values[t]:0,n=!0);if(n)return r}return e.total??0})(t,e.valueField):e=>e.total??0:null);e.sort((e,i)=>{for(let r=0;r<t.length;r++){const o=t[r],s="desc"===o.direction?-1:1;let l=0;if("value"===o.by){const t=n[r];l=(t(e)-t(i))*s}else l=e.rowLabel.localeCompare(i.rowLabel)*s;if(0!==l)return l}return 0});for(const o of e)o.children?.length&&$r(o.children,t,i)}const Br=["sum","avg","count","min","max","first","last"];function Wr(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(Kr("Options",()=>function(e,t){const{config:i,callbacks:r,signal:n}=t,o=document.createElement("div");return o.className="tbw-pivot-options",o.appendChild(Yr("Enable Pivot View",e,e=>{r.onTogglePivot(e)},n)),o.appendChild(Yr("Show Row Totals",i.showTotals??!0,e=>{r.onOptionChange("showTotals",e)},n)),o.appendChild(Yr("Show Grand Total",i.showGrandTotal??!0,e=>{r.onOptionChange("showGrandTotal",e)},n)),o}(i,o))),s.appendChild(Kr("Row Groups",()=>Vr("rowGroups",o))),s.appendChild(Kr("Column Groups",()=>Vr("columnGroups",o))),s.appendChild(Kr("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",n.appendChild(e)}else for(const s of o)n.appendChild(Ur(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(Kr("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{const e=document.createElement("div");if(e.className="tbw-pivot-fields-list",l.length>=6){const t=document.createElement("input");t.type="text",t.placeholder="Filter fields…",t.className="tbw-pivot-field-search",t.addEventListener("input",()=>{const i=t.value.toLowerCase();for(const t of e.querySelectorAll(".tbw-pivot-field-chip")){const e=t;e.style.display=e.textContent?.toLowerCase().includes(i)?"":"none"}},{signal:r}),n.appendChild(t)}for(const t of l){const i=document.createElement("div");i.className="tbw-pivot-field-chip available",i.textContent=t.header,i.draggable=!0,i.title=`Drag to add "${t.field}" to a zone`,i.addEventListener("dragstart",e=>{e.dataTransfer?.setData("text/plain",t.field),i.classList.add(R.DRAGGING)},{signal:r}),i.addEventListener("dragend",()=>{i.classList.remove(R.DRAGGING)},{signal:r}),e.appendChild(i)}n.appendChild(e)}return n}(o))),e.appendChild(s),()=>{n.abort(),s.remove()}}function Kr(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 Vr(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",o.appendChild(e)}else for(const l of s)o.appendChild(jr(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"),n=t.dataTransfer?.getData("source-zone");if(!i)return;const s=o.querySelectorAll(".tbw-pivot-field-chip");let l=s.length;for(let e=0;e<s.length;e++){const i=s[e].getBoundingClientRect();if(t.clientY<i.top+i.height/2){l=e;break}}!n||n===e||"rowGroups"!==n&&"columnGroups"!==n?n===e?r.onReorderFieldInZone(i,e,l):r.onAddFieldToZone(i,e):r.onMoveFieldBetweenZones(i,n,e)},{signal:n}),o}function jr(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(R.DRAGGING)},{signal:n}),o.addEventListener("dragend",()=>{o.classList.remove(R.DRAGGING)},{signal:n}),o}function Ur(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="function"==typeof e.aggFunc,d=document.createElement("select");if(d.className="tbw-pivot-agg-select",d.title="Aggregation function",a){const e=document.createElement("option");e.value="__custom__",e.textContent="CUSTOM",e.selected=!0,d.appendChild(e),d.disabled=!0}for(const u of Br){const t=document.createElement("option");t.value=u,t.textContent=u.toUpperCase(),a||(t.selected=u===e.aggFunc),d.appendChild(t)}d.addEventListener("change",()=>{i.onUpdateValueAggFunc(e.field,d.value)},{signal:r});const c=document.createElement("button");return c.className="tbw-pivot-chip-remove",c.innerHTML="×",c.title="Remove value field",c.addEventListener("click",t=>{t.stopPropagation(),i.onRemoveValueField(e.field)},{signal:r}),s.appendChild(l),s.appendChild(d),n.appendChild(s),n.appendChild(c),n}function Yr(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}function Xr(e,t,i){return t.className="data-grid-row pivot-grand-total-row",t.innerHTML="",i.forEach((i,r)=>{const n=document.createElement("div");if(n.className="cell",n.setAttribute("data-col",String(r)),0===r){const e=document.createElement("span");e.className="pivot-label",e.textContent="Grand Total",n.appendChild(e)}else{const t=e[i.field];n.textContent=null!=t?i.format?i.format(t,e):String(t):""}t.appendChild(n)}),!0}class Zr extends ${static manifest={modifiesRowStructure:!0,hookPriority:{onHeaderClick:-10,processRows:100},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."}],queries:[{type:"sort:get-sort-config",description:"Returns the current pivot sort configuration"}]};static dependencies=[{name:"multiSort",required:!1,reason:"Queries sort model for pivot column sorting"}];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)}@media(hover:hover){.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-direction:column;gap:var(--tbw-spacing-sm, .375rem);min-height:40px}.tbw-pivot-field-search{width:100%;padding:.25rem .5rem;border:1px solid var(--tbw-color-border, #d0d5dd);border-radius:var(--tbw-radius-sm, .25rem);font-size:var(--tbw-font-size-sm, .875rem);background:var(--tbw-color-bg, #fff);color:var(--tbw-color-fg, #1a1a2e);outline:none}.tbw-pivot-field-search:focus{border-color:var(--tbw-color-primary, #3b82f6)}.tbw-pivot-fields-list{display:flex;flex-wrap:wrap;gap:var(--tbw-spacing-sm, .375rem)}.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;valueFormatters=new Map;columnTotals={};activeSortField=null;activeSortDir=null;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,this.valueFormatters.clear(),this.columnTotals={},this.activeSortField=null,this.activeSortDir=null,this.config.sortRows=void 0}getToolPanel(){if(!1!==(this.config?.showToolPanel??this.userConfig?.showToolPanel??!0))return{id:Zr.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.buildValueFormatters(),this.defaultExpanded=this.config.defaultExpanded??!0,this.pivotResult=Hr(e,this.config);const i=this.getMultiSortConfigs();if(i&&$r(this.pivotResult.rows,i,this.config.valueFields??[]),0===this.expandedKeys.size&&!this.userHasToggledExpand){const e=qr(this.pivotResult.rows);this.expandedKeys=function(e,t){if(!0===e||void 0===e)return new Set(t);if(!1===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}(this.defaultExpanded,e)}this.config.valueDisplayMode&&"raw"!==this.config.valueDisplayMode&&(this.columnTotals=function(e,t,i){const r={};return function e(n){for(const o of n)if(o.isGroup&&o.children?.length)o.children&&e(o.children);else for(const e of t)for(const t of i){const i=Fr([e],t.field);r[i]=(r[i]??0)+(o.values[i]??0)}}(e),r}(this.pivotResult.rows,this.pivotResult.columnKeys,this.config.valueFields??[]));const r=this.config.indentWidth??20,n=!0===this.defaultExpanded||void 0===this.defaultExpanded,o=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,n).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*r,__pivotTotal:e.total,...e.values}));this.keysToAnimate.clear();const s=new Set;for(const l of o){const e=l.__pivotRowKey;s.add(e),!this.previousVisibleKeys.has(e)&&l.__pivotDepth>0&&this.keysToAnimate.add(e)}return this.previousVisibleKeys=s,this.config.grandTotalInRowModel&&this.config.showGrandTotal&&this.pivotResult&&o.push({__pivotRowKey:"__grandTotal",__pivotLabel:"Grand Total",__pivotIsGrandTotal:!0,__pivotDepth:0,__pivotTotal:this.pivotResult.grandTotal,...this.pivotResult.totals}),o}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,sortable:!0});for(const r of this.pivotResult.columnKeys)for(const e of this.config.valueFields??[]){const i=Fr([r],e.field),n=e.header||this.fieldHeaderMap.get(e.field)||e.field,o="function"==typeof e.aggFunc?"custom":e.aggFunc,s=this.valueFormatters.get(e.field);t.push({field:i,header:`${r} - ${n} (${o})`,width:120,type:"number",sortable:!0,...s?{format:e=>null!=e?s(Number(e)):""}:{}})}return this.config.showTotals&&t.push({field:"__pivotTotal",header:"Total",width:100,type:"number",sortable:!0}),t}renderRow(e,t,i){const r=e;return r.__pivotIsGrandTotal?Xr(r,t,this.gridColumns):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,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?r.format?r.format(t,e):String(t):""}t.appendChild(o)}),!0}(r,t,{columns:this.gridColumns,rowIndex:i,onToggle:e=>this.toggle(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?i.format?i.format(t,e):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}handleQuery(e){if("sort:get-sort-config"===e.type){const e=this.getMultiSortConfigs();return e||(this.config.sortRows??null)}}onHeaderClick(e){if(!this.isActive)return!1;const t=e.field;if(!this.isPivotField(t))return!1;if(this.isMultiSortActive())return!1;const i=this.mapFieldToSortConfig(t);if(!i)return!1;const r=this.activeSortDir;let n;n=this.activeSortField!==t?"asc":"asc"===r?"desc":null,this.activeSortField=n?t:null,this.activeSortDir=n,this.config.sortRows=n?{...i,direction:n}:void 0,this.emit("pivot-config-change",{property:"sortRows"}),this.refresh();const l=this.gridElement;if(l){const i=e.column.header??t;o(l,n?s(l,"sortApplied",i,"asc"===n?"ascending":"descending"):s(l,"sortCleared"))}return!0}isPivotField(e){return"__pivotLabel"===e||"__pivotTotal"===e||e.includes("|")}isMultiSortActive(){const e=this.grid?.query?.("sort:get-model",null);return Array.isArray(e)&&e.length>0}getMultiSortConfigs(){const e=this.grid?.query?.("sort:get-model",null);if(!e||0===e.length)return null;const t=e[0];if(!Array.isArray(t)||0===t.length)return null;const i=[];for(const r of t){if(!this.isPivotField(r.field))continue;const e=this.mapFieldToSortConfig(r.field);e&&i.push({...e,direction:r.direction})}return i.length>0?i:null}mapFieldToSortConfig(e){return"__pivotLabel"===e?{by:"label"}:"__pivotTotal"===e?{by:"value"}:e.includes("|")?{by:"value",valueField:e}:null}afterRender(){this.isActive&&this.config.showGrandTotal&&this.pivotResult&&!this.config.grandTotalInRowModel?this.renderGrandTotalFooter():this.cleanupGrandTotalFooter(),this.isActive&&!this.isMultiSortActive()&&this.updateSortIndicators();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()}updateSortIndicators(){const e=this.gridElement;if(!e)return;const t=this.activeSortField,i=this.activeSortDir,r=t?null:this.config.sortRows,n=e.querySelectorAll(".header-row .cell[data-field]");for(const o of n){const e=o.getAttribute("data-field");if(!e||!this.isPivotField(e))continue;let n=null;t===e?n=i:r&&("label"===r.by&&"__pivotLabel"===e?n=r.direction??"asc":"value"!==r.by||"__pivotTotal"!==e||r.valueField?"value"===r.by&&r.valueField&&e===r.valueField&&(n=r.direction??"asc"):n=r.direction??"asc"),this.updateSortIndicator(o,n)}}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));Xr({__pivotRowKey:"__grandTotal",__pivotLabel:"Grand Total",__pivotIsGrandTotal:!0,__pivotTotal:this.pivotResult.grandTotal,...this.pivotResult.totals},this.grandTotalFooter,this.gridColumns),this.grandTotalFooter.setAttribute("role","presentation")}cleanupGrandTotalFooter(){this.grandTotalFooter&&(this.grandTotalFooter.remove(),this.grandTotalFooter=null)}toggle(e){this.userHasToggledExpand=!0;const t=this.expandedKeys.has(e);t?this.expandedKeys.delete(e):this.expandedKeys.add(e),this.emitToggle(e,!t),this.requestRender()}expand(e){this.userHasToggledExpand=!0,this.expandedKeys.add(e),this.emitToggle(e,!0),this.requestRender()}collapse(e){this.userHasToggledExpand=!0,this.expandedKeys.delete(e),this.emitToggle(e,!1),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=qr(this.pivotResult.rows);for(const t of e)this.expandedKeys.add(t)}isExpanded(e){return this.expandedKeys.has(e)}getExpandedGroups(){return[...this.expandedKeys]}enablePivot(){0===this.originalColumns.length&&this.captureOriginalColumns(),this.isActive=!0,this.emit("pivot-state-change",{active:!0}),this.requestRender()}disablePivot(){this.isActive=!1,this.pivotResult=null,this.emit("pivot-state-change",{active:!1}),this.requestRender()}isPivotActive(){return this.isActive}getPivotResult(){return this.pivotResult}setRowGroupFields(e){this.config.rowGroupFields=e,this.emitConfigChange("rowGroupFields"),this.refresh()}setColumnGroupFields(e){this.config.columnGroupFields=e,this.emitConfigChange("columnGroupFields"),this.refresh()}setValueFields(e){this.config.valueFields=e,this.emitConfigChange("valueFields"),this.refresh()}refresh(){this.pivotResult=null,this.requestRender()}showPanel(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(Zr.PANEL_ID)||this.grid.toggleToolPanelSection(Zr.PANEL_ID)}hidePanel(){this.grid.closeToolPanel()}togglePanel(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(Zr.PANEL_ID)}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(Zr.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),this.emitConfigChange("rowGroups"===t?"rowGroupFields":"columnGroupFields",e,t)},onRemoveFieldFromZone:(e,t)=>{this.removeFieldFromZone(e,t),this.emitConfigChange("rowGroups"===t?"rowGroupFields":"columnGroupFields",e,t)},onReorderFieldInZone:(e,t,i)=>{this.reorderFieldInZone(e,t,i),this.emitConfigChange("rowGroups"===t?"rowGroupFields":"columnGroupFields",e,t)},onMoveFieldBetweenZones:(e,t,i)=>{this.moveFieldBetweenZones(e,t,i),this.emitConfigChange("rowGroups"===i?"rowGroupFields":"columnGroupFields",e,i)},onAddValueField:(e,t)=>{this.addValueField(e,t),this.emitConfigChange("valueFields",e,"values")},onRemoveValueField:e=>{this.removeValueField(e),this.emitConfigChange("valueFields",e,"values")},onUpdateValueAggFunc:(e,t)=>{this.updateValueAggFunc(e,t),this.emitConfigChange("valueFields",e,"values")},onOptionChange:(e,t)=>{this.config[e]=t,this.emitConfigChange(e),this.isActive&&this.refresh()},getAvailableFields:()=>this.getAvailableFields()};return Wr(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()}reorderFieldInZone(e,t,i){const r="rowGroups"===t?[...this.config.rowGroupFields??[]]:[...this.config.columnGroupFields??[]],n=r.indexOf(e);-1!==n&&n!==i&&(r.splice(n,1),r.splice(i>n?i-1:i,0,e),"rowGroups"===t?this.config.rowGroupFields=r:this.config.columnGroupFields=r,this.refreshIfActive())}moveFieldBetweenZones(e,t,i){"rowGroups"===t?this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(t=>t!==e):this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(t=>t!==e),"rowGroups"===i?this.config.rowGroupFields=[...this.config.rowGroupFields??[],e]:this.config.columnGroupFields=[...this.config.columnGroupFields??[],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()}emitToggle(e,t){const i=this.rows.find(t=>t.__pivotRowKey===e);this.emit("pivot-toggle",{key:e,expanded:t,label:i?.__pivotLabel??e,depth:i?.__pivotDepth??0})}emitConfigChange(e,t,i){this.emit("pivot-config-change",{property:e,field:t,zone:i})}buildValueFormatters(){this.valueFormatters.clear();const e=this.config.valueFields??[];for(const t of e)if(t.format)this.valueFormatters.set(t.field,t.format);else{if(this.originalColumns.find(e=>e.field===t.field)){const e=(this.grid.getAllColumns?.()??this.grid.columns??[]).find(e=>e.field===t.field);if(e?.format){const i=e.format;this.valueFormatters.set(t.field,e=>i(e,{}))}}}}}const Qr="tbw-print-isolation-style";async function Jr(e,t={}){const{orientation:i="landscape"}=t,r=e.id;document.querySelectorAll(`#${CSS.escape(r)}`).length>1&&p("TBW093",`Multiple elements found with id="${r}". Print isolation may not work correctly. Ensure each grid has a unique ID.`,r,"print"),document.getElementById(Qr)?.remove();const n=function(e,t){const i=document.createElement("style");return i.id=Qr,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(Qr)?.remove(),e()};window.addEventListener("afterprint",t),window.print(),setTimeout(()=>{window.removeEventListener("afterprint",t),document.getElementById(Qr)?.remove(),e()},5e3)})}const en={button:!1,orientation:"landscape",warnThreshold:500,maxRows:0,includeTitle:!0,includeTimestamp:!0,title:"",isolate:!1};function tn(e){if(!0===e.lockPosition)return!1;if(!0===e.utility)return!1;const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}function rn(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 nn="canMoveColumn";const on=new Map;function sn(e){const t=on.get(e);if(!t)return;if(t.hasPrimitives)return;const i=[];for(const r of t.refs){const e=r.deref();if(void 0===e)return;i.push(e)}return i}function ln(e){on.delete(e)}function an(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const e=new Uint32Array(2);return crypto.getRandomValues(e),`drag-${Date.now().toString(36)}-${e[0].toString(36)}${e[1].toString(36)}`}return`drag-${Date.now().toString(36)}-${(++dn).toString(36)}`}let dn=0,cn=null;function un(){return cn}function hn(){cn=null}const gn="application/x-tbw-grid-rows+json";function pn(e){const t=e.match(/^application\/x-tbw-grid-rows\+json;zone=(.*)$/);if(!t)return null;try{return decodeURIComponent(t[1])}catch{return t[1]}}function fn(e){return JSON.stringify(e)}function wn(e,t,i,r){if(!e)return{overIndex:null,insertIndex:r,isBefore:!1};const n=i(e);if(n<0)return{overIndex:null,insertIndex:r,isBefore:!1};const o=e.getBoundingClientRect(),s=t<o.top+o.height/2;return{overIndex:n,insertIndex:s?n:n+1,isBefore:s}}const mn="__tbw_row_drag";let bn=null;const vn=new Set;function yn(){if("undefined"==typeof BroadcastChannel)return null;if(bn)return bn;try{bn=new BroadcastChannel("tbw-row-drag-drop"),bn.addEventListener("message",e=>{const t=e.data;if(t&&"tbw-row-drag-drop:transfer"===t.type)for(const i of Array.from(vn))try{i(t)}catch{}})}catch{bn=null}return bn}class Cn extends ${name="rowDragDrop";aliases=["reorderRows","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[draggable=true]{cursor:grab}.data-grid-row[draggable=true].dragging{cursor:grabbing}.tbw-row-drag-clone{position:fixed;top:-10000px;left:-10000px;pointer-events:none}.tbw-row-drag-count{position:fixed;top:-1000px;left:-1000px;pointer-events:none;background:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));color:var(--tbw-color-accent-fg);font:600 12px/1.4 system-ui,sans-serif;border-radius:999px;padding:2px 8px;box-shadow:0 2px 6px var(--tbw-color-shadow);z-index:9999}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before,.data-grid-row.drop-target.drop-after:after{content:"";position:absolute;left:0;right:0;height:var(--tbw-drop-indicator-width, 2px);background-color:var(--tbw-drop-indicator-color, var(--tbw-row-reorder-indicator, var(--tbw-color-accent)));z-index:10;pointer-events:none}.data-grid-row.drop-target.drop-before:before{top:0}.data-grid-row.drop-target.drop-after:after{bottom:0}.tbw-grid--drop-target-active{outline:2px dashed var(--tbw-drop-indicator-color, var(--tbw-color-accent));outline-offset:-2px}.tbw-grid--drop-target-rejected{outline:2px dashed var(--tbw-color-danger);outline-offset:-2px}.tbw-grid--auto-scrolling{cursor:ns-resize}.data-grid-row.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}}';static manifest={events:[{type:"row-move",description:"Intra-grid row reorder.",cancelable:!0},{type:"row-drag-start",description:"Cross-grid drag started on this grid.",cancelable:!0},{type:"row-drag-end",description:"Drag finished on this grid (regardless of outcome)."},{type:"row-drop",description:"Cross-grid drop landing on this grid.",cancelable:!0},{type:"row-transfer",description:"Cross-grid transfer completed (fires on both grids)."}]};get defaultConfig(){return{enableKeyboard:!0,dragHandlePosition:"left",dragHandleWidth:40,debounceMs:150,animation:"flip",operation:"move",autoScroll:!0,dragFrom:"handle"}}shouldRenderDragHandle(){const e=this.config.showDragHandle;return!1!==e&&(!0===e||"row"!==this.config.dragFrom)}get rowIsDraggable(){return"row"===this.config.dragFrom||"both"===this.config.dragFrom}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}isDragging=!1;draggedRowIndex=null;draggedRows=[];draggedIndices=[];dragSessionId=null;dragAccepted=!1;dropRowIndex=null;pendingMove=null;debounceTimer=null;lastFocusCol=0;autoScroller=null;gridId="";remoteTransferListener=e=>this.onRemoteTransfer(e);get internalGrid(){return this.grid}attach(e){super.attach(e);const t=this.gridElement;var i;t&&(this.gridId=t.id||`tbw-grid-${an().slice(0,8)}`,t.id||(t.id=this.gridId),this.setupDelegatedDragListeners(),i=this.remoteTransferListener,vn.add(i),yn())}detach(){this.clearDebounceTimer(),this.autoScroller?.stop(),this.autoScroller=null,function(e){if(vn.delete(e),0===vn.size&&bn){try{bn.close()}catch{}bn=null}}(this.remoteTransferListener),this.dragSessionId&&ln(this.dragSessionId),hn(),this.resetDragState(),super.detach()}processColumns(e){if(!this.shouldRenderDragHandle())return[...e];const t={field:mn,header:"",width:this.config.dragHandleWidth??40,resizable:!1,sortable:!1,filterable:!1,lockPosition:!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,"dragHandle"),e}};return"right"===this.config.dragHandlePosition?[...e,t]:[t,...e]}afterRender(){this.applyRowDraggable()}onScrollRender(){this.applyRowDraggable()}applyRowDraggable(){const e=this.internalGrid._bodyEl;if(!e)return;const t=this.rowIsDraggable,i=e.querySelectorAll(".data-grid-row");for(const r of i)t?"true"!==r.getAttribute("draggable")&&r.setAttribute("draggable","true"):r.hasAttribute("draggable")&&r.removeAttribute("draggable")}onKeyDown(e){if(!this.config.enableKeyboard)return;if(!e.ctrlKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key)return;const t=this.internalGrid,i=t._focusRow,r=t._rows??this.sourceRows;if(i<0||i>=r.length)return;const n="up"===("ArrowUp"===e.key?"up":"down")?i-1:i+1;if(n<0||n>=r.length)return;const o=r[i];return this.canMoveRow(i,n)?(this.handleKeyboardMove(o,i,n,t._focusCol),e.preventDefault(),e.stopPropagation(),!0):void 0}onCellClick(){this.flushPendingMove()}moveRow(e,t){const i=[...this.sourceRows];e<0||e>=i.length||t<0||t>=i.length||e!==t&&this.canMoveRow(e,t)&&this.executeIntraGridMove(i[e],e,t,"keyboard")}canMoveRow(e,t){const i=this.internalGrid._rows??this.sourceRows;if(e<0||e>=i.length)return!1;if(t<0||t>=i.length)return!1;if(e===t)return!1;const r=i[e],n=this.grid?.query?.("canMoveRow",r);if(Array.isArray(n)&&n.includes(!1))return!1;if(this.config.canDrag&&!this.config.canDrag(r,e))return!1;if(this.config.canMove){const i=t<e?"up":"down";if(!this.config.canMove(r,e,t,i))return!1}if(this.config.canDrop){const i={sessionId:"intra",sourceGridId:this.gridId,dropZone:this.config.dropZone??"",rows:[r],rowIndices:[e],operation:"move"};if(!this.config.canDrop(i,t))return!1}return!0}setupDelegatedDragListeners(){const e=this.gridElement;if(!e)return;const t=this.disconnectSignal;e.addEventListener("dragstart",e=>this.onDragStart(e),{signal:t}),e.addEventListener("dragend",()=>this.onDragEnd(),{signal:t}),e.addEventListener("dragover",e=>this.onDragOver(e),{signal:t}),e.addEventListener("dragleave",e=>this.onDragLeave(e),{signal:t}),e.addEventListener("drop",e=>this.onDrop(e),{signal:t})}onDragStart(e){const t=e.target;if(!t)return;const i=t.closest(".dg-row-drag-handle");let r=null,n=!1;if(i)r=i.closest(".data-grid-row"),n=!0;else if(this.rowIsDraggable){if(this.isInteractiveDragOrigin(t))return;r=t.closest(".data-grid-row")}if(!r)return;const o=this.getRowIndex(r);if(o<0)return;const{rows:s,indices:l}=this.resolveDraggedRows(o);if(0===s.length)return;if(this.config.canDrag&&!this.config.canDrag(s[0],o))return void e.preventDefault();const a=this.config.operation??"move",d=this.config.dropZone??"",c=an(),u={rows:s,indices:l,operation:a,dropZone:d};if(this.emitCancelable("row-drag-start",u))return void e.preventDefault();this.isDragging=!0,this.draggedRowIndex=o,this.draggedRows=s,this.draggedIndices=l,this.dragSessionId=c,this.dragAccepted=!1;const h=this.config.serializeRow??(e=>e),g={sessionId:c,sourceGridId:this.gridId,dropZone:d,rows:s.map(h),rowIndices:l,operation:a};if(e.dataTransfer){e.dataTransfer.effectAllowed="copy"===a?"copyMove":"move";try{e.dataTransfer.setData(gn,fn(g)),d&&e.dataTransfer.setData(`${gn};zone=${encodeURIComponent(d)}`,fn(g)),e.dataTransfer.setData("text/plain",function(e,t){const i=t.filter(e=>!e.utility&&"string"==typeof e.field&&""!==e.field),r=[];for(const n of e){const e=i.map(e=>{const t=n[e.field];return null==t?"":String(t).replace(/[\t\r\n]+/g," ")});r.push(e.join("\t"))}return r.join("\n")}(s,this.columns))}catch{}if(s.length>1){const t=document.createElement("div");t.className="tbw-row-drag-count",t.textContent=`${s.length} rows`,document.body.appendChild(t);try{e.dataTransfer.setDragImage(t,10,10)}catch{}setTimeout(()=>t.remove(),0)}else this.attachRowCloneDragImage(e,r,n?i:null)}!function(e,t,i){const r=[];let n=!1;for(const o of t)null!==o&&"object"==typeof o?r.push(new WeakRef(o)):n=!0;on.set(e,{refs:r,hasPrimitives:n,meta:i})}(c,s),function(e,t){cn={sessionId:e,payload:t}}(c,g),r.classList.add(R.DRAGGING),this.gridElement.classList.add("tbw-grid--drag-source")}static INTERACTIVE_DRAG_SELECTORS='input,textarea,select,button,a,[contenteditable=""],[contenteditable="true"],.dg-cell-editor,.tbw-checkbox-cell';isInteractiveDragOrigin(e){return null!==e.closest(Cn.INTERACTIVE_DRAG_SELECTORS)}attachRowCloneDragImage(e,t,i){if(!e.dataTransfer)return;const r=t.getBoundingClientRect(),n=t.cloneNode(!0);n.classList.add("tbw-row-drag-clone"),n.classList.remove("dragging","drop-target","drop-before","drop-after","flip-animating","row-focus"),n.removeAttribute("aria-selected"),n.style.width=`${r.width}px`,n.style.height=`${r.height}px`,this.gridElement.appendChild(n);let o=e.clientX-r.left,s=e.clientY-r.top;if(i){const e=i.getBoundingClientRect();o=e.left-r.left+e.width/2,s=e.top-r.top+e.height/2}o=Math.max(0,Math.min(r.width,o)),s=Math.max(0,Math.min(r.height,s));try{e.dataTransfer.setDragImage(n,o,s)}catch{}setTimeout(()=>n.remove(),0)}onDragOver(e){const t=e.dataTransfer;if(!t)return;const i=t.types?Array.from(t.types):[];if(!function(e){for(const t of e)if(t===gn||t.startsWith(`${gn};`))return!0;return!1}(i)&&!this.isDragging)return;const r=this.config.dropZone??"",n=un(),o=this.isDragging&&n?.payload.sourceGridId===this.gridId;if(!o){if(!r)return;const e=function(e,t){for(const i of e)if(pn(i)===t)return i;return null}(i,r);if(!(e||n&&n.payload.dropZone===r))return}e.preventDefault(),t&&(t.dropEffect=n?.payload.operation??this.config.operation??"move");const s=e.target.closest(".data-grid-row"),l=this.internalGrid._rows??[],a=wn(s,e.clientY,e=>this.getRowIndex(e),l.length);if(o&&null!==a.overIndex&&a.overIndex===this.draggedRowIndex)this.clearDropTargetClasses();else{if(n&&this.config.canDrop){const e=this.config.canDrop(n.payload,a.insertIndex);if(this.gridElement.classList.toggle("tbw-grid--drop-target-active",e),this.gridElement.classList.toggle("tbw-grid--drop-target-rejected",!e),!e)return void this.clearDropTargetClasses()}else this.gridElement.classList.add("tbw-grid--drop-target-active");this.dropRowIndex=a.insertIndex,this.applyDropPositionClasses(s,a.isBefore),!1!==this.config.autoScroll&&(this.ensureAutoScroller(),this.autoScroller?.onPointerMove(e.clientY))}}onDragLeave(e){const t=e.target.closest(".data-grid-row");t&&t.classList.remove("drop-target","drop-before","drop-after"),e.currentTarget&&!this.gridElement.contains(e.relatedTarget)&&(this.gridElement.classList.remove("tbw-grid--drop-target-active","tbw-grid--drop-target-rejected"),this.autoScroller?.stop())}onDrop(e){e.preventDefault(),this.autoScroller?.stop(),this.gridElement.classList.remove("tbw-grid--drop-target-active","tbw-grid--drop-target-rejected"),this.clearDropTargetClasses();const t=e.dataTransfer;if(!t)return;const i=un();let r=i?.payload??null,n=null;if(r){const e=sn(r.sessionId);e&&(n=e)}else{if(r=function(e){if(!e)return null;try{const t=JSON.parse(e);if("string"!=typeof t?.sessionId||"string"!=typeof t?.sourceGridId||"string"!=typeof t?.dropZone||!Array.isArray(t?.rows)||!Array.isArray(t?.rowIndices)||"move"!==t.operation&&"copy"!==t.operation)return null;for(const e of t.rowIndices)if("number"!=typeof e||!Number.isInteger(e)||e<0)return null;return t}catch{return null}}(t.getData(gn)),r){const e=sn(r.sessionId);e&&(n=e)}}if(!r)return;const o=e.target.closest(".data-grid-row"),s=this.internalGrid._rows??[],l=wn(o,e.clientY,e=>this.getRowIndex(e),s.length);let a=this.dropRowIndex??l.insertIndex;const d=r.sourceGridId===this.gridId,c=this.config.dropZone??"";if(d){const e=r.rowIndices[0];if(1===r.rowIndices.length&&a>e&&a--,e===a)return;const t=(n??r.rows)[0];if(!this.canMoveRow(e,a))return;return void this.executeIntraGridMove(t,e,a,"drag")}if(!c||c!==r.dropZone)return;if(this.config.canDrop&&!this.config.canDrop(r,a))return this.gridElement.classList.add("tbw-grid--drop-target-rejected"),void setTimeout(()=>this.gridElement.classList.remove("tbw-grid--drop-target-rejected"),200);const u=this.config.deserializeRow??(e=>e),h=n??r.rows.map(e=>u(e)),g={payload:r,sourceGridId:r.sourceGridId,targetIndex:a,operation:r.operation};if(this.emitCancelable("row-drop",g))return;const p=[...s];p.splice(a,0,...h),this.grid.rows=p;const f=this.findPeerOnGrid(r.sourceGridId);if("move"===r.operation&&f){const e=document.getElementById(r.sourceGridId);if(e){const t=(e._rows??e.rows??[]).slice(),i=[...r.rowIndices].sort((e,t)=>t-e);for(const e of i)e>=0&&e<t.length&&t.splice(e,1);e.rows=t}}f&&(f.dragAccepted=!0);const w={rows:h,fromGridId:r.sourceGridId,toGridId:this.gridId,fromIndices:r.rowIndices,toIndex:a,operation:r.operation};this.emit("row-transfer",w),f?f.emitTransfer(w):function(e){const t=yn();if(t)try{t.postMessage(e)}catch{}}({type:"tbw-row-drag-drop:transfer",sessionId:r.sessionId,sourceGridId:r.sourceGridId,toGridId:this.gridId,dropZone:c,rowIndices:r.rowIndices,toIndex:a,operation:r.operation,serializedRows:r.rows})}onRemoteTransfer(e){if(e.sourceGridId!==this.gridId)return;const t=this.config.dropZone??"";if(!t||e.dropZone!==t)return;const i=this.config.deserializeRow??(e=>e),r=e.serializedRows.map(e=>i(e));if("move"===e.operation){const t=(this.internalGrid._rows??this.sourceRows).slice(),i=[...e.rowIndices].sort((e,t)=>t-e);for(const e of i)e>=0&&e<t.length&&t.splice(e,1);this.grid.rows=t}this.dragAccepted=!0,this.emit("row-transfer",{rows:r,fromGridId:e.sourceGridId,toGridId:e.toGridId,fromIndices:e.rowIndices,toIndex:e.toIndex,operation:e.operation})}onDragEnd(){if(this.dragSessionId&&ln(this.dragSessionId),hn(),this.autoScroller?.stop(),this.gridElement.classList.remove("tbw-grid--drag-source"),this.isDragging){const e={rows:this.draggedRows,indices:this.draggedIndices,accepted:this.dragAccepted};this.emit("row-drag-end",e)}this.clearDragClasses(),this.resetDragState()}emitTransfer(e){this.emit("row-transfer",e)}findPeerOnGrid(e){const t=document.getElementById(e);return t?.getPluginByName?t.getPluginByName("rowDragDrop")??null:null}resolveDraggedRows(e){const t=this.internalGrid._rows??this.sourceRows,i=t[e],r=this.grid?.getPluginByName?.("selection");if(r?.getSelectedRowIndices){const i=r.getSelectedRowIndices();if(i.includes(e)&&i.length>1){const e=[...i].sort((e,t)=>e-t);return{rows:e.map(e=>t[e]),indices:e}}}return{rows:[i],indices:[e]}}ensureAutoScroller(){if(this.autoScroller)return;const e=this.gridElement.querySelector(".rows-viewport");if(!e)return;const t="object"==typeof this.config.autoScroll?this.config.autoScroll:void 0;this.autoScroller=function(e,t={},i){const r=t.edgeSize??60,n=t.speed??8,o=t.maxSpeed??24;let s=null,l=null,a=!1;const d=e=>{e!==a&&(a=e,i?.(e))},c=()=>{if(s=null,null===l)return void d(!1);const t=e.getBoundingClientRect();let i=0;if(l<t.top+r){const e=1-Math.max(0,l-t.top)/r;i=-Math.round(n+(o-n)*e)}else if(l>t.bottom-r){const e=1-Math.max(0,t.bottom-l)/r;i=Math.round(n+(o-n)*e)}if(0===i)return void d(!1);const a=e.scrollTop;e.scrollTop=a+i,e.scrollTop!==a?(d(!0),s=requestAnimationFrame(c)):d(!1)};return{onPointerMove(e){l=e,null===s&&(s=requestAnimationFrame(c))},stop(){null!==s&&(cancelAnimationFrame(s),s=null),l=null,d(!1)},get isScrolling(){return a}}}(e,t,e=>{this.gridElement.classList.toggle("tbw-grid--auto-scrolling",e)})}applyDropPositionClasses(e,t){this.clearDropTargetClasses(),e&&(e.classList.add("drop-target"),e.classList.toggle("drop-before",t),e.classList.toggle("drop-after",!t))}clearDropTargetClasses(){this.gridElement?.querySelectorAll(".data-grid-row.drop-target").forEach(e=>{e.classList.remove("drop-target","drop-before","drop-after")})}clearDragClasses(){this.gridElement?.querySelectorAll(".data-grid-row").forEach(e=>{e.classList.remove(R.DRAGGING,"drop-target","drop-before","drop-after")})}resetDragState(){this.isDragging=!1,this.draggedRowIndex=null,this.draggedRows=[],this.draggedIndices=[],this.dragSessionId=null,this.dragAccepted=!1,this.dropRowIndex=null,this.pendingMove=null}getRowIndex(e){const t=e.querySelector(".cell[data-row]");return t?parseInt(t.getAttribute("data-row")??"-1",10):-1}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}handleKeyboardMove(e,t,i,r){this.pendingMove?this.pendingMove.currentIndex=i:this.pendingMove={originalIndex:t,currentIndex:i,row:e},this.lastFocusCol=r;const n=this.internalGrid,o=[...n._rows??this.sourceRows],[s]=o.splice(t,1);o.splice(i,0,s),n._rows=o,n._focusRow=i,n._focusCol=r,n.refreshVirtualWindow(!0),De(n),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=this.internalGrid,n={row:i,fromIndex:e,toIndex:t,rows:[...r._rows??this.sourceRows],source:"keyboard"};this.emitCancelable("row-move",n)&&(r._rows=[...this.sourceRows],r._focusRow=e,r._focusCol=this.lastFocusCol,r.refreshVirtualWindow(!0),De(r))}executeIntraGridMove(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 u=c-l.getBoundingClientRect().top;Math.abs(u)>1&&s.push({el:l,deltaY:u})}),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)})}}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 r=xn(i);return e>=r.startRow&&e<=r.endRow&&t>=r.startCol&&t<=r.endCol}(e,t,i))}function _n(e){const t=[],i=xn(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 An(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function kn(e,t){const i=xn(e),r=xn(t);return i.startRow===r.startRow&&i.startCol===r.startCol&&i.endRow===r.endRow&&i.endCol===r.endCol}const Tn="__tbw_checkbox";function In(e,t){return Math.floor(e/t)}function Mn(){return new DOMException("Aborted","AbortError")}function Ln(e,t,i,r,n){const o=function(e,t){return{start:e*t,end:(e+1)*t}}(t,i);return function(e,t){return t.aborted?Promise.reject(Mn()):"object"!=typeof(i=e)||null===i||"function"!=typeof i.subscribe||"function"==typeof i.then?new Promise((i,r)=>{const n=()=>r(Mn());t.addEventListener("abort",n,{once:!0}),Promise.resolve(e).then(e=>{t.removeEventListener("abort",n),i(e)},e=>{t.removeEventListener("abort",n),r(e)})}):new Promise((i,r)=>{let n=!1;const o=e.subscribe({next:e=>{n||(n=!0,i(e),o.unsubscribe())},error:e=>{n||(n=!0,r(e))},complete:()=>{n||(n=!0,r(new Error("getRows observable completed without emitting a value")))}});n||t.addEventListener("abort",()=>{n||(n=!0,o.unsubscribe(),r(Mn()))},{once:!0})});var i}(e.getRows({startNode:o.start,endNode:o.end,sortModel:r.sortModel,filterModel:r.filterModel,signal:n}),n)}function Pn(e,t,i){const r=In(e,t),n=i.get(r);if(!n)return;return n[e%t]}function Dn(e){return e.scrollWidth>e.clientWidth}function Fn(){return"function"==typeof HTMLElement.prototype?.showPopover}function Hn(e,t,i){return void 0!==e.id?String(e.id):i?`${i}-${t}`:String(t)}function Gn(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}function On(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=Hn(l,s,i),d=l[n];if(Array.isArray(d)&&d.length>0){o.add(a);const e=On(d,t,a,r+1);for(const t of e)o.add(t)}}return o}function Nn(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=Hn(l,s,r);if(a===t)return[a];const d=l[o];if(Array.isArray(d)&&d.length>0){const e=Nn(d,t,i,a,n+1);if(e)return[a,...e]}}return null}function qn(e,t,i,r){const n=Nn(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 zn(e,t){const i=Math.min(t,e.length-1);if(i<0)return 0;let r=i;for(;r>0&&e[r].depth>0;)r--;let n=0;for(let o=0;o<=r;o++)0===e[o].depth&&n++;return n-1}function $n(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;if(null!=e&&!Array.isArray(e)&&e)return!0}return!1}function Bn(e,t,i){const r=[...e.undoStack,t];for(;r.length>i;)r.shift();return{undoStack:r,redoStack:[]}}function Wn(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 Kn(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}}class Vn extends ${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(R.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.lockVisible||i.meta?.lockVisibility)return;return[{id:"visibility/hide-column",label:"Hide Column",icon:"👁",order:30,action:()=>this.hideColumn(i.field)}]}}getToolPanel(){return{id:Vn.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(Vn.PANEL_ID)||this.grid.toggleToolPanelSection(Vn.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(Vn.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(Vn.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)}canMoveColumn(e){const t=this.grid.columns.find(t=>t.field===e.field);if(!t)return!1;const i=this.grid.query("canMoveColumn",t);return i.length>0&&!i.includes(!1)}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,"dragHandle"),e.title="Drag to reorder group",o.insertBefore(e,s)}r.appendChild(o);const u=this.grid.getAllColumns().filter(e=>!e.utility);for(const h of t){const e=u.findIndex(e=>e.field===h.field),t=this.createColumnRow(h,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&&this.canMoveColumn(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&&this.canMoveColumn(e)){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,"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(R.DRAGGING),r.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&e.classList.add(R.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(R.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(R.DRAGGING),r.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&e.classList.add(R.DRAGGING)})):this.draggedField&&r.querySelector(`.tbw-visibility-row[data-field="${this.draggedField}"]`)?.classList.add(R.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=Gi,e.BaseGridPlugin=$,e.CORE_CONSUMED_ADAPTER_METHODS=["canHandle","createRenderer","createEditor","processConfig","getTypeDefault","createToolPanelRenderer","parseDetailElement","parseResponsiveCardElement","releaseCell","unmount"],e.ClipboardPlugin=class extends ${static manifest={queries:[{type:"clipboard:copy",description:"Triggers a copy operation and returns the copied text"}]};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}handleQuery(e){if("clipboard:copy"===e.type)return this.copy(),!0}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#Lt(e.target),!0)}#Lt(e){const t=this.#Pt();if(t&&0===t.ranges.length){const t=this.#Dt(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=jt(t,this.config),r=this.#Pt(),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,u=[],h=i[0]?.length??0;for(let p=0;p<h&&s+p<=a;p++){const e=this.visibleColumns[s+p];e&&u.push(e.field)}const g={rows:i,text:t,target:c,fields:u};this.emit("paste",g),this.#Ft(g)}#Ft(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??Ut)(e,this.grid)}#Pt(){const e=this.grid?.query("getSelection");return e?.[0]}#Ht(e){const t=this.#Pt();let i,r;if(e?.columns)i=Kt(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=Kt(this.visibleColumns.slice(r,n+1))}else i=Kt(this.columns);if(e?.rowIndices)r=Vt(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}}#Gt(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=W(a,e);return s?s(t,e.field,a):this.#Ot(e,t,a)});l.push(t.join(r))}return l.join(n)}#Ot(e,t,i){if(e.format)try{const r=e.format(t,i);return null==r?"":String(r)}catch{}if(e.renderer||e.viewRenderer){const t=this.#Nt(e.field,i);if(null!=t)return t}return function(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}(t)}#Nt(e,t){const i=this.gridElement;if(!i)return null;const r=this.rows.indexOf(t);if(-1===r)return null;const n=i.querySelector(`.cell[data-row="${r}"][data-field="${e}"]`);return n?n.textContent?.trim()??null:null}#Dt(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.#Ht(e);return 0===t.length||0===i.length?"":this.#Gt(t,i,e)}async copy(e){const{columns:t,rows:i}=this.#Ht(e);if(0===t.length||0===i.length)return"";const r=this.#Gt(t,i,e);return await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){p("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?jt(e,this.config):null}getLastCopied(){return this.lastCopied}},e.ColumnVirtualizationPlugin=class extends ${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=Xt(t),this.columnOffsets=Zt(t),this.totalWidth=Qt(t),this.endCol=t.length-1}detach(){this.#qt(),this.columnWidths=[],this.columnOffsets=[],this.originalColumns=[],this.isVirtualized=!1,this.startCol=0,this.endCol=0,this.scrollLeft=0,this.totalWidth=0}#qt(){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=Xt(e),this.columnOffsets=Zt(e),this.totalWidth=Qt(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=Jt(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=di,e.DEFAULT_A11Y_MESSAGES=i,e.DEFAULT_ANIMATION_CONFIG=r,e.DEFAULT_GRID_ICONS=n,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",CELL_ACTIVATE:"cell-activate",GROUP_TOGGLE:"group-toggle",COLUMN_STATE_CHANGE:"column-state-change",DATA_CHANGE:"data-change",TBW_SCROLL:"tbw-scroll"},e.DataGridElement=Wt,e.EditingPlugin=class extends ${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:max(var(--tbw-row-height),calc(1lh + 2 * var(--tbw-cell-padding-v, .25em) + var(--tbw-border-width, 1px)));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;align-self:stretch;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#zt(){return"grid"===this.config.mode}#$t(e,t){const i=this.#At.effectiveConfig?.rowEditable;if(i&&!i(t))return!1;const{editable:r}=e;return"function"==typeof r?r(t):!0===r}#Bt(e){return!0===e.editable||"function"==typeof e.editable}#Wt=-1;#Kt;#Vt;#jt=-1;#Ut=new Map;#Yt=new Set;#Xt=new Map;#Zt=!1;#Qt=-1;#Jt;#ei=!1;#ti=!1;#ii=!1;#ri=null;#ni=new vi;#oi;get#At(){return this.grid}attach(e){super.attach(e);const t=this.disconnectSignal,i=this.#At;if(this.#Jt=new pi((e,t,i)=>{this.#si(e,t,i)}),this.#oi={grid:i,isGridMode:this.#zt,config:this.config,editingCells:this.#Yt,editorValueCallbacks:this.#Xt,isEditSessionActive:()=>-1!==this.#Wt,commitCellValue:(e,t,i,r)=>this.#li(e,t,i,r),exitRowEdit:(e,t)=>this.#ai(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.#ni.changedRowIds,configurable:!0}),e.resetChangedRows=e=>this.resetChangedRows(e),document.addEventListener("keydown",e=>{if(!this.#zt&&"Escape"===e.key&&-1!==this.#Wt){if(Ri(this.config,e))return;this.#ai(this.#Wt,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",e=>{if(this.#zt)return;if(-1===this.#Wt)return;const t=i.findRenderedRowElement?.(this.#Wt);if(!t)return;if((e.composedPath&&e.composedPath()||[]).includes(t))return;const r=e.target;if(!r||this.gridElement.contains(r)||!this.grid.containsFocus?.(r)){if(r&&!this.gridElement.contains(r)){const e=i.findRenderedRowElement?.(this.#Wt);if(e&&function(e,t){if(!e)return!1;const i=t.querySelectorAll('[aria-expanded="true"][aria-controls]');for(let r=0;r<i.length;r++){const n=i[r].getAttribute("aria-controls");if(!n)continue;const o=t.ownerDocument?.getElementById(n);if(o&&o.contains(e))return!0}return!1}(r,e))return}Ri(this.config,e)||queueMicrotask(()=>{-1!==this.#Wt&&this.#ai(this.#Wt,!1)})}},{signal:t}),this.config.focusTrap&&this.gridElement.addEventListener("focusout",e=>{if(this.#zt)return;if(-1===this.#Wt)return;const t=e.relatedTarget;t&&this.grid.containsFocus?.(t)||t&&this.gridElement.contains(t)||queueMicrotask(()=>{-1!==this.#Wt&&this.#di()})},{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.#Xt.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.#ni.isRowDirty(n,r);this.emit("dirty-change",{rowId:n,row:r,original:this.#ni.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.#zt&&(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(yi)){if(this.#ti)return t.blur(),void this.gridElement.focus();const e=i._focusRow,r=i._focusCol,n=this.#ri;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.#ri={rowIndex:e,colIndex:r,field:i,value:n[i]}}}this.#ei=!0}},{signal:t}),this.gridElement.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.gridElement.contains(t)||this.grid.containsFocus?.(t))&&t.matches(yi)||(this.#ei=!1,this.#ri=null)},{signal:t}),this.gridElement.addEventListener("keydown",e=>{if("Escape"===e.key&&this.#ei){if(Ri(this.config,e))return void queueMicrotask(()=>{if(this.#ei){this.#ci();const e=document.activeElement;e&&this.gridElement.contains(e)&&(e.blur(),this.gridElement.focus()),this.#ei=!1,this.#ti=!0}});this.#ci();const t=document.activeElement;t&&this.gridElement.contains(t)&&(t.blur(),this.gridElement.focus()),this.#ei=!1,this.#ti=!0,e.preventDefault(),e.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",e=>{e.target.matches(yi)&&(this.#ti=!1)},{signal:t}))}detach(){this.#At._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#Wt=-1,this.#Kt=void 0,this.#Vt=void 0,this.#jt=-1,this.#Ut.clear(),this.#ni.clear(),this.#Yt.clear(),this.#Xt.clear(),this.#ei=!1,this.#ti=!1,this.#ri=null,this.#ii=!1,super.detach()}handleQuery(e){if("isEditing"===e.type)return this.#zt||-1!==this.#Wt}onCellClick(e){if(this.#zt)return!1;const t=this.#At,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.#Bt(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.#At;if("Escape"===e.key){if(this.#zt&&this.#ei){this.#ci();const e=document.activeElement;return e&&this.gridElement.contains(e)&&(e.blur(),this.gridElement.focus()),this.#ei=!1,this.#ti=!0,this.requestAfterRender(),!0}if(-1!==this.#Wt&&!this.#zt)return Ri(this.config,e)||this.#ai(this.#Wt,!0),!0}if(this.#zt&&!this.#ei&&("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key))return!1;if(this.#zt&&this.#ei&&("ArrowUp"===e.key||"ArrowDown"===e.key))return!0;if(("ArrowUp"===e.key||"ArrowDown"===e.key)&&-1!==this.#Wt&&!this.#zt)return!0;if("Tab"===e.key&&(-1!==this.#Wt||this.#zt)){if(e.preventDefault(),this.#ii)return this.#ai(this.#Wt,!1),!0;const t=!e.shiftKey;return this.#ui(t),!0}if(" "===e.key||"Spacebar"===e.key){if(-1!==this.#Wt)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.#$t(n,o)&&"boolean"===n.type){const t=n.field;if(Ci(t)){const r=!o[t];return this.#li(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.#zt&&!this.#ei)return this.#di(),!0;if(-1!==this.#Wt){const t=e.target;return(!t||"true"!==t.getAttribute?.("aria-expanded")||!t.hasAttribute?.("aria-controls"))&&!!Ri(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.#Bt(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}});return this.gridElement.dispatchEvent(d),d.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(r),!0)}}return!1}if("F2"===e.key){if(-1!==this.#Wt||this.#zt)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.#$t(n,o)&&n.field)return e.preventDefault(),this.beginCellEdit(i,n.field),!0}return!1}return!1}processColumns(e){const t=this.#At,i=t.effectiveConfig?.typeDefaults,r=t.__frameworkAdapter;return i||r?.getTypeDefault?e.map(e=>{if(!e.type)return e;let n;if(i?.[e.type]?.editorParams&&(n=i[e.type].editorParams),!n&&r?.getTypeDefault){const i=r.getTypeDefault(e.type,t._hostElement);i?.editorParams&&(n=i.editorParams)}return n?{...e,editorParams:{...n,...e.editorParams}}:e}):e}processRows(e){const t=this.#At;if(this.config.dirtyTracking&&t.getRowId&&this.#ni.capture(e,e=>{try{return t.getRowId?.(e)}catch{return}}),-1===this.#Wt||this.#zt)return e;const i=this.#Kt,r=this.#Vt;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.#Wt!==o&&this.#hi(this.#Wt,o),n)}afterRender(){const e=this.#At;if(-1!==this.#Wt&&this.#Vt&&!this.#zt&&e._rows[this.#Wt]!==this.#Vt){const t=e._rows.indexOf(this.#Vt);if(-1===t)return void setTimeout(()=>this.cancelActiveRowEdit(),0);this.#hi(this.#Wt,t)}if(this.#Zt&&(this.#Zt=!1,this.#gi(e)),-1!==this.#Qt){const t=this.#Qt;this.#Qt=-1,e.animateRow?.(t,"change")}const t=this.#ni.drainCapturedFlag();if(null!=t&&this.emit("baselines-captured",{count:t}),!this.#zt&&0!==this.#Yt.size)for(const i of this.#Yt){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.#pi(a,n,d,o,l,!0)}}afterCellRender(e){const{row:t,rowIndex:i,column:r,colIndex:n,cellElement:o}=e,s=this.#$t(r,t);if(s)o.removeAttribute("aria-readonly");else if(o.setAttribute("aria-readonly","true"),this.#zt&&o.classList.contains("editing")){o.classList.remove("editing");const e=t[r.field];o.textContent=null==e?"":String(e)}this.#zt&&s&&(o.classList.contains("editing")||this.#pi(t,i,r,n,o,!0,e.rowElement))}afterRowRender(e){if(!this.config.dirtyTracking)return;const t=this.#At,i=t.getRowId?.(e.row);if(!i)return;const{isNew:r,isCommittedDirty:n,hasBaseline:o}=this.#ni.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.#ni.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.#ni.getChangedRows(e=>this.grid.getRow(e))}get changedRowIds(){return this.#ni.getChangedRowIds()}get activeEditRow(){return this.#Wt}get activeEditCol(){return this.#jt}isRowEditing(e){return this.#Wt===e}isCellEditing(e,t){return this.#Yt.has(`${e}:${t}`)}isRowChanged(e){const t=this.#At,i=t._rows[e];if(!i)return!1;try{const e=t.getRowId?.(i);return!!e&&this.#ni.isRowChanged(e)}catch{return!1}}isRowChangedById(e){return this.#ni.isRowChanged(e)}isDirty(e){if(!this.config.dirtyTracking)return!1;if(this.#ni.newRowIds.has(e))return!0;const t=this.grid.getRow(e);return!!t&&this.#ni.isRowDirty(e,t)}isPristine(e){return!this.isDirty(e)}get dirty(){if(!this.config.dirtyTracking)return!1;const e=this.#At;return this.#ni.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.#ni.markPristine(e,t),this.emit("dirty-change",{rowId:e,row:t,original:t,type:"pristine"}))}markAsNew(e){if(!this.config.dirtyTracking)return;this.#ni.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.#ni.markDirty(e),this.emit("dirty-change",{rowId:e,row:t,original:this.#ni.getOriginalRow(e),type:"modified"}))}markAllPristine(){if(!this.config.dirtyTracking)return;const e=this.#At;this.#ni.markAllPristine(t=>e._getRowEntry(t)?.row)}getOriginalRow(e){if(this.config.dirtyTracking)return this.#ni.getOriginalRow(e)}hasBaseline(e){return!!this.config.dirtyTracking&&this.#ni.hasBaseline(e)}getDirtyRows(){if(!this.config.dirtyTracking)return[];const e=this.#At;return this.#ni.getDirtyRows(t=>e._getRowEntry(t)?.row)}get dirtyRowIds(){if(!this.config.dirtyTracking)return[];const e=this.#At;return this.#ni.getDirtyRowIds(t=>e._getRowEntry(t)?.row)}revertRow(e){if(!this.config.dirtyTracking)return;const t=this.grid.getRow(e);t&&this.#ni.revertRow(e,t)&&(this.emit("dirty-change",{rowId:e,row:t,original:this.#ni.getOriginalRow(e),type:"reverted"}),this.requestRender())}revertAll(){if(!this.config.dirtyTracking)return;const e=this.#At;this.#ni.revertAll(t=>e._getRowEntry(t)?.row),this.requestRender()}setInvalid(e,t,i=""){this.#Jt.setInvalid(e,t,i)}clearInvalid(e,t){this.#Jt.clearInvalid(e,t)}clearRowInvalid(e){this.#Jt.clearRowInvalid(e)}clearAllInvalid(){this.#Jt.clearAllInvalid()}isCellInvalid(e,t){return this.#Jt.isCellInvalid(e,t)}getInvalidMessage(e,t){return this.#Jt.getInvalidMessage(e,t)}hasInvalidCells(e){return this.#Jt.hasInvalidCells(e)}getInvalidFields(e){return this.#Jt.getInvalidFields(e)}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#ni.changedRowIds.clear(),this.#ni.committedDirtyRowIds.clear(),this.#fi(),e||this.emit("changed-rows-reset",{rows:t,ids:i});const r=this.#At;r._rowPool?.forEach(e=>e.classList.remove("changed"))}beginCellEdit(e,t){const i=this.#At,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.#$t(n,o))return;const s=i.findRenderedRowElement?.(e),l=s?.querySelector(`.cell[data-col="${r}"]`);l&&(this.#ii=!0,this.#wi(e,r,l))}beginBulkEdit(e){const t=this.#At;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return;const i=t._columns?.some(e=>this.#Bt(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.#ii=!1,this.#mi(e,n),Array.from(r.children).forEach((i,r)=>{const o=t._visibleColumns[r];if(o&&this.#$t(o,n)){const t=i;t.classList.contains("editing")||this.#pi(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(yi);try{t?.focus({preventScroll:!0})}catch{}}},0))}commitActiveRowEdit(){-1!==this.#Wt&&this.#ai(this.#Wt,!1)}cancelActiveRowEdit(){-1!==this.#Wt&&this.#ai(this.#Wt,!0)}#si(e,t,i){const r=this.#At,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.#Jt.getInvalidMessage(e,t);i&&a.setAttribute("title",i)}else a.removeAttribute("data-invalid"),a.removeAttribute("title")}#hi(e,t){this.#Wt=t;const i=new Set,r=`${e}:`;for(const s of this.#Yt)s.startsWith(r)?i.add(`${t}:${s.substring(r.length)}`):i.add(s);this.#Yt.clear();for(const s of i)this.#Yt.add(s);const n=this.#Ut.get(e);void 0!==n&&(this.#Ut.delete(e),this.#Ut.set(t,n));const o=[];for(const[s,l]of this.#Xt)s.startsWith(r)&&(o.push([`${t}:${s.substring(r.length)}`,l]),this.#Xt.delete(s));for(const[s,l]of o)this.#Xt.set(s,l);this.#fi()}#wi(e,t,i){const r=this.#At,n=r._rows[e],o=r._visibleColumns[t];n&&o&&this.#$t(o,n)&&(i.classList.contains("editing")||(this.#Wt!==e&&this.#mi(e,n),this.#jt=t,this.#pi(n,e,o,t,i,!1)))}#ci(){const e=this.#ri;if(!e)return;const t=this.#At,i=t._rows?.[e.rowIndex];i&&(i[e.field]=e.value);const r=`${e.rowIndex}:${e.field}`,n=this.#Xt.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.#ni.isRowDirty(e,i)||(this.#ni.changedRowIds.delete(e),this.emit("dirty-change",{rowId:e,row:i,original:this.#ni.getOriginalRow(e),type:"reverted"})):this.#ni.changedRowIds.delete(e))}this.requestRender(),this.#ri=null}#di(){const e=this.#At,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(yi);e&&(this.#ti=!1,e.focus(),this.#ei=!0,e instanceof HTMLInputElement&&("text"===e.type||"number"===e.type)&&e.select())}}#ui(e){const t=this.#At,i=t._rows,r=this.#zt?t._focusRow:this.#Wt,n=i[r],o=t._visibleColumns.map((e,t)=>n&&this.#$t(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(yi);e?.focus({preventScroll:!0})}return void De(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.#$t(e,n)?t:-1).filter(e=>e>=0);if(0===o.length)return;this.#zt?(t._focusRow=l,t._focusCol=e?o[0]:o[o.length-1],De(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(yi);e?.focus({preventScroll:!0})}},0)):(this.#ai(r,!1),t._focusRow=l,t._focusCol=e?o[0]:o[o.length-1],this.beginBulkEdit(l),De(t,{forceHorizontalScroll:!0}))}}#fi(){const e=this.#At;e._activeEditRows=this.#Wt,e._rowEditSnapshots=this.#Ut}#mi(e,t){if(this.#Wt!==e){-1!==this.#Wt&&this.#ai(this.#Wt,!1),this.#Ut.set(e,{...t}),this.#Wt=e,this.#Vt=t;const i=this.#At;try{this.#Kt=i.getRowId?.(t)??void 0}catch{this.#Kt=void 0}this.#fi(),this.#zt||(this.emit("edit-open",{rowIndex:e,rowId:this.#Kt??"",row:t}),o(this.gridElement,s(this.gridElement,"editingStarted",e)))}}#ai(e,t){if(this.#Wt!==e)return;const i=this.#At,r=this.#Ut.get(e),n=i.findRenderedRowElement?.(e);let l=this.#Kt;const a=l?i._getRowEntry(l):void 0,d=a?.row??this.#Vt??i._rows[e];if(!l&&d)try{l=i.getRowId?.(d)}catch{}if(!t&&n&&d){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=d[t],r=gi(o,n,i);i!==r&&this.#li(e,n,r,d)}})}if(t||this.#zt||!d||this.emit("before-edit-close",{rowIndex:e,rowId:l??"",row:d}),t&&r&&d)Object.keys(r).forEach(e=>{d[e]=r[e]}),l&&(this.#ni.changedRowIds.delete(l),this.#ni.committedDirtyRowIds.delete(l),this.clearRowInvalid(l));else if(!t&&d){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,d),i=l?this.#ni.changedRowIds.has(l):t,n=this.emitCancelable("row-commit",{rowIndex:e,rowId:l??"",row:d,oldValue:r,newValue:d,changed:i,changedRows:this.changedRows,changedRowIds:this.changedRowIds});n&&r?(Object.keys(r).forEach(e=>{d[e]=r[e]}),l&&(this.#ni.changedRowIds.delete(l),this.#ni.committedDirtyRowIds.delete(l),this.clearRowInvalid(l))):n||(l&&this.config.dirtyTracking&&(this.#ni.isRowDirty(l,d)?this.#ni.committedDirtyRowIds.add(l):this.#ni.committedDirtyRowIds.delete(l)),t&&this.isAnimationEnabled&&(this.#Qt=e))}this.#Ut.delete(e),this.#Wt=-1,this.#Kt=void 0,this.#Vt=void 0,this.#jt=-1,this.#ii=!1,this.#fi();for(const o of this.#Yt)o.startsWith(`${e}:`)&&this.#Yt.delete(o);for(const o of this.#Xt.keys())o.startsWith(`${e}:`)&&this.#Xt.delete(o);if(this.#Zt=!0,n){const e=i.__frameworkAdapter,t=n.querySelectorAll(".cell.editing");e?.releaseCell&&t.forEach(t=>{e.releaseCell(t)}),t.forEach(e=>{e.classList.remove("editing"),function(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing")}(e.parentElement)}),i.refreshVirtualWindow(!0)}else this.#gi(i),this.#Zt=!1;!this.#zt&&d&&(this.emit("edit-close",{rowIndex:e,rowId:l??"",row:d,reverted:t}),t||o(this.gridElement,s(this.gridElement,"editingCommitted",e)))}#li(e,t,i,r){const n=t.field;if(!Ci(n))return;const o=r[n];if(o===i)return;const s=this.#At;let l;try{l=this.grid.getRowId(r)}catch{}const a=!l||!this.#ni.changedRowIds.has(l),d=l?e=>this.grid.updateRow(l,e,"cascade"):xi;let c=!1;const u=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:u}))return;if(l&&!c&&this.isCellInvalid(l,n)&&this.clearInvalid(l,n),r[n]=i,K(r,n),l&&this.#ni.changedRowIds.add(l),this.#fi(),this.config.dirtyTracking&&l){const e=this.#ni.isRowDirty(l,r);this.emit("dirty-change",{rowId:l,row:r,original:this.#ni.getOriginalRow(l),type:e?"modified":"pristine"})}this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:n,oldValue:o,newValue:i});const h=s.findRenderedRowElement?.(e);h&&h.classList.add("changed")}#pi(e,t,i,r,n,o,s){Ei(this.#oi,e,t,i,r,n,o,s)}#gi(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 ${static manifest={queries:[{type:"export:csv",description:"Triggers a CSV export"}]};name="export";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;handleQuery(e){if("export:csv"===e.type)return this.exportCsv(),!0}resolveExportData(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,mode:t?.mode??"raw",columns:t?.columns,rowIndices:t?.rowIndices,excelStyles:t?.excelStyles,fileExtension:t?.fileExtension},n=Kt(this.columns,t?.columns,i.onlyVisible);let o;if(t?.rowIndices)o=Vt(this.rows,t.rowIndices);else if(i.onlySelected){const e=this.getSelectionState();o=e?.selected?.size?Vt(this.rows,[...e.selected]):[...this.rows]}else o=[...this.rows];return{columns:n,rows:o,fullParams:r}}resolveCellOutput(e,t,i,r,n){let o=e;if("formatted"===r){const r=this.#bi(t);if(r)try{const t=r(e,i);o=null==t?"":String(t)}catch{o=null==e?"":String(e)}else o="date"===t.type?pe(e):"boolean"===t.type?!!e:e}return n&&(o=n(o,t.field,i)),o}performExport(e,t){const{columns:i,rows:r,fullParams:n}=this.resolveExportData(e,t);this.isExportingFlag=!0;let o=n.fileName??"export";const s=this.#vi(i);try{switch(e){case"csv":{const e=_i(this.#yi(r,i,n),s,{...n,processCell:void 0},{bom:!0});o=o.endsWith(".csv")?o:`${o}.csv`,function(e,t){Ai(new Blob([e],{type:"text/csv;charset=utf-8;"}),t)}(e,o);break}case"excel":{const e=Hi(this.#yi(r,i,n),s,{...n,processCell:void 0}),t=n.fileExtension??".xls",l=t.startsWith(".")?t:`.${t}`;o=o.endsWith(l)?o:`${o}${l}`,function(e,t){Ai(new Blob([e],{type:"application/vnd.ms-excel;charset=utf-8;"}),t)}(e,o);break}case"json":{const e=this.#yi(r,i,n),t=JSON.stringify(e,null,2);o=o.endsWith(".json")?o:`${o}.json`;Ai(new Blob([t],{type:"application/json"}),o);break}}this.lastExportInfo={format:e,timestamp:new Date},this.emit("export-complete",{format:e,fileName:o,rowCount:r.length,columnCount:i.length})}finally{this.isExportingFlag=!1}}#yi(e,t,i){const r=i.mode??"raw";return e.map(e=>{const n={};for(const o of t){const t=W(e,o);n[o.field]=this.resolveCellOutput(t,o,e,r,i.processCell)}return n})}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}export(e){const{columns:t,rows:i,fullParams:r}=this.resolveExportData("json",e);return this.#yi(i,t,r)}getResolvedColumns(e){return Kt(this.columns,e?.columns,this.config.onlyVisible)}formatCsv(e,t,i){const{columns:r,fullParams:n}=this.resolveExportData("csv",t);return _i(e,this.#vi(r),n,i)}formatExcel(e,t){const{columns:i,fullParams:r}=this.resolveExportData("excel",t);return Hi(e,this.#vi(i),r)}#vi(e){return e.map(e=>e.valueAccessor?{...e,valueAccessor:void 0}:e)}#bi(e){if(e.format)return e.format;if(!e.type)return;const t=this.grid,i=t?.__frameworkAdapter;if(!i?.getTypeDefault)return;const r=i.getTypeDefault(e.type,t?._hostElement);return r?.format}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=Ui,e.FitModeEnum=t,e.GridCSSVars={COLOR_BG:"--tbw-color-bg",COLOR_FG:"--tbw-color-fg",COLOR_FG_MUTED:"--tbw-color-fg-muted",COLOR_BORDER:"--tbw-color-border",COLOR_ACCENT:"--tbw-color-accent",COLOR_HEADER_BG:"--tbw-color-header-bg",COLOR_HEADER_FG:"--tbw-color-header-fg",COLOR_SELECTION:"--tbw-color-selection",COLOR_ROW_HOVER:"--tbw-color-row-hover",COLOR_ROW_ALT:"--tbw-color-row-alt",ROW_HEIGHT:"--tbw-row-height",HEADER_HEIGHT:"--tbw-header-height",CELL_PADDING:"--tbw-cell-padding",FONT_FAMILY:"--tbw-font-family",FONT_SIZE:"--tbw-font-size",BORDER_RADIUS:"--tbw-border-radius",FOCUS_OUTLINE:"--tbw-focus-outline"},e.GridClasses=R,e.GridDataAttrs=E,e.GridElement=Wt,e.GridSelectors=S,e.GroupingColumnsPlugin=class extends ${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;#Ci=new Set;#xi=[];#Ri=new Map;attach(e){super.attach(e),this.gridElement.addEventListener("column-move",this.#Ei,{signal:this.disconnectSignal})}detach(){this.groups=[],this.isActive=!1,this.#Ci.clear(),this.#xi=[],this.#Ri.clear()}#Ei=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.#Si(n,r))return t.preventDefault(),void this.#_i(i)}this.#Ai(r)};#Ai(e){this.#Ci.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.#Ci.add(e[i])}}#Si(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}#_i(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.#ki()}#ki(){let e;if(this.#xi.length>0)e=this.#xi.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||g("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.#xi=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});n=e.map(e=>{const t=i.get(e.field);return t&&!e.group?{...e,group:t}:e})}else this.#xi=[],this.#Ri.clear(),n=[...e];const o=Yi(n);if(0===o.length)return this.isActive=!1,this.groups=[],n;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.#Ci.clear();for(const s of o){const e=s.columns[s.columns.length-1];e?.field&&this.#Ci.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=Yi(i);if(0===r.length)return;if(this.#Ri.size>0)for(const l of r){const e=this.#Ri.get(l.id);e&&(l.renderer=e)}this.#Ci.clear();const n=Xi(r);for(let l=0;l<n.merged.length;l++){const e=n.merged[l],t=e.columns[e.columns.length-1];t?.field&&l<n.merged.length-1&&this.#Ci.add(t.field)}const o=function(e,t,i,r){if(0===e.length)return null;const n=document.createElement("div");n.className="header-group-row",n.setAttribute("role","row");const{merged:o}=r??Xi(e);for(const s of o){const e=String(s.id),r=e.startsWith("__implicit__"),o=Zi(s,t);if(!o)continue;const[l,a]=o,d=a-l+1,c=r?"":s.label||s.id,u=document.createElement("div");u.className="cell header-group-cell",r&&u.classList.add("implicit-group"),u.setAttribute("data-group",e),u.style.gridColumn=`${l+1} / span ${d}`;const h=!r&&(s.renderer||i)||void 0;if(h&&!r){const t=h({id:e,label:String(c),columns:s.columns,firstIndex:l,isImplicit:!1});t instanceof HTMLElement?u.appendChild(t):"string"==typeof t?u.innerHTML=F(t):u.textContent=c}else u.textContent=c;n.appendChild(u)}return n}(r,i,this.config.groupHeaderRenderer,n);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,r){if(!t.length||!e)return;const{merged:n,embedded:o}=r??Xi(t),s=new Map;for(const a of n)if(!String(a.id).startsWith("__implicit__"))for(const e of a.columns)e.field&&s.set(e.field,a.id);for(let a=0;a<t.length;a++){const e=t[a];if(String(e.id).startsWith("__implicit__")&&o.has(String(e.id)))for(let i=a-1;i>=0;i--)if(!String(t[i].id).startsWith("__implicit__")){for(const r of e.columns)r.field&&s.set(r.field,t[i].id);break}}const l=Array.from(e.querySelectorAll(".cell[data-field]"));l.forEach(e=>{const t=e.getAttribute("data-field")||"",i=s.get(t);i&&(e.classList.add("grouped"),e.getAttribute("data-group")||e.setAttribute("data-group",i))});for(const a of n){const e=a.columns[a.columns.length-1],t=l.find(t=>t.getAttribute("data-field")===e.field);t&&t.classList.add("group-end")}}(s,r,0,n))}afterCellRender(e){this.isActive&&this.config.showGroupBorders&&e.cellElement.classList.toggle("group-end",this.#Ci.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 ${static manifest={modifiesRowStructure:!0,hookPriority:{processRows:10,onHeaderClick:-1},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."}],events:[{type:"group-toggle",description:"Emitted when groups are expanded/collapsed. Broadcast to both DOM consumers and plugin bus."},{type:"group-expand",description:"Emitted when a pre-defined group is expanded."},{type:"group-collapse",description:"Emitted when a pre-defined group is collapsed."}],queries:[{type:"canMoveRow",description:"Returns false for group header rows (cannot be reordered)"},{type:"grouping:get-grouped-fields",description:"Returns the column field names that match group depth levels (string[])"},{type:"datasource:viewport-mapping",description:"Translates flat viewport row indices to top-level group indices for ServerSide pagination."}],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)}]};static dependencies=[{name:"multiSort",required:!1,reason:"Queries sort model for coordinated group sorting"},{name:"serverSide",required:!1,reason:"Consumes datasource events for lazy-loaded grouped data"}];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)}@media(hover:hover){.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;preDefinedGroups=[];groupRowsMap=new Map;loadingGroups=new Set;groupedFields=[];userGroupSortDirections=new Map;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,this.preDefinedGroups=[],this.groupRowsMap.clear(),this.loadingGroups.clear(),this.groupedFields=[],this.userGroupSortDirections.clear()}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}if("grouping:get-grouped-fields"===e.type)return[...this.groupedFields];if("datasource:viewport-mapping"===e.type){const{viewportStart:t,viewportEnd:i}=e.context;if(0===this.flattenedRows.length)return;if(0===this.preDefinedGroups.length&&!Array.isArray(this.config.groups))return;const r=this.getActiveGroups();return{startNode:this.getTopLevelGroupIndex(t),endNode:this.getTopLevelGroupIndex(i)+1,totalLoadedNodes:r.length}}}getTopLevelGroupIndex(e){let t=-1;const i=Math.min(e,this.flattenedRows.length-1);for(let r=0;r<=i;r++){const e=this.flattenedRows[r];"group"===e.kind&&0===e.depth&&t++}return Math.max(0,t)}attach(e){super.attach(e),this.on("datasource:data",e=>{const t=e;t.claimed||(t.claimed=!0,this.preDefinedGroups=t.rows,this.groupRowsMap.clear(),this.loadingGroups.clear(),this.hasAppliedDefaultExpanded=!1,this.requestRender())}),this.on("datasource:children",e=>{const t=e;if("grouping-rows"!==t.context?.source)return;t.claimed=!0;const i=t.context.groupKey;i&&(this.groupRowsMap.set(i,t.rows),this.loadingGroups.delete(i),this.requestRender())})}onHeaderClick(e){const t=this.groupedFields.indexOf(e.field);if(-1===t)return;if(!e.column.sortable)return;const i=t,r=this.userGroupSortDirections.get(i)??1;return this.userGroupSortDirections.set(i,1===r?-1:1),this.requestRender(),!0}resolveGroupSortDirections(e){const t=this.config;if("function"!=typeof t.groupOn||0===e.length)return void(this.groupedFields=[]);const i=this.columns.map(e=>e.field),r=function(e,t,i){const r=new Map;if(0===e.length)return r;const n=e[0];let o=t(n);if(null==o||!1===o)return r;Array.isArray(o)||(o=[o]);for(let s=0;s<o.length;s++){const e=o[s];for(const t of i)if(n[t]===e){r.set(s,t);break}}return r}([...e],t.groupOn,i);if(this.groupedFields=[...r.values()],0===r.size)return;const n=new Map(this.userGroupSortDirections);if(n.size<r.size){const e=new Map,t=this.grid?.query?.("sort:get-model",null);if(Array.isArray(t)&&t.length>0){const i=t[0];if(Array.isArray(i))for(const t of i)e.set(t.field,"desc"===t.direction?-1:1)}if(0===e.size){const t=this.grid;t._sortState&&e.set(t._sortState.field,t._sortState.direction)}for(const[i,o]of r)if(!n.has(i)){const t=e.get(o);void 0!==t&&n.set(i,t)}}return n.size>0?n:void 0}static detect(e,t){return"function"==typeof t?.groupOn||"boolean"==typeof t?.enableRowGrouping||Array.isArray(t?.groups)}processRows(e){if(this.preDefinedGroups.length>0||Array.isArray(this.config.groups))return this.preDefinedGroups.length>0||Array.isArray(this.config.groups)&&this.config.groups.length>0?this.processPreDefinedGroups():(this.isActive=!1,this.flattenedRows=[],[]);const t=this.config;if("function"!=typeof t.groupOn)return this.isActive=!1,this.flattenedRows=[],[...e];const i=this.resolveGroupSortDirections(e),r=nr({rows:[...e],config:t,expanded:new Set,groupSortDirections:i});if(0===r.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)}(r);n=or(t.defaultExpanded??!1,e),n.size>0&&(this.expandedKeys=new Set(n),this.hasAppliedDefaultExpanded=!0)}const o=nr({rows:[...e],config:t,expanded:this.expandedKeys,initialExpanded:n,groupSortDirections:i});this.isActive=!0,this.flattenedRows=o,this.keysToAnimate.clear();const s=new Set;return o.forEach((e,t)=>{if("data"===e.kind){const e=`data-${t}`;s.add(e),this.previousVisibleKeys.has(e)||this.keysToAnimate.add(e)}}),this.previousVisibleKeys=s,o.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(`.${R.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(!0===e?.__loading&&e?.__groupKey){t.className="data-grid-row",t.__isCustomRow=!0,t.innerHTML="";const e=document.createElement("div");return e.className="cell",e.style.gridColumn="1 / -1",e.setAttribute("role","gridcell"),e.textContent=" ",t.appendChild(e),We(t,!0),!0}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()}processPreDefinedGroups(){const e=this.preDefinedGroups.length>0?this.preDefinedGroups:Array.isArray(this.config.groups)?this.config.groups:[];if(0===e.length)return this.isActive=!1,this.flattenedRows=[],[];if(!this.hasAppliedDefaultExpanded&&0===this.expandedKeys.size&&!1!==this.config.defaultExpanded){const t=this.collectGroupKeys(e),i=or(this.config.defaultExpanded??!1,t);i.size>0&&(this.expandedKeys=new Set(i),this.hasAppliedDefaultExpanded=!0)}const t=sr({groups:e,expanded:this.expandedKeys,groupRows:this.groupRowsMap,loadingGroups:this.loadingGroups});this.isActive=!0,this.flattenedRows=t,this.keysToAnimate.clear();const i=new Set;return t.forEach((e,t)=>{if("data"===e.kind){const e=`data-${t}`;i.add(e),this.previousVisibleKeys.has(e)||this.keysToAnimate.add(e)}}),this.previousVisibleKeys=i,t.map(t=>{if("group"===t.kind){const i=this.findGroupDefinition(e,t.key),r=i?.rowCount??t.rows.length;return{__isGroupRow:!0,__groupKey:t.key,__groupValue:t.value,__groupDepth:t.depth,__groupRows:t.rows,__groupExpanded:t.expanded,__groupRowCount:r,__rowCacheKey:`group:${t.key}`}}return t.row})}collectGroupKeys(e){const t=[];for(const i of e)t.push(i.key),i.children?.length&&t.push(...this.collectGroupKeys(i.children));return t}getActiveGroups(){return this.preDefinedGroups.length>0?this.preDefinedGroups:Array.isArray(this.config.groups)?this.config.groups:[]}findGroupDefinition(e,t){for(const i of e){if(i.key===t)return i;if(i.children?.length){const e=this.findGroupDefinition(i.children,t);if(e)return e}}}createToggleButton(e,t){const i=document.createElement("button");return i.type="button",i.className=`${R.GROUP_TOGGLE}${e?` ${R.EXPANDED}`:""}`,i.setAttribute("aria-label",e?"Collapse group":"Expand group"),this.setIcon(i,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=R.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=R.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=ir.run(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"),$i(o))return a.setAttribute("data-field",o.field),void t.appendChild(a);if(d){const e=n[o.field];if(e){const t=ir.run(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=ir.run(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=R.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("group-toggle",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("group-toggle",{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.broadcast("group-toggle",{key:e,expanded:this.expandedKeys.has(e),value:r?.value,depth:r?.depth??0,expandedKeys:[...this.expandedKeys]});const n=this.getActiveGroups();if(n.length>0){const i=lr(n,e);if(t){if(this.emit("group-expand",{groupKey:e,groupPath:i}),!this.groupRowsMap.has(e)){const t=this.findGroupDefinition(n,e);t&&(this.loadingGroups.add(e),this.grid?.query?.("datasource:fetch-children",{context:{source:"grouping-rows",groupKey:e,group:t,groupPath:i}}))}}else this.emit("group-collapse",{groupKey:e,groupPath:i})}const l=this.expandedKeys.has(e),a=null!=r?.value?String(r.value):e;if(l){const e=r?.rows?.length??0;o(this.gridElement,s(this.gridElement,"groupExpanded",a,e))}else o(this.gridElement,s(this.gridElement,"groupCollapsed",a));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()}setGroups(e){this.preDefinedGroups=e,this.groupRowsMap.clear(),this.loadingGroups.clear(),this.expandedKeys.clear(),this.hasAppliedDefaultExpanded=!1,this.requestRender()}getGroups(){return this.preDefinedGroups.length>0?[...this.preDefinedGroups]:Array.isArray(this.config.groups)?[...this.config.groups]:[]}setGroupRows(e,t){this.groupRowsMap.set(e,t),this.loadingGroups.delete(e),this.requestRender()}setGroupLoading(e,t){t?this.loadingGroups.add(e):this.loadingGroups.delete(e),this.requestRender()}clearGroupRows(e){null!=e?this.groupRowsMap.delete(e):this.groupRowsMap.clear(),this.requestRender()}},e.MasterDetailPlugin=cr,e.MultiSortPlugin=class extends ${static manifest={queries:[{type:"sort:get-model",description:"Returns the current multi-sort model as SortModel[]"},{type:"sort:set-model",description:"Sets the multi-sort model from context (SortModel[])"}]};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;#Ti=!1;#Ii=[];get#At(){return this.grid}clearCoreSortState(){this.#At._sortState=null}#Mi(e){const t=this.grid?.query?.("grouping:get-grouped-fields",null);if(!Array.isArray(t)||0===t.length)return e;const i=t[0];if(!Array.isArray(i)||0===i.length)return e;const r=new Set(i),n=e.filter(e=>!r.has(e.field));return n.length===e.length?e:n}detach(){this.sortModel=[],this.cachedSortResult=null}handleQuery(e){switch(e.type){case"sort:get-model":return[...this.sortModel];case"sort:set-model":{const t=e.context;return!!Array.isArray(t)&&(this.sortModel=[...t],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),!0)}default:return}}processRows(e){if(0===this.sortModel.length)return this.cachedSortResult=null,[...e];const t=this.#At;if(!t._isGridEditMode&&"number"==typeof t._activeEditRows&&-1!==t._activeEditRows&&this.cachedSortResult&&this.cachedSortResult.length===e.length)return[...this.cachedSortResult];const i=this.#Mi(this.sortModel),r=e;return i.length>0&&function(e,t,i){if(!t.length)return;const r=t.map(e=>{const t=i.find(t=>t.field===e.field),r=t?.sortComparator??hr;return{field:e.field,asc:"asc"===e.direction,comparator:r,pinPlaceholders:!t?.sortComparator,column:t}}),n=(e,t)=>t.column?.valueAccessor?W(e,t.column):e[t.field];if(1===r.length){const t=r[0];e.sort((e,i)=>{if(t.pinPlaceholders){const t=ur(e,i);if(0!==t)return t}const r=t.comparator(n(e,t),n(i,t),e,i);return t.asc?r:-r})}else e.sort((e,t)=>{if(r.some(e=>e.pinPlaceholders)){const i=ur(e,t);if(0!==i)return i}for(let i=0;i<r.length;i++){const o=r[i],s=o.comparator(n(e,o),n(t,o),e,t);if(0!==s)return o.asc?s:-s}return 0})}(r,i,this.columns),this.cachedSortResult=r,r}onHeaderClick(e){const t=this.columns.find(t=>t.field===e.field);if(!t?.sortable)return!1;const i=e.originalEvent.shiftKey,r=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,i,r),this.clearCoreSortState(),this.broadcast("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"}`});o(this.gridElement,s(this.gridElement,"sortApplied",e.join(", then "),""))}else o(this.gridElement,s(this.gridElement,"sortCleared"));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=gr(this.sortModel,i),n=pr(this.sortModel,i);if(e.querySelector(".sort-index")?.remove(),n){const i=this.updateSortIndicator(e,n);if(t&&this.sortModel.length>1&&void 0!==r){const t=document.createElement("span");t.className="sort-index",t.textContent=String(r),i.nextSibling?e.insertBefore(t,i.nextSibling):e.appendChild(t)}}else e.classList.contains("sortable")&&this.updateSortIndicator(e,null)})}getSortModel(){return[...this.sortModel]}setSortModel(e){if(this.sortModel=[...e],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...e]}),this.requestRender(),this.grid?.requestStateChange?.(),e.length>0){const t=e.map(e=>{const t=this.columns.find(t=>t.field===e.field);return`${t?.header??e.field} ${"asc"===e.direction?"ascending":"descending"}`});o(this.gridElement,s(this.gridElement,"sortApplied",t.join(", then "),""))}}clearSort(){this.sortModel=[],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[]}),this.requestRender(),this.grid?.requestStateChange?.(),o(this.gridElement,s(this.gridElement,"sortCleared"))}getSortIndex(e){return gr(this.sortModel,e)}getSortDirection(e){return pr(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(this.#Ti||(this.#Ii=[...this.sortModel]),t.sort){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)}else this.sortModel=this.sortModel.filter(t=>t.field!==e);this.clearCoreSortState(),this.#Ti||(this.#Ti=!0,queueMicrotask(()=>{this.#Ti=!1;const e=this.#Ii;this.#Ii=[],function(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i].field!==t[i].field||e[i].direction!==t[i].direction)return!1;return!0}(e,this.sortModel)||(this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender())}))}},e.PinnedColumnsPlugin=class extends ${static manifest={hookPriority:{processColumns:-10},ownedProperties:[{property:"pinned",level:"column",description:'the "pinned" column property',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e}],queries:[{type:Sr,description:"Prevents pinned columns from being moved/reordered"},{type:"getStickyOffsets",description:"Returns the 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;#Li={addGroupEnd:new Set,removeGroupEnd:new Set};#Pi=[];#Di=[];detach(){this.leftOffsets.clear(),this.rightOffsets.clear(),this.isApplied=!1,this.#Li={addGroupEnd:new Set,removeGroupEnd:new Set},this.#Pi=[],this.#Di=[]}static detect(e,t){const i=t?.columns;return!!Array.isArray(i)&&vr(i)}processColumns(e){const t=[...e];if(this.isApplied=vr(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=fr(o);e?"left"===wr(e,t)?i.push(o):n.push(o):r.push(o)}return[...i,...r,...n]}(t,i?me(i):"ltr")}afterRender(){if(!this.isApplied)return;const e=this.gridElement,t=[...this.columns];if(!vr(t))return Er(e),void(this.isApplied=!1);queueMicrotask(()=>{const i=yr(e,t);this.#Li=i.groupEndAdjustments,this.leftOffsets=i.leftOffsets,this.rightOffsets=i.rightOffsets,this.#Pi=i.splitGroups,this.#Fi()})}afterCellRender(e){if(!this.isApplied)return;const t=e.column.field,i=e.cellElement,r=this.leftOffsets.get(t);if(void 0!==r)i.classList.contains(R.STICKY_LEFT)||i.classList.add(R.STICKY_LEFT),i.style.position="sticky",i.style.left=r+"px";else{const e=this.rightOffsets.get(t);void 0!==e&&(i.classList.contains(R.STICKY_RIGHT)||i.classList.add(R.STICKY_RIGHT),i.style.position="sticky",i.style.right=e+"px")}this.#Li.addGroupEnd.has(t)?e.cellElement.classList.add("group-end"):this.#Li.removeGroupEnd.has(t)&&e.cellElement.classList.remove("group-end")}onScroll(e){this.#Fi()}#Fi(){if(!this.isApplied||0===this.#Pi.length)return;const e=this.gridElement;for(const t of this.#Pi){const i=t.pinnedFragment.getBoundingClientRect(),r=t.scrollableFragment.getBoundingClientRect().right<=i.right;if(r&&!t.isTransferred?(t.pinnedFragment.textContent=t.label,t.pinnedFragment.style.overflow="hidden",t.pinnedFragment.style.textOverflow="ellipsis",t.pinnedFragment.style.whiteSpace="nowrap",t.pinnedFragment.style.borderRightStyle="",t.floatLabel.style.visibility="hidden",t.floatLabel.style.transform="",t.floatOffset=0,this.#Li.addGroupEnd.add(t.pinnedField),e.querySelectorAll(`.header-row .cell[data-field="${t.pinnedField}"], .data-grid-row .cell[data-field="${t.pinnedField}"]`).forEach(e=>e.classList.add("group-end")),t.isTransferred=!0):!r&&t.isTransferred&&(t.pinnedFragment.textContent="",t.pinnedFragment.style.overflow="",t.pinnedFragment.style.textOverflow="",t.pinnedFragment.style.whiteSpace="",t.pinnedFragment.style.borderRightStyle="none",t.floatLabel.style.visibility="",t.floatLabel.style.transform="",t.floatOffset=0,this.#Li.addGroupEnd.delete(t.pinnedField),e.querySelectorAll(`.header-row .cell[data-field="${t.pinnedField}"], .data-grid-row .cell[data-field="${t.pinnedField}"]`).forEach(e=>e.classList.remove("group-end")),t.isTransferred=!1),!t.isTransferred){const e=t.floatLabel.getBoundingClientRect().left-t.floatOffset,r=i.left;e<r?(t.floatOffset=r-e,t.floatLabel.style.transform=`translateX(${t.floatOffset}px)`):(t.floatOffset=0,t.floatLabel.style.transform="")}}}handleQuery(e){switch(e.type){case Sr:return null==fr(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.lockPinning||i.meta?.lockPinning)return;const r=[];return null!=fr(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.#Di.length&&(this.#Di=i.map(e=>e.field));const r=i.map(i=>{if(i.field!==e)return i;const r={...i};return r.pinned=t,r});n.columns=r}else{const t={...i[r]};delete t.pinned;const o=[...i];o.splice(r,1);const s=this.#Di.indexOf(e);if(s>=0){let e=o.length;for(let t=0;t<o.length;t++){if(fr(o[t]))continue;if(this.#Di.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!=fr(e))||(this.#Di=[]),n.columns=o}}refreshStickyOffsets(){const e=[...this.columns],t=yr(this.gridElement,e);this.#Li=t.groupEndAdjustments,this.leftOffsets=t.leftOffsets,this.rightOffsets=t.rightOffsets,this.#Pi=t.splitGroups}getLeftPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>mr(e,t))}([...this.columns],me(this.gridElement))}getRightPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>br(e,t))}([...this.columns],me(this.gridElement))}clearStickyPositions(){Er(this.gridElement)}getHorizontalScrollOffsets(e,t){if(!this.isApplied)return;let i=0,r=0;if(e){const t=e.querySelectorAll(`.${R.STICKY_LEFT}`),n=e.querySelectorAll(`.${R.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(R.STICKY_LEFT)?i+=e.offsetWidth:e.classList.contains(R.STICKY_RIGHT)&&(r+=e.offsetWidth)})}const n=t?.classList.contains(R.STICKY_LEFT)||t?.classList.contains(R.STICKY_RIGHT);return{left:i,right:r,skipScroll:n}}},e.PinnedRowsPlugin=class extends ${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=Pr(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=Ar("top");const i=e.querySelector(".header");i&&i.nextSibling?t.insertBefore(this.topAggregationContainer,i.nextSibling):t.appendChild(this.topAggregationContainer)}kr(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=_r(this.config,n);this.infoBarElement.replaceWith(e),this.infoBarElement=e}else this.infoBarElement=_r(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=Ar("bottom")),this.footerWrapper.appendChild(this.bottomAggregationContainer),kr(this.bottomAggregationContainer,l,this.visibleColumns,this.sourceRows,this.config.fullWidth)),d&&(this.infoBarElement=_r(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 Pr(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=Zr,e.PluginEvents={SELECTION_CHANGE:"selection-change",TREE_EXPAND:"tree-expand",TREE_LOAD_START:"tree-load-start",TREE_LOAD_END:"tree-load-end",TREE_LOAD_ERROR:"tree-load-error",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=Bt,e.PrintPlugin=class extends ${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}}}";#Hi=!1;#Gi=null;#Oi=null;#Ni=null;#qi=null;#zi=null;#$i=null;get#At(){return this.grid}isPrinting(){return this.#Hi}async print(e){if(this.#Hi)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={...en,...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.#Hi=!0;const s=performance.now();this.emit("print-start",{rowCount:n,limitApplied:o,originalRowCount:r});try{const e=this.#At;this.#Oi={bypassThreshold:e._virtualization?.bypassThreshold??24},this.#Bi(),o&&(this.#Ni=this.sourceRows,this.grid.rows=this.sourceRows.slice(0,n),await new Promise(e=>setTimeout(e,50))),(i.includeTitle||i.includeTimestamp)&&this.#Wi(i),await this.#Ki(),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.#Vi(i):await this.#ji(),this.emit("print-complete",{success:!0,rowCount:n,duration:Math.round(performance.now()-s)})}catch(l){w("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.#Ui(),this.#Hi=!1}}#Wi(e){const t=this.gridElement;if(t){if(this.#qi=document.createElement("div"),this.#qi.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.#qi.appendChild(i)}if(e.includeTimestamp){const e=document.createElement("div");e.className="tbw-print-header-timestamp",e.textContent=`Printed: ${(new Date).toLocaleString()}`,this.#qi.appendChild(e)}t.insertBefore(this.#qi,t.firstChild),this.#zi=document.createElement("div"),this.#zi.className="tbw-print-footer",this.#zi.textContent=`Page generated from ${window.location.hostname}`,t.appendChild(this.#zi)}}async#Ki(){const e=this.#At;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#ji(){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#Vi(e){const t=this.gridElement;t&&await Jr(t,{orientation:e.orientation})}#Bi(){const e=this.columns;if(e){this.#Gi=new Map;for(const t of e){if(!t.field)continue;(!0===t.printHidden||!0===t.utility&&!1!==t.printHidden)&&(this.#Gi.set(t.field,!t.hidden),this.grid.setColumnVisible(t.field,!1))}}}#Yi(){if(this.#Gi){for(const[e,t]of this.#Gi)this.grid.setColumnVisible(e,t);this.#Gi=null}}#Ui(){const e=this.gridElement;if(!e)return;this.#Yi(),e.classList.remove("print-portrait","print-landscape"),null!==this.#$i&&(e.style.transform="",e.style.transformOrigin="",e.style.width="",this.#$i=null),this.#qi&&(this.#qi.remove(),this.#qi=null),this.#zi&&(this.#zi.remove(),this.#zi=null);const t=this.#At;this.#Oi&&t._virtualization&&(t._virtualization.bypassThreshold=this.#Oi.bypassThreshold,t.refreshVirtualWindow(!0),this.#Oi=null),null!==this.#Ni&&(this.grid.rows=this.#Ni,this.#Ni=null)}afterRender(){this.config?.button&&!this.#Xi&&(this.#Zi(),this.#Xi=!0)}#Xi=!1;#Zi(){const e=this.#At;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",this.setIcon(t,"print"),t.addEventListener("click",()=>{this.print()},{signal:this.disconnectSignal}),e.appendChild(t)}})}},e.ROW_DRAG_HANDLE_FIELD=mn,e.RenderPhase=de,e.ReorderPlugin=class extends ${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}}';static manifest={queries:[{type:nn,description:"Authoritative check for whether a column may be reordered (honors lockPosition)."}]};handleQuery(e){if(e.type===nn){const t=e.context;return t?tn(t):void 0}}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#At(){return this.grid}canMoveColumnWithPlugins(e){if(!e||!tn(e))return!1;return!this.grid.query(nn,e).includes(!1)}clearDragClasses(){this.gridElement?.querySelectorAll(".header-row > .cell, .header-group-row > .cell").forEach(e=>{e.classList.remove(R.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(R.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(R.DRAGGING);else this.draggedField&&this.gridElement?.querySelector(`.header-row > .cell[data-field="${this.draggedField}"]`)?.classList.add(R.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=rn(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(R.DRAGGING);for(const i of n)e.querySelector(`.header-row > .cell[data-field="${i}"]`)?.classList.add(R.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=rn(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.#At,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,De(this.#At),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=rn(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 ${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"}]};#ne;#Qi=!1;#Ji;#er=!1;#tr=0;#ir=new Set;#rr=new Set;#nr=null;#or=[];get#At(){return this.grid}isResponsive(){return this.#Qi}setResponsive(e){e!==this.#Qi&&(this.#Qi=e,this.#sr(),this.emit("responsive-change",{isResponsive:e,width:this.#tr,breakpoint:this.config.breakpoint??0}),this.requestRender())}setBreakpoint(e){this.config.breakpoint=e,this.#lr(this.#tr)}setCardRenderer(e){this.config.cardRenderer=e,this.#Qi&&this.requestRender()}getWidth(){return this.#tr}getActiveBreakpoint(){return this.#nr}attach(e){super.attach(e),this.#ar(),this.#dr(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#or=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#ne=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#tr=t,clearTimeout(this.#Ji),this.#Ji=setTimeout(()=>{this.#lr(t)},this.config.debounceMs??100)}),this.#ne.observe(this.gridElement)}#ar(){const e=this.gridElement;if(!e)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const i=this.#At.__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=F(G(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})}#dr(e){if(this.#ir.clear(),this.#rr.clear(),e)for(const t of e)"string"==typeof t?this.#ir.add(t):t.showValue?this.#rr.add(t.field):this.#ir.add(t.field)}detach(){this.#ne?.disconnect(),this.#ne=void 0,clearTimeout(this.#Ji),this.#Ji=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#Qi}afterRender(){this.#cr();if(!(this.#or.length>0?null!==this.#nr:this.#Qi))return;const e=this.#ir.size>0,t=this.#rr.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.#ir.has(e)?(r.setAttribute("data-responsive-hidden",""),r.removeAttribute("data-responsive-value-only")):this.#rr.has(e)?(r.setAttribute("data-responsive-value-only",""),r.removeAttribute("data-responsive-hidden")):(r.removeAttribute("data-responsive-hidden"),r.removeAttribute("data-responsive-value-only")))}}#lr(e){if(this.#or.length>0)return void this.#ur(e);const t=this.config.breakpoint??0;0!==t||this.#er||(this.#er=!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.#Qi&&(this.#Qi=i,this.#sr(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#ur(e){let t=null;for(const i of this.#or)e<=i.maxWidth&&(t=i);if(t!==this.#nr){this.#nr=t,t?.hiddenColumns?this.#dr(t.hiddenColumns):this.#dr(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#Qi&&(this.#Qi=i,this.#sr()),this.emit("responsive-change",{isResponsive:this.#Qi,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#hr;#sr(){this.gridElement.toggleAttribute("data-responsive",this.#Qi);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.#At;if(this.#Qi){t._virtualization&&(this.#hr=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.#hr&&this.#hr>0&&t._virtualization&&(t._virtualization.rowHeight=this.#hr,this.#hr=void 0),this.#gr=void 0,this.#pr=void 0,this.#fr=void 0}}renderRow(e,t,i){if(!this.#Qi||!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.#wr()}px`,t.appendChild(r),!0}onKeyDown(e){if(!this.#Qi)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(),De(this.#At),!0;if(this.grid._focusRow<t)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),De(this.#At),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),De(this.#At),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=i,e.preventDefault(),De(this.#At),!0;break;case"ArrowRight":if(this.grid._focusRow<t)return this.grid._focusRow+=1,e.preventDefault(),De(this.#At),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),De(this.#At),!0}return!1}#gr;#pr;#fr;#wr(){if(this.#gr&&this.#gr>0)return this.#gr;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#mr(){return this.#pr&&this.#pr>0?this.#pr:this.#hr??28}#br(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}getRowHeight(e,t){if(this.#Qi&&this.config.cardRenderer)return e.__isGroupRow?this.#mr():this.#wr()}#vr(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#yr=!1;#cr(){if(!this.#Qi)return;let e=!1;const t=this.#At,i=this.#br(),r=this.#vr();if(r!==this.#fr&&(this.#fr=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.#pr&&(this.#pr=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.#gr&&(this.#gr=r,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=r))}e&&!this.#yr&&(this.#yr=!0,queueMicrotask(()=>{this.#yr=!1,this.grid&&this.#Qi&&this.#At.refreshVirtualWindow?.(!0,!0)}))}},e.RowDragDropPlugin=Cn,e.RowReorderPlugin=Cn,e.SelectionPlugin=class extends ${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:26}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.row-focus>.cell.sticky-left,tbw-grid .data-grid-row.row-focus>.cell.sticky-right{background:linear-gradient(var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0),var(--tbw-color-panel-bg)}tbw-grid .data-grid-row.row-focus[data-selectable=false]>.cell.sticky-left,tbw-grid .data-grid-row.row-focus[data-selectable=false]>.cell.sticky-right{background:var(--tbw-color-row-alt)}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;announceTimer=null;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-change",()=>this.clearSelectionSilent()),this.on("group-toggle",()=>this.clearSelectionSilent()),this.on("tree-expand",()=>this.clearSelectionSilent()),this.on("sort-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(){const e=this.gridElement?.querySelector(".rows-body");e?.removeAttribute("aria-multiselectable"),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&&Bi(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.#Cr()),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?.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.#Cr()),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=An(this.cellAnchor,{row:t,col:i}),r=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(r&&kn(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&&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.#Cr()),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.#Cr()),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.#Cr()),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&&Bi(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&&kn(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.#Cr()),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&&Bi(i)){const e=this.visibleColumns.findIndex(e=>!Bi(e));e>=0&&(t=e)}const r=An(this.cellAnchor,{row:e.rowIndex,col:t}),n=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return n&&kn(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.#Cr()),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.#xr(),i=e.findIndex($i),r=i>=0?i+1:0;return[...e.slice(0,r),t,...e.slice(r)]}return e}#xr(){return{field:Tn,header:"",width:32,resizable:!1,sortable:!1,lockPosition:!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}}}#Rr(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const t=e.closest(".cell"),i=t?fe(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}}#Er(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.#Cr()))))}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.#Cr()))}}}#Sr(){const e=this.gridElement;if(!e)return;const{mode:t}=this.config,i=!!this.config.isSelectable,r=e.querySelector(".rows-body");if(r){const e=!1!==this.config.multiSelect;r.setAttribute("aria-multiselectable",e?"true":"false")}e.querySelectorAll(".cell").forEach(e=>{e.classList.remove(R.SELECTED,"top","bottom","first","last"),i&&e.removeAttribute("data-selectable")});const n=e.querySelectorAll(".data-grid-row");if(n.forEach(e=>{e.classList.remove(R.SELECTED,"row-focus"),e.setAttribute("aria-selected","false"),i&&e.removeAttribute("data-selectable")}),"row"===t&&(we(e),n.forEach(e=>{const t=fe(e.querySelector(".cell[data-row]"));t>=0&&(i&&!this.isRowSelectable(t)&&e.setAttribute("data-selectable","false"),this.selected.has(t)&&(e.classList.add(R.SELECTED,"row-focus"),e.setAttribute("aria-selected","true")))}),this.config.checkbox&&this.#Rr(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){we(e);const t=this.ranges.map(xn),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&&Bi(n))return;i(t,r)&&(e.classList.add(R.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.#Cr())}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.#Cr())}this.#Er(i),this.gridElement.setAttribute("data-selection-mode",i),t&&t.classList.toggle("selecting",this.isDragging),this.#Sr()}onScrollRender(){this.isSelectionEnabled()&&this.#Sr()}getSelection(){return{mode:this.config.mode,ranges:this.#Cr().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.#Cr()),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.#Cr()),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.#Cr()),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:En(this.ranges)}),this.requestAfterRender()}#Cr(){const e=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:En(t.ranges)}:{mode:e,ranges:[]}}(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length);return this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=setTimeout(()=>{const t="row"===e.mode?this.selected.size:e.ranges.length;t>0&&o(this.gridElement,s(this.gridElement,"selectionChanged",t))},150),e}},e.ServerSidePlugin=class extends ${static manifest={modifiesRowStructure:!0,hookPriority:{processRows:-10},incompatibleWith:[{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."}],events:[{type:"datasource:data",description:"Root data page/block loaded"},{type:"datasource:children",description:"Child data loaded for a parent context"},{type:"datasource:loading",description:"Loading state changed"},{type:"datasource:error",description:"Fetch operation failed"}],queries:[{type:"datasource:fetch-children",description:"Request child rows for a parent context"},{type:"datasource:is-active",description:"Check if ServerSide plugin has an active data source"}]};name="serverSide";get defaultConfig(){return{pageSize:100,cacheBlockSize:100,maxConcurrentRequests:2}}dataSource=null;totalNodeCount=0;infiniteScrollMode=!1;loadedBlocks=new Map;loadingBlocks=new Set;blockControllers=new Map;lastRequestId=0;scrollDebounceTimer;managedNodes=[];attach(e){super.attach(e),this.on("sort-change",()=>{"local"===this.config.sortMode?this.requestRender():this.onModelChange()}),this.on("filter-change",()=>{"local"===this.config.filterMode?this.requestRender():this.onModelChange()}),this.config.dataSource&&this.setDataSource(this.config.dataSource)}detach(){this.dataSource=null,this.totalNodeCount=0,this.infiniteScrollMode=!1,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.abortAllBlocks(),this.managedNodes=[],this.lastRequestId=0,this.scrollDebounceTimer&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=void 0)}abortAllBlocks(){for(const e of this.blockControllers.values())e.abort();this.blockControllers.clear()}getEnrichmentParams(){const e="local"===this.config.sortMode,t="local"===this.config.filterMode,i=e?void 0:this.grid?.query?.("sort:get-model",null),r=t?void 0:this.grid?.query?.("filter:get-model",null);let n=i?.[0];const o=this.grid;if(!e&&!n&&o?._sortState){const{field:e,direction:t}=o._sortState;n=[{field:e,direction:1===t?"asc":"desc"}]}return{sortModel:n,filterModel:r?.[0]}}getViewportMapping(e,t){const i={viewportStart:e,viewportEnd:t},r=this.grid?.query?.("datasource:viewport-mapping",i);return r?.[0]?r[0]:{startNode:e,endNode:t,totalLoadedNodes:this.totalNodeCount}}onModelChange(){this.dataSource&&(this.abortAllBlocks(),this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1,this.requestRender(),this.loadRequiredBlocks())}applyServerResult(e,t,i){void 0!==e.lastNode?(this.totalNodeCount=e.lastNode+1,this.infiniteScrollMode=!1):-1===e.totalNodeCount?this.infiniteScrollMode=!0:(this.totalNodeCount=e.totalNodeCount,this.infiniteScrollMode=!1),this.infiniteScrollMode&&e.rows.length<i&&(this.totalNodeCount=t*i+e.rows.length,this.infiniteScrollMode=!1)}getInfiniteScrollEstimate(e){let t=0;for(const[i,r]of this.loadedBlocks){const n=i*e+r.length;n>t&&(t=n)}return t+e}loadRequiredBlocks(){if(!this.dataSource)return;const e=this.grid,t=this.config.cacheBlockSize??100,i=this.getViewportMapping(e._virtualization.start,e._virtualization.end),r=Math.max(0,this.config.loadThreshold??0),n=Math.max(0,i.startNode-r),o=this.totalNodeCount>0?this.totalNodeCount:1/0,s=Math.min(o,i.endNode+r);if(s<=n)return;const l=function(e,t,i){const r=In(e,i),n=In(t-1,i),o=[];for(let s=r;s<=n;s++)o.push(s);return o}(n,s,t),a=this.getEnrichmentParams(),d=this.grid?.getAttribute?.("id")??void 0;for(const c of l){if(this.loadedBlocks.has(c)||this.loadingBlocks.has(c))continue;if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2)){f("TBW143","Concurrent request limit reached, deferring block load",d);break}this.loadingBlocks.add(c);const e=new AbortController;this.blockControllers.set(c,e),this.broadcast("datasource:loading",{loading:!0}),Ln(this.dataSource,c,t,a,e.signal).then(i=>{if(this.blockControllers.delete(c),e.signal.aborted)return this.loadingBlocks.delete(c),void(0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}));this.loadedBlocks.set(c,i.rows);const r=this.managedNodes.length;this.applyServerResult(i,c,t),this.loadingBlocks.delete(c);const n=c*t;for(let e=0;e<i.rows.length;e++)n+e<this.managedNodes.length&&(this.managedNodes[n+e]=i.rows[e]);const o={rows:i.rows,totalNodeCount:i.totalNodeCount,startNode:n,endNode:n+i.rows.length,claimed:!1};this.broadcast("datasource:data",o),0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1});0===r||this.managedNodes.length<(Number.isFinite(this.totalNodeCount)?this.totalNodeCount:0)?this.requestRender():this.requestVirtualRefresh(),this.loadRequiredBlocks()}).catch(t=>{if(this.blockControllers.delete(c),this.loadingBlocks.delete(c),e.signal.aborted)return void(0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}));const i=t instanceof Error?t:new Error(String(t));w(u,`getRows() failed: ${i.message}`,d),this.broadcast("datasource:error",{error:i}),0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1})})}}processRows(e){if(!this.dataSource)return[...e];const t=this.config.cacheBlockSize??100,i=this.infiniteScrollMode?this.getInfiniteScrollEstimate(t):Number.isFinite(this.totalNodeCount)&&this.totalNodeCount>=0?this.totalNodeCount:0;for(;this.managedNodes.length<i;){const e=this.managedNodes.length;this.managedNodes.push({__loading:!0,__index:e})}this.managedNodes.length=i;for(let n=0;n<i;n++){const e=Pn(n,t,this.loadedBlocks);e&&(this.managedNodes[n]=e)}const r=this.grid;if("local"===this.config.sortMode&&r?._sortState){const e=r._columns??[],t=(r.effectiveConfig?.sortHandler??V)(this.managedNodes,r._sortState,e);return t&&"function"==typeof t.then?(t.catch(()=>{}),this.managedNodes):t}return this.managedNodes}onScroll(e){this.dataSource&&(this.loadRequiredBlocks(),this.scrollDebounceTimer&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.loadRequiredBlocks()},100))}handleQuery(e){switch(e.type){case"datasource:is-active":return null!=this.dataSource;case"datasource:fetch-children":{const{context:t}=e.context;return void this.fetchChildren(t)}}}fetchChildren(e){if(!this.dataSource)return;const t=this.grid?.getAttribute?.("id")??void 0;if(!this.dataSource.getChildRows)return void p("TBW142",`Plugin "${e.source}" requested child rows but getChildRows() is not implemented on the dataSource`,t);const i=this.getEnrichmentParams();this.broadcast("datasource:loading",{loading:!0,context:e}),this.dataSource.getChildRows({context:e,sortModel:i.sortModel,filterModel:i.filterModel}).then(t=>{const i={rows:t.rows,context:e,claimed:!1};this.broadcast("datasource:children",i),this.broadcast("datasource:loading",{loading:!1,context:e})}).catch(i=>{const r=i instanceof Error?i:new Error(String(i));w("TBW141",`getChildRows() failed: ${r.message}`,t),this.broadcast("datasource:error",{error:r,context:e}),this.broadcast("datasource:loading",{loading:!1,context:e})})}setDataSource(e){this.abortAllBlocks(),this.dataSource=e,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1;const t=this.config.cacheBlockSize??100,i=this.getEnrichmentParams(),r=this.grid?.getAttribute?.("id")??void 0,n=new AbortController;this.blockControllers.set(0,n),this.loadingBlocks.add(0),this.broadcast("datasource:loading",{loading:!0}),Ln(e,0,t,i,n.signal).then(e=>{if(this.blockControllers.delete(0),this.loadingBlocks.delete(0),n.signal.aborted)return void this.broadcast("datasource:loading",{loading:!1});this.loadedBlocks.set(0,e.rows),this.applyServerResult(e,0,t);const i={rows:e.rows,totalNodeCount:e.totalNodeCount,startNode:0,endNode:e.rows.length,claimed:!1};this.broadcast("datasource:data",i),this.broadcast("datasource:loading",{loading:!1}),this.requestRender(),(this.config.loadThreshold??0)>0&&this.loadRequiredBlocks()}).catch(e=>{if(this.blockControllers.delete(0),this.loadingBlocks.delete(0),n.signal.aborted)return void this.broadcast("datasource:loading",{loading:!1});const t=e instanceof Error?e:new Error(String(e));w(u,`getRows() failed: ${t.message}`,r),this.broadcast("datasource:error",{error:t}),this.broadcast("datasource:loading",{loading:!1})})}refresh(){if(!this.dataSource)return;const e=this.dataSource;this.abortAllBlocks(),this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1,this.setDataSource(e)}purgeCache(){this.abortAllBlocks(),this.loadedBlocks.clear(),this.managedNodes=[]}getTotalNodeCount(){return this.totalNodeCount}getTotalRowCount(){return this.totalNodeCount}isNodeLoaded(e){const t=In(e,this.config.cacheBlockSize??100);return this.loadedBlocks.has(t)}isRowLoaded(e){return this.isNodeLoaded(e)}getLoadedBlockCount(){return this.loadedBlocks.size}},e.TooltipPlugin=class extends ${name="tooltip";styles='@layer tbw-plugins{.tbw-tooltip-popover{margin:0;padding:var(--tbw-tooltip-padding, var(--tbw-spacing-sm, .375rem) var(--tbw-spacing-md, .5rem));background:var(--tbw-tooltip-bg, light-dark(#333338, #484850));color:var(--tbw-tooltip-fg, light-dark(#f5f5f5, #f0f0f0));border:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72));border-radius:var(--tbw-tooltip-radius, var(--tbw-border-radius, .25rem));box-shadow:none;filter:var(--tbw-tooltip-shadow, drop-shadow(0 4px 4px rgba(0, 0, 0, .45)));font-family:var(--tbw-font-family, system-ui, sans-serif);font-size:var(--tbw-tooltip-font-size, var(--tbw-font-size-sm, .9285em));max-width:var(--tbw-tooltip-max-width, 300px);white-space:pre-line;word-wrap:break-word;overflow-wrap:break-word;pointer-events:none;z-index:10001}.tbw-tooltip-popover:after{content:"";position:absolute;width:var(--tbw-tooltip-arrow-size, 14px);height:var(--tbw-tooltip-arrow-size, 14px);left:var(--tbw-tooltip-arrow-offset, 16px);background:inherit;pointer-events:none}.tbw-tooltip-popover:not(.tbw-tooltip-above):after{top:calc(var(--tbw-tooltip-arrow-size, 14px) / -2);transform:rotate(45deg);border-top:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72));border-left:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72))}.tbw-tooltip-popover.tbw-tooltip-above:after{bottom:calc(var(--tbw-tooltip-arrow-size, 14px) / -2);transform:rotate(45deg);border-bottom:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72));border-right:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72))}@supports (anchor-name: --test){.tbw-tooltip-popover{position-anchor:--tbw-tooltip-anchor;top:calc(anchor(bottom) + 11px);left:anchor(left);position-try-fallbacks:--tbw-tooltip-flip-above}@position-try --tbw-tooltip-flip-above{top:auto;bottom:calc(anchor(top) + 11px)}}}';static manifest={ownedProperties:[{property:"cellTooltip",level:"column",description:'the "cellTooltip" column property'},{property:"headerTooltip",level:"column",description:'the "headerTooltip" column property'}],configRules:[]};#_r=null;#Ar=null;#kr=!1;get#Tr(){return!1!==this.config.header}get#Ir(){return!1!==this.config.cell}attach(e){super.attach(e)}detach(){this.#Mr(),this.#_r?.remove(),this.#_r=null,this.#kr=!1,super.detach()}afterRender(){this.#Lr(),this.#Pr()}#Lr(){if(this.#_r)return;const e=document.createElement("div");e.className="tbw-tooltip-popover",e.setAttribute("popover","hint"),e.style.overflow="visible",e.style.margin="0",document.body.appendChild(e),this.#_r=e}#Dr(e,t){if(this.#_r){if(this.#Fr(),e.style.setProperty("anchor-name","--tbw-tooltip-anchor"),this.#Ar=e,this.#_r.textContent=t,Fn())try{this.#_r.showPopover()}catch{}"undefined"!=typeof CSS&&!0===CSS.supports?.("anchor-name","--test")?requestAnimationFrame(()=>this.#Hr(e)):this.#Gr(e)}}#Mr(){if(this.#_r){if(Fn())try{this.#_r.hidePopover()}catch{}this.#_r.classList.remove("tbw-tooltip-above")}this.#Fr()}#Fr(){this.#Ar&&("--tbw-tooltip-anchor"===this.#Ar.style.getPropertyValue("anchor-name")&&this.#Ar.style.removeProperty("anchor-name"),this.#Ar=null)}#Gr(e){if(!this.#_r)return;const t=e.getBoundingClientRect();this.#_r.style.position="fixed",this.#_r.style.left=`${t.left}px`;window.innerHeight-t.bottom<80?(this.#_r.style.top="",this.#_r.style.bottom=window.innerHeight-t.top+11+"px",this.#_r.classList.add("tbw-tooltip-above")):(this.#_r.style.top=`${t.bottom+11}px`,this.#_r.style.bottom="",this.#_r.classList.remove("tbw-tooltip-above"))}#Hr(e){if(!this.#_r)return;const t=e.getBoundingClientRect(),i=this.#_r.getBoundingClientRect();this.#_r.classList.toggle("tbw-tooltip-above",i.bottom<=t.top)}#Pr(){if(this.#kr)return;const e=this.gridElement?.querySelector(".tbw-grid-root");e&&(this.#kr=!0,e.addEventListener("mouseover",e=>this.#Or(e),{signal:this.disconnectSignal}),e.addEventListener("mouseout",e=>this.#Nr(e),{signal:this.disconnectSignal}))}#Or(e){const t=e.target;if(!t?.closest)return;const i=t.closest('[part~="header-cell"]');if(i&&this.#Tr)return void this.#qr(i);const r=t.closest("[data-row][data-col]");r&&this.#Ir&&!r.style.getPropertyValue("anchor-name")&&this.#zr(r)}#Nr(e){const t=e.target;if(!t?.closest)return;const i=t.closest('[part~="header-cell"], [data-row][data-col]');if(!i)return;const r=e.relatedTarget;r&&i.contains(r)||this.#Mr()}#qr(e){const t=parseInt(e.getAttribute("data-col")??"-1",10);if(t<0)return;const i=this.visibleColumns[t];if(!i)return;const r=function(e,t){const i=e.headerTooltip;if(!1===i)return null;if("string"==typeof i)return i;if("function"==typeof i)return i({column:e,value:e.header??e.field});const r=t.querySelector("span:first-child")??t;return Dn(r)&&r.textContent?.trim()||null}(i,e);r&&this.#Dr(e,r)}#zr(e){const t=parseInt(e.getAttribute("data-row")??"-1",10),i=parseInt(e.getAttribute("data-col")??"-1",10);if(t<0||i<0)return;const r=this.visibleColumns[i];if(!r)return;const n=this.rows[t],o=n?.[r.field],s=function(e,t,i,r,n){const o=e.cellTooltip;if(!1===o)return null;if("string"==typeof o)return o;if("function"==typeof o)return o({value:r,row:i,column:e,field:e.field,grid:n});return Dn(t)&&t.textContent?.trim()||null}(r,e,n,o,this.grid);s&&this.#Dr(e,s)}},e.TreePlugin=class extends ${static manifest={modifiesRowStructure:!0,hookPriority:{processRows:10},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."}],events:[{type:"tree-expand",description:"Emitted when tree expansion state changes (toggle, expand all, collapse all). Broadcast to both DOM consumers and plugin bus."}],queries:[{type:"canMoveRow",description:"Returns false for rows with children (parent nodes cannot be reordered)"},{type:"datasource:viewport-mapping",description:"Translates flat viewport row indices to top-level node indices for ServerSide pagination."}]};static dependencies=[{name:"multiSort",required:!1,reason:"Queries sort model for coordinated tree sorting"},{name:"serverSide",required:!1,reason:"Consumes datasource events for lazy-loaded tree data"}];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;vertical-align:middle;overflow:visible;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);height: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}}tbw-grid.tbw-tree-loading .rows-viewport:after{content:"";display:block;height:2px;background:linear-gradient(90deg,transparent,var(--tbw-color-accent, #2563eb),transparent);animation:tbw-tree-loading-bar 1s ease-in-out infinite;position:sticky;bottom:0;left:0;right:0}@keyframes tbw-tree-loading-bar{0%{transform:translate(-100%)}to{transform:translate(100%)}}}';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;loadingKeys=new Set;#$r=new WeakMap;#Br=new WeakMap;originalTreeColumnRenderer;wrappedTreeColumnField;detach(){this.expandedKeys.clear(),this.initialExpansionDone=!1,this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.sortState=null,this.loadingKeys.clear(),this.originalTreeColumnRenderer=void 0,this.wrappedTreeColumnField=void 0}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}if("datasource:viewport-mapping"===e.type){const{viewportStart:t,viewportEnd:i}=e.context;if(0===this.flattenedRows.length)return;return{startNode:zn(this.flattenedRows,t),endNode:zn(this.flattenedRows,i)+1,totalLoadedNodes:function(e){let t=0;for(const i of e)0===i.depth&&t++;return t}(this.flattenedRows)}}}attach(e){super.attach(e),this.on("datasource:data",e=>{const t=e;t.claimed||(t.claimed=!0)}),this.on("datasource:children",e=>{const t=e;if("tree"!==t.context?.source)return;t.claimed=!0;const i=t.context.parentNode;if(i){i[this.config.childrenField??"children"]=t.rows;const e=this.#$r.get(i)??String(i.id??"?");this.loadingKeys.delete(e),this.requestRender()}})}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 $n(t,i)}processRows(e){const t=this.config.childrenField??"children",i=e;if(0===i.length||!$n(i,t))return this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),[...e];const r=this.resolveEffectiveSortState();this.config.defaultExpanded&&!this.initialExpansionDone&&(this.expandedKeys=On(i,this.config),this.initialExpansionDone=!0),this.flattenedRows=this.#Wr(i,this.expandedKeys,r,null,0),this.#Br=new WeakMap,this.rowKeyMap.clear(),this.keysToAnimate.clear();const n=new Set;for(const o of this.flattenedRows)this.rowKeyMap.set(o.key,o),this.#Br.set(o.data,o),n.add(o.key),!this.previousVisibleKeys.has(o.key)&&o.depth>0&&this.keysToAnimate.add(o.key);return this.previousVisibleKeys=n,this.flattenedRows.map(e=>e.data)}#Kr(e,t,i){if(void 0!==e.id){const t=String(e.id);return this.#$r.set(e,t),t}const r=this.#$r.get(e);if(void 0!==r)return r;const n=i?`${i}-${t}`:String(t);return this.#$r.set(e,n),n}#Wr(e,t,i,r,n){const o=this.config.childrenField??"children";for(let a=0;a<e.length;a++)this.#Kr(e[a],a,r);const s=i?this.#Vr(e,i.field,i.direction):e,l=[];for(let a=0;a<s.length;a++){const e=s[a],d=this.#Kr(e,a,r),c=e[o],u=Array.isArray(c)&&c.length>0,h=null!=c&&!Array.isArray(c)&&!!c,g=u||h,p=t.has(d);l.push({key:d,data:e,depth:n,hasChildren:g,isExpanded:p,parentKey:r}),u&&p&&l.push(...this.#Wr(c,t,i,d,n+1))}return l}#Vr(e,t,i){const r=this.grid,n=r?._columns??[],o={field:t,direction:i},s=[...e],l=(r?.effectiveConfig?.sortHandler??V)(s,o,n);return l&&"function"==typeof l.then?(l.catch(()=>{}),V(s,o,n)):l}requestLazyChildren(e){if(this.loadingKeys.has(e.key))return;const t=this.config.childrenField??"children",i=e.data[t];if(Array.isArray(i)&&i.length>0)return;const r=this.grid?.query?.("datasource:is-active",null);r&&(this.loadingKeys.add(e.key),this.grid.query("datasource:fetch-children",{context:{source:"tree",parentNode:e.data,nodePath:[e.key]}}))}resolveEffectiveSortState(){const e=this.grid?.query?.("sort:get-model",null);if(Array.isArray(e)&&e.length>0){const t=e[0];if(Array.isArray(t)&&t.length>0)return{field:t[0].field,direction:"desc"===t[0].direction?-1:1}}return this.sortState}processColumns(e){if(0===this.flattenedRows.length)return[...e];const t=[...e];if(0===t.length)return t;const{treeColumn:i}=this.config;let r=0;if(i){const e=t.findIndex(e=>e.field===i);e>=0&&(r=e)}const n=t[r],o=n.field;this.wrappedTreeColumnField!==o&&(this.originalTreeColumnRenderer=n.viewRenderer,this.wrappedTreeColumnField=o);const s=this.originalTreeColumnRenderer,l=()=>this.config,a=this.setIcon.bind(this);return t[r]={...n,viewRenderer:e=>{const{row:t,value:i}=e,{showExpandIcons:r=!0,indentWidth:n}=l(),o=this.#Br.get(t),d=o?.depth??0,c=document.createElement("span");if(c.className="tree-cell-wrapper",c.style.setProperty("--tbw-tree-depth",String(d)),void 0!==n&&c.style.setProperty("--tbw-tree-indent-width",`${n}px`),r)if(o&&o.hasChildren){const e=document.createElement("span");e.className=`${R.TREE_TOGGLE}${o.isExpanded?` ${R.EXPANDED}`:""}`,a(e,o.isExpanded?"collapse":"expand"),e.setAttribute("data-tree-key",o.key),c.appendChild(e)}else{const e=document.createElement("span");e.className="tree-spacer",c.appendChild(e)}const u=document.createElement("span");if(u.className="tree-content",s){const t=s(e);t instanceof Node?u.appendChild(t):"string"==typeof t&&(u.innerHTML=t)}else u.textContent=null!=i?String(i):"";return c.appendChild(u),c}},t}onCellClick(e){const t=e.originalEvent?.target;if(!t?.classList.contains(R.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=Gn(this.expandedKeys,i),this.expandedKeys.has(i)&&this.requestLazyChildren(r),this.broadcast("tree-expand",{key:i,row:r.data,expanded:this.expandedKeys.has(i),depth:r.depth,expandedKeys:[...this.expandedKeys]}),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=Gn(this.expandedKeys,i.key),this.expandedKeys.has(i.key)&&this.requestLazyChildren(i),this.broadcast("tree-expand",{key:i.key,row:i.data,expanded:this.expandedKeys.has(i.key),depth:i.depth,expandedKeys:[...this.expandedKeys]}),this.requestRenderWithFocus(),!0):void 0}onHeaderClick(e){if(0===this.flattenedRows.length||!e.column.sortable)return!1;const t=this.grid?.query?.("sort:get-model",null);if(Array.isArray(t)&&t.length>0)return!1;const{field:i}=e.column;this.sortState&&this.sortState.field===i?1===this.sortState.direction?this.sortState={field:i,direction:-1}:this.sortState=null:this.sortState={field:i,direction:1};const r=this.grid;return void 0!==r._sortState&&(r._sortState=this.sortState?{...this.sortState}:null),this.broadcast("sort-change",{field:i,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);const t=this.rowKeyMap.get(e);t&&this.requestLazyChildren(t),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}toggle(e){this.expandedKeys=Gn(this.expandedKeys,e);const t=this.rowKeyMap.get(e);t?(this.expandedKeys.has(e)&&this.requestLazyChildren(t),this.broadcast("tree-expand",{key:e,row:t.data,expanded:this.expandedKeys.has(e),depth:t.depth,expandedKeys:[...this.expandedKeys]})):this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}expandAll(){this.expandedKeys=On(this.rows,this.config),this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}getExpandedKeys(){return[...this.expandedKeys]}getFlattenedRows(){return[...this.flattenedRows]}getRowMeta(e){return this.#Br.get(e)}getRowByKey(e){return this.rowKeyMap.get(e)?.data}expandToKey(e){this.expandedKeys=qn(this.rows,e,this.config,this.expandedKeys),this.requestRender()}},e.UndoRedoPlugin=class extends ${static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];#jr=!1;#Ur=null;#Yr(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}}#Xr(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(R.EDITING)){const e=n.querySelector(Ce);e?.focus({preventScroll:!0})}}#Zr(e,t){if(this.#jr=!0,"compound"===e.type){const i="undo"===t?[...e.actions].reverse():e.actions;for(const e of i)this.#Yr(e,"undo"===t?e.oldValue:e.newValue)}else this.#Yr(e,"undo"===t?e.oldValue:e.newValue);this.#jr=!1}#Qr(e){const t="compound"===e.type?e.actions[e.actions.length-1]:e;t&&this.#Xr(t)}attach(e){super.attach(e),this.on("cell-edit-committed",e=>{this.#jr||this.recordEdit(e.rowIndex,e.field,e.oldValue,e.newValue)})}detach(){this.undoStack=[],this.redoStack=[],this.#Ur=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=Wn({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#Zr(t.action,"undo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.emit("undo",{action:t.action,type:"undo"}),this.#Qr(t.action),this.requestRenderWithFocus()),!0}if(i){e.preventDefault();const t=Kn({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#Zr(t.action,"redo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.emit("redo",{action:t.action,type:"redo"}),this.#Qr(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.#Ur)return void this.#Ur.push(n);const o=Bn({undoStack:this.undoStack,redoStack:this.redoStack},n,this.config.maxHistorySize??100);this.undoStack=o.undoStack,this.redoStack=o.redoStack}beginTransaction(){this.#Ur&&g("TBW111","Transaction already in progress. Call endTransaction() first."),this.#Ur=[]}endTransaction(){const e=this.#Ur;if(e||g("TBW112","No transaction in progress. Call beginTransaction() first."),this.#Ur=null,0===e.length)return;const t=1===e.length?e[0]:{type:"compound",actions:e,timestamp:Date.now()};const i=Bn({undoStack:this.undoStack,redoStack:this.redoStack},t,this.config.maxHistorySize??100);this.undoStack=i.undoStack,this.redoStack=i.redoStack}undo(){const e=Wn({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#Zr(e.action,"undo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.#Qr(e.action),this.requestRenderWithFocus()),e.action}redo(){const e=Kn({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#Zr(e.action,"redo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.#Qr(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.#Ur=null}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}},e.VisibilityPlugin=Vn,e.builtInSort=V,e.createGrid=function(e){const t=document.createElement("tbw-grid");return e&&(t.gridConfig=e),t},e.defaultComparator=function(e,t){return null==e&&null==t?0:null==e?-1:null==t||e>t?1:e<t?-1:0},e.defaultEditorFor=hi,e.defaultPasteHandler=Ut,e.invalidateAccessorCache=K,e.printGridIsolated=Jr,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(Wt.tagName).then(()=>r.querySelector(e)):r.querySelector(e)},e.resolveCellValue=W,e.setFeatureResolver=function(e){Ne=e},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";const t={STRETCH:"stretch",FIXED:"fixed"},i={sortApplied:(e,t)=>`Sorted by ${e}, ${t}`,sortCleared:()=>"Sort cleared",filterApplied:e=>`Filter applied on ${e}`,filterCleared:e=>`Filter cleared from ${e}`,allFiltersCleared:()=>"All filters cleared",groupExpanded:(e,t)=>`Group ${e} expanded, ${t} rows`,groupCollapsed:e=>`Group ${e} collapsed`,selectionChanged:e=>`${e} rows selected`,editingStarted:e=>`Editing row ${e+1}`,editingCommitted:e=>`Row ${e+1} saved`,dataLoaded:e=>`${e} rows loaded`},r={mode:"reduced-motion",duration:200,easing:"ease-out"},n={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};function o(e,t){if(!e)return;const i="effectiveConfig"in e?e.effectiveConfig:void 0;if(!1===i?.a11y?.announcements)return;const r=e.querySelector?.(".tbw-sr-only");r&&(r.textContent="",requestAnimationFrame(()=>{r.textContent=t}))}function s(e,t,...r){const n=e&&"effectiveConfig"in e?e.effectiveConfig:void 0,o=n?.a11y?.messages?.[t];return o?o(...r):i[t](...r)}function l(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}const a="TBW041",d="TBW061",c="TBW062",u="TBW140";function h(e,t,i,r){return`${l(i,r)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}function g(e,t,i,r){throw new Error(h(e,t,i,r))}function p(e,t,i,r){console.warn(h(e,t,i,r))}function f(e,t,i,r){console.debug(h(e,t,i,r))}function w(e,t,i,r){console.error(h(e,t,i,r))}function m(e,t){if(!(e&&e.length||t&&t.length))return[];if(!e||!e.length)return t||[];if(!t||!t.length)return e;const i={},r=t;for(let s=0;s<r.length;s++){const e=r[s],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 n=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}),o=Object.keys(i);for(let s=0;s<o.length;s++)n.push(i[o[s]]);return n}function b(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 v(e){const i=e.effectiveConfig?.fitMode||e.fitMode||t.STRETCH;if(i!==t.STRETCH&&i!==t.FIXED)return;if(e.__didInitialAutoSize)return;if(!e.isConnected)return;const r=Array.from(e._headerRowEl?.children||[]);if(!r.length)return;let n=!1;const o=e._visibleColumns;for(let t=0;t<o.length;t++){const i=o[t];if(i.width)continue;const s=r[t];let l=s?s.scrollWidth:0;for(let r=0;r<e._rowPool.length;r++){const i=e._rowPool[r].children[t];if(i){const e=i.scrollWidth;e>l&&(l=e)}}l>0&&(i.width=l+2,i.__autoSized=!0,n=!0)}n&&x(e),e.__didInitialAutoSize=!0}const y=/^(?:\d+(?:\.\d+)?(?:px|%|fr|em|rem|ch|vw|vh|vmin|vmax)|calc\(.+\)|min-content|max-content|minmax\(.+\)|fit-content\(.+\)|auto)$/i;function C(e,t){return"number"==typeof e?`${e}px`:(y.test(e)||p("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 x(e){const i=e.effectiveConfig?.fitMode||e.fitMode||t.STRETCH;e._gridTemplate=i===t.STRETCH?e._visibleColumns.map(e=>{if(null!=e.width)return C(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?C(e.width,e.field):"max-content").join(" "),e.style.setProperty("--tbw-column-template",e._gridTemplate)}const R={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"},E={FIELD:"data-field",GROUP_KEY:"data-group-key"},S={ROOT:`.${R.ROOT}`,HEADER:`.${R.HEADER}`,HEADER_ROW:`.${R.HEADER_ROW}`,HEADER_CELL:`.${R.HEADER_CELL}`,ROWS_VIEWPORT:`.${R.ROWS_VIEWPORT}`,ROWS_CONTAINER:`.${R.ROWS_CONTAINER}`,DATA_ROW:`.${R.DATA_ROW}`,DATA_CELL:`.${R.DATA_CELL}`,GROUP_ROW:`.${R.GROUP_ROW}`,CELL_BY_FIELD:e=>`.${R.DATA_CELL}[${E.FIELD}="${e}"]`,SELECTED_ROWS:`.${R.DATA_ROW}.${R.SELECTED}`,EDITING_CELL:`.${R.DATA_CELL}.${R.EDITING}`},_=/{{\s*([^}]+)\s*}}/g,A="__DG_EMPTY__",k=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,T="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join("")),I=new RegExp(`__(proto|defineGetter|defineSetter)|${T.slice(3).join("|")}|this\\b`);const M=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".split("|")),L=/^on\w+$/i,P=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),D=/^\s*(javascript|vbscript|data|blob):/i;function F(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(M.has(e)){t.push(r);continue}if("svg"===e||"http://www.w3.org/2000/svg"===r.namespaceURI){if(Array.from(r.attributes).some(e=>L.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();L.test(e)?i.push(t.name):(P.has(e)&&D.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 H(e,t){const i=function(e){const t=[];let i=0;for(;i<e.length;){const r=e[i];if(" "!==r){if(r>="0"&&r<="9"||"."===r&&i+1<e.length&&e[i+1]>="0"&&e[i+1]<="9"){const r=i;for(;i<e.length&&(e[i]>="0"&&e[i]<="9"||"."===e[i]);)i++;t.push({type:"num",v:Number(e.slice(r,i))});continue}if("'"===r){let r="";for(i++;i<e.length&&"'"!==e[i];)r+=e[i++];if(i>=e.length)return null;i++,t.push({type:"str",v:r});continue}if(r>="a"&&r<="z"||r>="A"&&r<="Z"||"_"===r||"$"===r){const r=i;for(;i<e.length&&/[\w$.]/.test(e[i]);)i++;t.push({type:"id",v:e.slice(r,i)});continue}if(i+2<e.length){const r=e.slice(i,i+3);if("==="===r||"!=="===r){t.push({type:"op",v:r}),i+=3;continue}}if(i+1<e.length){const r=e.slice(i,i+2);if("=="===r||"!="===r||"<="===r||">="===r||"&&"===r||"||"===r){t.push({type:"op",v:r}),i+=2;continue}}if(!"+-*/%<>!?:(),".includes(r))return null;t.push({type:"op",v:r}),i++}else i++}return t}(e);if(!i)return;const r=i;let n=0;function o(){return r[n]}function s(){return r[n++]}function l(e,t){const i=o();return!!i&&(i.type===e&&(void 0===t||i.v===t))}function a(){const e=function(){let e=d();for(;l("op","||");)s(),e=e||d();return e}();if(l("op","?")){s();const t=a();if(!l("op",":"))return;s();const i=a();return e?t:i}return e}function d(){let e=c();for(;l("op","&&");)s(),e=e&&c();return e}function c(){let e=u();for(;;){const t=o();if(!t||"op"!==t.type)break;if("==="===t.v)s(),e=e===u();else if("!=="===t.v)s(),e=e!==u();else if("=="===t.v)s(),e=e==u();else{if("!="!==t.v)break;s(),e=e!=u()}}return e}function u(){let e=h();for(;;){const t=o();if(!t||"op"!==t.type)break;if("<"===t.v)s(),e=e<h();else if(">"===t.v)s(),e=e>h();else if("<="===t.v)s(),e=e<=h();else{if(">="!==t.v)break;s(),e=e>=h()}}return e}function h(){let e=g();for(;;){const t=o();if(!t||"op"!==t.type)break;if("+"===t.v)s(),e+=g();else{if("-"!==t.v)break;s(),e-=g()}}return e}function g(){let e=p();for(;;){const t=o();if(!t||"op"!==t.type)break;if("*"===t.v)s(),e*=p();else if("/"===t.v)s(),e/=p();else{if("%"!==t.v)break;s(),e%=p()}}return e}function p(){return l("op","!")?(s(),!p()):f()}function f(){const e=o();if(e){if("num"===e.type)return s(),e.v;if("str"===e.type)return s(),e.v;if("id"===e.type)return s(),function(e){if("value"===e)return t.value;if(e.startsWith("row.")){const i=e.slice(4);return t.row?t.row[i]:void 0}return"row"===e?t.row:void 0}(e.v);if("op"===e.type&&"("===e.v){s();const e=a();return l("op",")")&&s(),e}return"op"===e.type&&"-"===e.v?(s(),-f()):void 0}}const w=a();return n<r.length?void 0:w}function G(e,t){if(!e||-1===e.indexOf("{{"))return e;const i=[],r=e.replace(_,(e,r)=>{const n=function(e,t){if(e=(e||"").trim(),!e)return A;if(N.test(e))return A;if("value"===e)return null==t.value?A: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?A:String(r)}if(e.length>80)return A;if(!k.test(e)||I.test(e))return A;const i=e.match(/\./g);if(i&&i.length>1)return A;try{const i=H(e,t),r=null==i?"":String(i);return N.test(r)?A:r||A}catch{return A}}(r,t);return i.push({expr:r.trim(),result:n}),n}),n=(o=r)?o.replace(new RegExp(A,"g"),"").replace(/Reflect\.[^<>{}\s]+|\bProxy\b|ownKeys\([^)]*\)/g,""):o;var o;const s=i.length&&i.every(e=>""===e.result||e.result===A);return N.test(e)||s?"":n}const N=/Reflect|Proxy|ownKeys/;function O(e){if(N.test(e.textContent||"")){for(const t of e.childNodes)t.nodeType===Node.TEXT_NODE&&N.test(t.textContent||"")&&(t.textContent="");N.test(e.textContent||"")&&(e.textContent="")}}function q(e){if(N.test(e)){const e=()=>"";return e.__blocked=!0,e}const t=t=>G(e,t);return t.__blocked=!1,t}function z(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase()}class ${static dependencies;static manifest;aliases;version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},i={};for(const r of Object.keys(t))i[r]=this;for(const r of e){const e=r.userConfig;for(const[n,o]of Object.entries(e)){if(void 0===o)continue;if(!(n in t)){t[n]=o,i[n]=r;continue}if(t[n]===o)continue;const e=i[n]?.constructor.name??this.constructor.name,s=r.constructor.name,l=h("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${n}" supplied by both ${e} and ${s}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(l)}}Object.assign(this.userConfig,t)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=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)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(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.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...n,...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}setIcon(e,t,i){e.dataset.icon=z(t),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const r=this.#t(t,i);void 0!==r?"string"==typeof r?e.innerHTML=F(r):r instanceof HTMLElement&&(e.innerHTML="",e.appendChild(r.cloneNode(!0))):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const i=document.createElement("span");i.setAttribute("part","sort-indicator"),i.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(i,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(i,"sortNone"));const r=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return r?e.insertBefore(i,r):e.appendChild(i),i}warn(e,t){void 0!==t?console.warn(h(e,t,this.gridElement.id,this.name)):console.warn(`${l(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(h(e,t,this.gridElement.id,this.name))}}const B=new WeakMap;function W(e,t,i=-1){if(!t.valueAccessor)return e?.[t.field];if("object"!=typeof e||null===e)return t.valueAccessor({row:e,column:t,rowIndex:i});const r=t.field;let n=B.get(e);if(n){if(n.has(r))return n.get(r)}else n=new Map,B.set(e,n);const o=t.valueAccessor({row:e,column:t,rowIndex:i});return n.set(r,o),o}function K(e,t){e&&(t?B.get(e)?.delete(t):B.delete(e))}function V(e,t,i){const r=i.find(e=>e.field===t.field),n=r?.sortComparator,{field:o,direction:s}=t,l=[...e];return n?r?.valueAccessor?l.sort((e,t)=>n(W(e,r),W(t,r),e,t)*s):l.sort((e,t)=>n(e[o],t[o],e,t)*s):r?.valueAccessor?U(l,r,s):j(l,o,s),l}function j(e,t,i){e.sort((e,r)=>{const n=Y(e,r);if(0!==n)return n;const o=e[t],s=r[t];return null==o&&null==s?0:null==o?-i:null==s||o>s?i:o<s?-i:0})}function U(e,t,i){e.sort((e,r)=>{const n=Y(e,r);if(0!==n)return n;const o=W(e,t),s=W(r,t);return null==o&&null==s?0:null==o?-i:null==s||o>s?i:o<s?-i:0})}function Y(e,t){const i=!0===e?.__loading;return i===(!0===t?.__loading)?0:i?1:-1}function X(e,t,i,r){const n=r.find(e=>e.field===t),o=n?.sortComparator;o?n?.valueAccessor?e.sort((e,t)=>o(W(e,n),W(t,n),e,t)*i):e.sort((e,r)=>o(e[t],r[t],e,r)*i):n?.valueAccessor?U(e,n,i):j(e,t,i)}function Z(e,t,i,r){e._rows=t,e.__rowRenderEpoch++;for(let n=0;n<e._rowPool.length;n++)e._rowPool[n].__epoch=-1;le(e),e.refreshVirtualWindow(!0),Q(e,i,r)}function Q(e,t,i){const r={field:t.field,direction:i};e.dispatchEvent(new CustomEvent("sort-change",{detail:r})),e._pluginManager?.emitPluginEvent?.("sort-change",r),o(e,s(e,0===i?"sortCleared":"sortApplied",t.header??t.field,1===i?"ascending":"descending")),e.requestStateChange?.()}function J(e){return e._pluginManager?._hasRowStructurePlugins??!1}function ee(e,t){if(e._sortState&&e._sortState.field===t.field)if(1===e._sortState.direction)te(e,t,-1);else{if(e._sortState=null,J(e))return e._requestSchedulerPhase(4,"sort-clear"),void Q(e,t,0);e.__rowRenderEpoch++;for(let t=0;t<e._rowPool.length;t++)e._rowPool[t].__epoch=-1;e._rows=e.__originalOrder.slice(),e.__originalOrder=[],le(e);const i=e._headerRowEl?.querySelectorAll('[role="columnheader"].sortable');if(i)for(let t=0;t<i.length;t++){const r=i[t];r.getAttribute("aria-sort")&&("ascending"!==r.getAttribute("aria-sort")&&"descending"!==r.getAttribute("aria-sort")||e._sortState)||r.setAttribute("aria-sort","none")}e.refreshVirtualWindow(!0),Q(e,t,0)}else e._sortState||(e.__originalOrder=e._rows.slice()),te(e,t,1)}function te(e,t,i){if(e._sortState={field:t.field,direction:i},J(e))return e._requestSchedulerPhase(4,"sort-apply"),void Q(e,t,i);const r={field:t.field,direction:i},n=e._columns,o=e.effectiveConfig?.sortHandler??V;if(o===V)return X(e._rows,r.field,i,n),void Z(e,e._rows,t,i);const s=o(e._rows,r,n);s&&"function"==typeof s.then?s.then(r=>{Z(e,r,t,i)}):Z(e,s,t,i)}function ie(e,t){return!1!==e.effectiveConfig?.sortable&&!0===t.sortable}function re(e,t){return!1!==e.effectiveConfig?.resizable&&!1!==t.resizable}function ne(e,t){const i=document.createElement("span");b(i,"sort-indicator");const r=e._sortState?.field===t.field?e._sortState.direction:0,n=1===r?"sortAsc":-1===r?"sortDesc":"sortNone";i.dataset.icon=z(n);const o=e.icons?.[n];return void 0!==o&&function(e,t){"string"==typeof t?e.innerHTML=F(t):t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}(i,o),i}function oe(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 se(e,t,i,r){r.classList.add(R.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)||ee(e,t)}),r.addEventListener("keydown",i=>{if("Enter"===i.key||" "===i.key){if(i.preventDefault(),e._dispatchHeaderClick?.(i,t,r))return;ee(e,t)}})}function le(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",b(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:()=>ie(e,i)?ne(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=F(t);i.firstChild;)e.appendChild(i.firstChild)}else t instanceof Node&&e.appendChild(t)}(n,s),ie(e,i)&&se(e,i,0,n),re(e,i)&&(n.classList.add("resizable"),n.appendChild(oe(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=F(s):s instanceof Node&&l.appendChild(s),n.appendChild(l),ie(e,i)&&(se(e,i,0,n),n.appendChild(ne(e,i))),re(e,i)&&(n.classList.add("resizable"),n.appendChild(oe(e,r,n)))}else if(i.__headerTemplate)Array.from(i.__headerTemplate.childNodes).forEach(e=>n.appendChild(e.cloneNode(!0))),ie(e,i)&&(se(e,i,0,n),n.appendChild(ne(e,i))),re(e,i)&&(n.classList.add("resizable"),n.appendChild(oe(e,r,n)));else{const t=document.createElement("span");t.textContent=o,n.appendChild(t),ie(e,i)&&(se(e,i,0,n),n.appendChild(ne(e,i))),re(e,i)&&(n.classList.add("resizable"),n.appendChild(oe(e,r,n)))}t.appendChild(n)}),t.querySelectorAll(`.cell.${R.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 ae(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}}const de={STYLE:1,VIRTUALIZATION:2,HEADER:3,ROWS:4,COLUMNS:5,FULL:6};class ce{#i;#r=0;#n=0;#o=null;#s=null;#l=null;#a=!1;constructor(e){this.#i=e}requestPhase(e,t){e>this.#r&&(this.#r=e),0===this.#n&&(this.#d(),this.#n=requestAnimationFrame(()=>this.#c()))}whenReady(){return this.#o?this.#o:Promise.resolve()}setInitialReadyResolver(e){this.#l=e}cancel(){0!==this.#n&&(cancelAnimationFrame(this.#n),this.#n=0),this.#r=0,this.#s&&(this.#s(),this.#s=null,this.#o=null)}get isPending(){return 0!==this.#r}get pendingPhase(){return this.#r}#d(){this.#o||(this.#o=new Promise(e=>{this.#s=e}))}#c(){if(this.#n=0,!this.#i._schedulerIsConnected)return this.#r=0,void(this.#s&&(this.#s(),this.#s=null,this.#o=null));const e=this.#r;this.#r=0,e>=de.COLUMNS&&this.#i._schedulerMergeConfig(),e>=de.ROWS&&this.#i._schedulerProcessRows(),e>=de.COLUMNS&&(this.#i._schedulerProcessColumns(),this.#i._schedulerUpdateTemplate()),e>=de.HEADER&&this.#i._schedulerRenderHeader(),e>=de.VIRTUALIZATION&&this.#i.refreshVirtualWindow(!0,!0),e>=de.STYLE&&this.#i._schedulerAfterRender(),!this.#a&&this.#l&&(this.#a=!0,this.#l()),this.#s&&(this.#s(),this.#s=null,this.#o=null)}}class ue{#u;#h;#g;#p;#f;#w={};#m={};#b=!0;#v=[];#y;#C;#x;#R;#i;#E;constructor(e){this.#i=e}get original(){return this.#w}get effective(){return this.#m}get columns(){return this.#m.columns??[]}set columns(e){this.#m.columns=e}get lightDomColumnsCache(){return this.#p}set lightDomColumnsCache(e){this.#p=e}get originalColumnNodes(){return this.#f}set originalColumnNodes(e){this.#f=e}get lightDomTitle(){return this.#E}set lightDomTitle(e){this.#E=e}get initialColumnState(){return this.#R}set initialColumnState(e){this.#R=e}get sourcesChanged(){return this.#b}markSourcesChanged(){this.#b=!0}setGridConfig(e){this.#u!==e&&(this.#u=e,this.#b=!0,this.#p=void 0)}getGridConfig(){return this.#u}setColumns(e){this.#h=e,this.#b=!0}getColumns(){return this.#h}setFitMode(e){this.#g=e,this.#b=!0}getFitMode(){return this.#g}merge(){const e=(this.#m.columns?.length??0)>0;if(!this.#b&&e)return;const t=this.#S();this.#b=!1,this.#w=t,Object.freeze(this.#w),this.#w.columns&&Object.freeze(this.#w.columns),this.#m=this.#_(this.#w),this.#A()}#_(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}#A(){const e=this.#m;if(this.#k(),"number"==typeof e.rowHeight&&e.rowHeight>0&&(this.#i._virtualization.rowHeight=e.rowHeight),"fixed"===e.fitMode){this.columns.forEach(e=>{null==e.width&&(e.width=80)})}this.#i._applyAnimationConfig(e)}#k(){const e=this.#m.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))}}#S(){const e=this.#u?{...this.#u}:{},t=Array.isArray(e.columns)?[...e.columns]:[],i=(this.#p??[]).map(e=>({...e}));let r=m(t,i);this.#h&&this.#h.length&&(r=m(this.#h,i));const n=this.#i.sourceRows;if(0===r.length&&n.length){r=ae(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=q(e.__viewTemplate.innerHTML)),e.__editorTemplate&&!e.__compiledEditor&&(e.__compiledEditor=q(e.__editorTemplate.innerHTML))}),e.columns=r),this.#g&&(e.fitMode=this.#g),e.fitMode||(e.fitMode="stretch"),this.#T(e),e.columnState&&!this.#R&&(this.#R=e.columnState),e}#T(e){e.shell=e.shell?{...e.shell}:{},e.shell.header=e.shell.header?{...e.shell.header}:{};const t=this.#i._shellState.lightDomTitle;t&&(this.#E=t),this.#E&&!e.shell.header.title&&(e.shell.header.title=this.#E);const i=this.#i._shellState.lightDomHeaderContent;i?.length>0&&(e.shell.header.lightDomContent=i),this.#i._shellState.hasToolButtonsContainer&&(e.shell.header.hasToolButtonsContainer=!0);const r=this.#i._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.#i._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.#i._shellState.toolbarContents,s=Array.from(o.values()),l=this.#u?.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.#I();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.#i._sortState={field:e.field,direction:"asc"===e.sort.direction?1:-1})}else this.#i._sortState=null;for(const s of t)if(s.applyColumnState)for(const t of e.columns)s.applyColumnState(t.field,t)}resetState(e){this.#R=void 0,this.#i._sortState=null,this.#m=this.#_(this.#w),this.#A();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)}#I(){const e=new Map,t=this.#i._sortState;return t&&e.set(t.field,{direction:1===t.direction?"asc":"desc",priority:0}),e}requestStateChange(e){this.#C&&clearTimeout(this.#C),this.#C=setTimeout(()=>{this.#C=void 0;const t=this.collectState(e);this.#i._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.#i._emit("column-visibility",{field:e,visible:t,visibleColumns:i.filter(e=>!e.hidden).map(e=>e.field)}),this.#i._clearRowPool(),this.#i._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.#i._emit("column-visibility",{visibleColumns:e.map(e=>e.field)}),this.#i._clearRowPool(),this.#i._setup())}getAllColumns(){return this.columns.map(e=>({field:e.field,header:e.header||e.field,visible:!e.hidden,lockVisible:e.lockVisible,utility:!0===e.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,this.#i._invalidateVisibleColumnsCache(),le(this.#i),x(this.#i),this.#i._requestSchedulerPhase(de.COLUMNS,"configManager")}parseLightDomColumns(e){this.#p||(this.#f=Array.from(e.querySelectorAll("tbw-grid-column")),this.#p=this.#f.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);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"),u=e.querySelector("tbw-grid-column-header");d&&(r.__viewTemplate=d),c&&(r.__editorTemplate=c),u&&(r.__headerTemplate=u);const h=globalThis.DataGridElement,g=h?.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.#p=void 0}#M=new Map;registerLightDomHandler(e,t){this.#M.set(e.toLowerCase(),t)}unregisterLightDomHandler(e){this.#M.delete(e.toLowerCase())}observeLightDOM(e){this.#y&&this.#y.disconnect();const t=new Set,i=()=>{this.#x=void 0;for(const e of t){const t=this.#M.get(e);t?.()}t.clear()};this.#y=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.#M.has(i)&&t.add(i)}if("attributes"===i.type&&i.target.nodeType===Node.ELEMENT_NODE){const e=i.target.tagName.toLowerCase();this.#M.has(e)&&t.add(e)}}t.size>0&&!this.#x&&(this.#x=setTimeout(i,0))}),this.#y.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["title","field","header","width","hidden","id","icon","tooltip","order"]})}onChange(e){this.#v.push(e)}notifyChange(){for(const e of this.#v)e()}dispose(){this.#y?.disconnect(),this.#v=[],this.#C&&clearTimeout(this.#C),this.#x&&(clearTimeout(this.#x),this.#x=void 0)}}function he(){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 ge(e){return`<span role="checkbox" aria-checked="${e}" aria-label="${e}">${e?"🗹":"☐"}</span>`}function pe(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 fe(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 we(e){e&&e.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function me(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 be(e){return"rtl"===me(e)}function ve(e,t){const i=t.renderer||t.viewRenderer;if(i)return i;if(!t.type)return;const r=e.__frameworkAdapter;if(r?.getTypeDefault){const i=r.getTypeDefault(t.type,e._hostElement);if(i?.renderer)return i.renderer}}function ye(e,t){if(t.format)return t.format;if(!t.type)return;const i=e.__frameworkAdapter;if(i?.getTypeDefault){const r=i.getTypeDefault(t.type,e._hostElement);if(r?.format)return r.format}}const Ce='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function xe(e){return(e.__editingCellCount??0)>0}function Re(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing");e.querySelectorAll(`.cell.${R.EDITING}`).forEach(e=>e.classList.remove(R.EDITING))}const Ee=document.createElement("template");Ee.innerHTML='<div class="cell" role="gridcell" part="cell"></div>';const Se=document.createElement("template");function _e(){return Ee.content.firstElementChild.cloneNode(!0)}function Ae(){return Se.content.firstElementChild.cloneNode(!0)}function ke(e){e.__cellDisplayCache=void 0,e.__cellCacheEpoch=void 0,e.__hasSpecialColumns=void 0}function Te(e,t,i,r){const n=t.children,o=e._visibleColumns,s=o.length,l=n.length,a=s<l?s:l,u=e._focusRow,h=e._focusCol,g=e._hasAfterCellRenderHook?.()??!1;let f=e.__hasSpecialColumns;if(void 0===f){f=!1;const t=e.__frameworkAdapter;for(let i=0;i<s;i++){const r=o[i];if(r.__viewTemplate||r.__compiledView||r.renderer||r.viewRenderer||r.externalView||r.format||r.cellClass||"date"===r.type||"boolean"===r.type||r.type&&t?.getTypeDefault?.(r.type,e._hostElement)?.renderer||r.type&&t?.getTypeDefault?.(r.type,e._hostElement)?.format){f=!0;break}}e.__hasSpecialColumns=f}const w=String(r);if(f){for(let s=0;s<a;s++){if(o[s].externalView){if(!n[s].querySelector("[data-external-view]"))return void Ie(e,t,i,r)}}for(let s=0;s<a;s++){const l=o[s],a=n[s];a.getAttribute("data-row")!==w&&a.setAttribute("data-row",w);const f=a.classList.contains(R.EDITING);if(!f){const e=u===r&&h===s;e!==a.classList.contains("cell-focus")&&(a.classList.toggle("cell-focus",e),a.setAttribute("aria-selected",String(e)))}const b=l.cellClass;if(b){const t=a.getAttribute("data-dynamic-classes");if(t){const e=t.split(" ");for(let t=0;t<e.length;t++)e[t]&&a.classList.remove(e[t])}try{const e=b(W(i,l,r),i,l),t="string"==typeof e?e.split(/\s+/):e;if(t&&t.length>0){let e="";for(let i=0;i<t.length;i++){const r=t[i];r&&"string"==typeof r&&(a.classList.add(r),e+=(e?" ":"")+r)}a.setAttribute("data-dynamic-classes",e)}else a.removeAttribute("data-dynamic-classes")}catch(m){p(d,`cellClass callback error for column '${l.field}': ${m}`,e.id),a.removeAttribute("data-dynamic-classes")}}if(f)continue;const v=ve(e,l);if(v){const n=W(i,l,r),o=v({row:i,value:n,field:l.field,column:l,grid:e,cellEl:a});"string"==typeof o?(e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=F(o)):o instanceof Node?o.parentElement!==a&&(e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML="",a.appendChild(o)):null==o&&(e.__frameworkAdapter?.releaseCell?.(a),a.textContent=null==n?"":String(n)),g&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:s,value:n,cellElement:a,rowElement:t});continue}if(l.__compiledView){const n=W(i,l,r),o=l.__compiledView({row:i,value:n,field:l.field,column:l});l.__compiledView.__blocked?a.textContent="":(a.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=F(o),O(a)),g&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:s,value:n,cellElement:a,rowElement:t});continue}if(l.__viewTemplate){const n=W(i,l,r),o=l.__viewTemplate.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(o)?a.textContent="":(a.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=F(G(o,{row:i,value:n})),O(a)),g&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:s,value:n,cellElement:a,rowElement:t});continue}if(l.externalView)continue;const y=W(i,l,r);let C;a.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(a);const x=ye(e,l);if(x){try{const e=x(y,i);C=null==e?"":String(e)}catch(m){p(c,`Format error in column '${l.field}': ${m}`,e.id),C=null==y?"":String(y)}a.textContent=C}else"date"===l.type?(C=pe(y),a.textContent=C):"boolean"===l.type?a.innerHTML=ge(!!y):(C=null==y?"":String(y),a.textContent=C);g&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:s,value:y,cellElement:a,rowElement:t})}}else for(let d=0;d<a;d++){const s=n[d];if(s.classList.contains(R.EDITING))continue;s.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(s);const l=o[d],a=W(i,l,r);s.textContent=null==a?"":String(a),s.getAttribute("data-row")!==w&&s.setAttribute("data-row",w);const c=u===r&&h===d;c!==s.classList.contains("cell-focus")&&(s.classList.toggle("cell-focus",c),s.setAttribute("aria-selected",String(c))),g&&e._afterCellRender?.({row:i,rowIndex:r,column:l,colIndex:d,value:a,cellElement:s,rowElement:t})}}function Ie(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,a=e._focusCol,u=e._hasAfterCellRenderHook?.()??!1,h=document.createDocumentFragment();for(let f=0;f<s;f++){const n=o[f],s=_e();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=W(i,n,r);const m=ye(e,n);if(m)try{w=m(w,i)}catch(g){p(c,`Format error in column '${n.field}': ${g}`,e.id)}const b=n.__compiledView,v=n.__viewTemplate,y=ve(e,n),C=n.externalView;let x=!1;if(y){const t=y({row:i,value:w,field:n.field,column:n,grid:e,cellEl:s});"string"==typeof t?(s.innerHTML=F(t),x=!0):t instanceof Node?t.parentElement!==s&&(s.textContent="",s.appendChild(t)):null==t&&(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,grid:e};if(t.mount)try{t.mount({placeholder:r,context:o,spec:t})}catch(g){p("TBW063",`External view mount error for column '${n.field}': ${g}`,e.id)}else queueMicrotask(()=>{try{e.dispatchEvent(new CustomEvent("mount-external-view",{bubbles:!0,composed:!0,detail:{placeholder:r,spec:t,context:o}}))}catch(g){p("TBW064",`External view event dispatch error for column '${n.field}': ${g}`,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?"":F(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=F(G(e,{row:i,value:w})),x=!0)}else m?s.textContent=null==w?"":String(w):"date"===n.type?s.textContent=pe(w):"boolean"===n.type?s.innerHTML=ge(!!w):s.textContent=null==w?"":String(w);if(x){O(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&&a===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(W(i,n,r),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(g){p(d,`cellClass callback error for column '${n.field}': ${g}`,e.id)}u&&e._afterCellRender?.({row:i,rowIndex:r,column:n,colIndex:f,value:w,cellElement:s,rowElement:t}),h.appendChild(s)}t.appendChild(h)}function Me(e,t,i){if(t.target?.closest(".resize-handle"))return;const r=fe(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(R.EDITING)){n&&(we(e._bodyEl??e),o.classList.add("cell-focus"));const i=t.target,r=o.contains(i)&&i.matches(Ce)?i:o.querySelector(Ce);try{r?.focus({preventScroll:!0})}catch{}return}De(e)}}}function Le(e){"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit()}function Pe(e){if(!e)return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t||!!e.isContentEditable}function De(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),we(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(R.EDITING)){const e=s.querySelector(Ce);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})}}}Se.innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const Fe=new WeakMap;function He(e,t){const i=fe(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,we(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 Ge(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,u,h,g,p;return s&&(d=parseInt(s.getAttribute("data-row")??"-1",10),c=parseInt(s.getAttribute("data-col")??"-1",10),d>=0&&c>=0&&(u=e._rows[d],p=e._visibleColumns[c],h=p?.field,g=u&&h?u[h]:void 0)),{type:r,row:u,rowIndex:void 0!==d&&d>=0?d:void 0,colIndex:void 0!==c&&c>=0?c:void 0,field:h,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 Ne(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;if((!Pe(a)||"Home"!==t.key&&"End"!==t.key)&&!(Pe(a)&&("ArrowUp"===t.key||"ArrowDown"===t.key)&&"INPUT"===a.tagName&&"number"===a.type||Pe(a)&&("ArrowLeft"===t.key||"ArrowRight"===t.key)||Pe(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&&(e._activeEditRows===e._focusRow&&Le(e),e._focusRow-=1,e._focusCol=r):e._focusCol<r?e._focusCol+=1:(Le(e),e._focusRow<i&&(e._focusRow+=1,e._focusCol=0)),void De(e);case"ArrowDown":n&&Le(e),e._focusRow=Math.min(i,e._focusRow+1),t.preventDefault();break;case"ArrowUp":n&&Le(e),e._focusRow=Math.max(0,e._focusRow-1),t.preventDefault();break;case"ArrowRight":{const i=be(e);e._focusCol=i?Math.max(0,e._focusCol-1):Math.min(r,e._focusCol+1),t.preventDefault();break}case"ArrowLeft":{const i=be(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&&Le(e),e._focusRow=0,e._focusCol=0):e._focusCol=0,t.preventDefault(),void De(e,{forceScrollLeft:!0});case"End":return t.ctrlKey||t.metaKey?(n&&Le(e),e._focusRow=i,e._focusCol=r):e._focusCol=r,t.preventDefault(),void De(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}});if(e.dispatchEvent(d),d.defaultPrevented)return void t.preventDefault();break}default:return}De(e)}}(e,t),{signal:r}),i.addEventListener("mousedown",t=>function(e,t,i){const r=Ge(e,t,i,"mousedown");e._dispatchCellMouseDown?.(r)&&Fe.set(e,!0)}(e,i,t),{signal:r}),document.addEventListener("mousemove",t=>function(e,t,i){if(!Fe.get(e))return;const r=Ge(e,t,i,"mousemove");e._dispatchCellMouseMove?.(r)}(e,i,t),{signal:r}),document.addEventListener("mouseup",t=>function(e,t,i){if(!Fe.get(e))return;const r=Ge(e,t,i,"mouseup");e._dispatchCellMouseUp?.(r),Fe.set(e,!1)}(e,i,t),{signal:r})}let Oe;class qe{#i;#L=new Set;#P=new Map;constructor(e){this.#i=e}focusCell(e,t){const i=this.#i,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)),De(i))}get focusedCell(){const e=this.#i;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.#i._virtualization;if(!i.enabled)return;const r=i.container;if(!r)return;const n=this.#i._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 u=i.viewportEl?.clientHeight??r.clientHeight??0;if(u<=0)return;const h=r.scrollTop,g=a+d,p=h+u;let f;switch(s){case"start":f=a;break;case"center":f=a-u/2+d/2;break;case"end":f=g-u;break;default:if(a>=h&&g<=p)return;f=a<h?a:g-u}f=Math.max(0,f),"smooth"===l?r.scrollTo({top:f,behavior:"smooth"}):r.scrollTop=f}scrollToRowById(e,t){const i=this.#i._getRowEntry(e);i&&this.scrollToRow(i.index,t)}registerExternalFocusContainer(e){if(this.#L.has(e))return;this.#L.add(e);const t=new AbortController,i=t.signal,r=this.#i;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.#P.set(e,()=>t.abort())}unregisterExternalFocusContainer(e){this.#L.delete(e);const t=this.#P.get(e);t&&(t(),this.#P.delete(e))}containsFocus(e){const t=e??document.activeElement;return!!t&&(!!this.#i.contains(t)||this.isInExternalFocusContainer(t))}isInExternalFocusContainer(e){for(const t of this.#L)if(t.contains(e))return!0;return!1}destroy(){for(const e of this.#P.values())e();this.#P.clear(),this.#L.clear()}}const ze="function"==typeof requestIdleCallback;function $e(e){ze?cancelIdleCallback(e):clearTimeout(e)}function Be(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 We(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()}function Ke(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],u="number"==typeof c?.width?c.width:void 0,h=c?.__renderedWidth??u??a.getBoundingClientRect().width;t={startX:i.clientX,colIndex:s,startWidth:h},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 Ve="data-animating",je={change:"--tbw-row-change-duration",insert:"--tbw-row-insert-duration",remove:"--tbw-row-remove-duration"},Ue={change:500,insert:300,remove:200};function Ye(e,t){const i=je[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 Ue[t]}function Xe(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(Ve),e.offsetWidth,e.setAttribute(Ve,t);const r=Ye(e,t);setTimeout(()=>{"remove"!==t&&e.removeAttribute(Ve),i?.()},r)}(r,i,()=>e(!0))}):Promise.resolve(!1)}function Ze(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 Qe(e,t,i){const r=Ze(e,i);return void 0===r&&g("TBW040",'Cannot determine row ID. Configure getRowId in gridConfig or ensure rows have an "id" property.',t),r}class Je{#i;constructor(e){this.#i=e}resolveRowId(e){return Qe(e,this.#i.id,this.#i.effectiveConfig?.getRowId)}getRow(e){return this.#i._getRowEntry(e)?.row}getRowEntry(e){return this.#i._getRowEntry(e)}updateRow(e,t,i="api"){const r=this.#i,n=r._getRowEntry(e);n||g(a,`Row with ID "${e}" not found. Ensure the row exists and getRowId is correctly configured.`,r.id);const{row:o,index:s}=n,l=[];for(const[a,d]of Object.entries(t)){const e=o[a];e!==d&&(l.push({field:a,oldValue:e,newValue:d}),o[a]=d,K(o,a))}for(const{field:a,oldValue:d,newValue:c}of l)r.dispatchEvent(new CustomEvent("cell-change",{detail:{row:o,rowId:e,rowIndex:s,field:a,oldValue:d,newValue:c,changes:t,source:i},bubbles:!0,composed:!0}));l.length>0&&(ke(r),r._requestSchedulerPhase(de.VIRTUALIZATION,"updateRow"),r._emitDataChange())}updateRows(e,t="api"){const i=this.#i;let r=!1;for(const{id:n,changes:o}of e){const e=i._getRowEntry(n);e||g(a,`Row with ID "${n}" not found. Ensure the row exists and getRowId is correctly configured.`,i.id);const{row:s,index:l}=e;for(const[a,d]of Object.entries(o)){const e=s[a];e!==d&&(r=!0,s[a]=d,K(s,a),i.dispatchEvent(new CustomEvent("cell-change",{detail:{row:s,rowId:n,rowIndex:l,field:a,oldValue:e,newValue:d,changes:o,source:t},bubbles:!0,composed:!0})))}}r&&(ke(i),i._requestSchedulerPhase(de.VIRTUALIZATION,"updateRows"),i._emitDataChange())}async insertRow(e,t,i=!0){const r=this.#i,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]),ke(r),r._rebuildRowIdMap(),r.__rowRenderEpoch++;for(let s=0;s<r._rowPool.length;s++)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 Xe(r,n,"insert"))}async removeRow(e,t=!0){const i=this.#i,r=i._rows[e];if(!r)return;t&&await Xe(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}}ke(i),i._rebuildRowIdMap(),i.__rowRenderEpoch++;for(let l=0;l<i._rowPool.length;l++)i._rowPool[l].__epoch=-1;return i.refreshVirtualWindow(!0),i._emitDataChange(),t&&requestAnimationFrame(()=>{const e=i.querySelectorAll('[data-animating="remove"]');for(let t=0;t<e.length;t++)e[t].removeAttribute("data-animating")}),r}async applyTransaction(e,t=!0){const i=this.#i,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 Xe(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,K(t,r),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){ke(i),i._rebuildRowIdMap(),i.__rowRenderEpoch++;for(let e=0;e<i._rowPool.length;e++)i._rowPool[e].__epoch=-1;i.refreshVirtualWindow(!0)}else s&&(ke(i),i._requestSchedulerPhase(de.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 Xe(i,t,"insert")}}if(t&&r.updated.length>0)for(const l of r.updated){const e=i._rows.indexOf(l);e>=0&&await Xe(i,e,"change")}return t&&r.removed.length>0&&requestAnimationFrame(()=>{const e=i.querySelectorAll('[data-animating="remove"]');for(let t=0;t<e.length;t++)e[t].removeAttribute("data-animating")}),r}#D=null;#F=[];#H=null;applyTransactionAsync(e){return this.#D||(this.#D={add:[],update:[],remove:[]}),e.add&&this.#D.add.push(...e.add),e.update&&this.#D.update.push(...e.update),e.remove&&this.#D.remove.push(...e.remove),new Promise(e=>{this.#F.push(e),null===this.#H&&(this.#H=requestAnimationFrame(()=>{this.#H=null;const e=this.#D,t=this.#F;this.#D=null,this.#F=[],this.applyTransaction(e,!1).then(e=>{for(const i of t)i(e)})}))})}}function et(e,t){if(t)for(const i in t){const r=t[i];null!=r&&e.setAttribute(i,r)}}function tt(e,t,i){const r=document.createElement(e);return et(r,t),r}function it(e,t){const i=document.createElement("div");return e&&(i.className=e),et(i,t),i}function rt(e,t,i){const r=document.createElement("button");return e&&(r.className=e),et(r,t),r}const nt=document.createElement("template");function ot(){return nt.content.cloneNode(!0)}function st(e){const t=document.createDocumentFragment(),i=it(e.hasShell?`${R.ROOT} has-shell`:R.ROOT);if(e.hasShell&&e.shellHeader&&e.shellBody)i.appendChild(e.shellHeader),i.appendChild(e.shellBody);else{const e=it("tbw-grid-content");e.appendChild(ot()),i.appendChild(e)}return t.appendChild(i),t}function lt(e){const t=it("tbw-shell-header",{part:"shell-header",role:"presentation"});if(e.title){const i=it("tbw-shell-title");i.textContent=e.title,t.appendChild(i)}const i=it("tbw-shell-content",{part:"shell-content",role:"presentation","data-light-dom-header-content":""});t.appendChild(i);const r=it("tbw-shell-toolbar",{part:"shell-toolbar",role:"presentation"});for(const n of e.configButtons)n.hasRender&&r.appendChild(it("tbw-toolbar-content-slot",{"data-toolbar-content":n.id}));for(const n of e.apiButtons)n.hasRender&&r.appendChild(it("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(it("tbw-toolbar-separator")),e.hasPanels){const t=rt(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.dataset.icon="tool-panel",void 0!==e.toolPanelIcon&&(t.innerHTML=F(e.toolPanelIcon)),r.appendChild(t)}return t.appendChild(r),t}function at(e){const t=it("tbw-shell-body"),i=e.panels.length>0,r=1===e.panels.length,n=it("tbw-grid-content");n.appendChild(ot());let o=null;if(i){o=tt("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(it("tbw-tool-panel-resize",{"data-resize-handle":"","data-handle-position":t,"aria-hidden":"true"}));const i=it("tbw-tool-panel-content",{role:"presentation"}),n=it("tbw-accordion");for(const o of e.panels){const t=it(`tbw-accordion-section${o.isExpanded?" expanded":""}${r?" single":""}`,{"data-section":o.id}),i=rt("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=tt("span",{class:"tbw-accordion-icon"});e.innerHTML=F(o.icon),i.appendChild(e)}const s=tt("span",{class:"tbw-accordion-title"});if(s.textContent=o.title,i.appendChild(s),!r){const t=tt("span",{class:"tbw-accordion-chevron","data-icon":"expand"});void 0!==e.expandIcon&&(t.innerHTML=F(e.expandIcon)),i.appendChild(t)}t.appendChild(i),t.appendChild(it("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}function dt(e){return e?"string"==typeof e?F(e):e.outerHTML:""}function ct(e){return!!e?.header?.title||(!!e?.header?.toolbarContents?.length||(!!e?.toolPanels?.length||(!!e?.headerContents?.length||(!!e?.header?.lightDomContent?.length||!!e?.header?.hasToolButtonsContainer))))}function ut(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 ht(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 gt(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 p("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=F(r.innerHTML.trim());d=t=>{const i=document.createElement("div");return i.innerHTML=e,t.appendChild(i),()=>i.remove()}}const u=t.toolPanels.get(n);if(u){if(c){u.render=d,u.order=a,u.icon=s,u.tooltip=l;const e=t.panelCleanups.get(n);e&&(e(),t.panelCleanups.delete(n))}return}const h={id:n,title:o,icon:s,tooltip:l,order:a,render:d};t.toolPanels.set(n,h),t.lightDomToolPanelIds.add(n),r.style.display="none"})}function pt(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 ft(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 wt(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 mt(e,t){const i=e.querySelector("[data-panel-toggle]");i&&(i.classList.toggle("active",t.isPanelOpen),i.setAttribute("aria-pressed",String(t.isPanelOpen)))}function bt(e,t){const i=e.querySelector(".tbw-tool-panel");i&&(i.classList.toggle("open",t.isPanelOpen),t.isPanelOpen||(i.style.width=""))}function vt(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 yt(e,t,i){const r=void 0!==i?.toolPanel?dt(i.toolPanel):void 0,n=void 0!==i?.expand?dt(i.expand):void 0,o=void 0!==i?.collapse?dt(i.collapse):void 0,s=[...e.header?.toolbarContents??[]].sort((e,t)=>(e.order??0)-(t.order??0)),l=[...e.toolPanels??[]].sort((e,t)=>(e.order??100)-(t.order??100));return{headerOptions:{title:e.header?.title??void 0,hasPanels:l.length>0,isPanelOpen:t.isPanelOpen,toolPanelIcon:r,configButtons:s.map(e=>({id:e.id,hasElement:!1,hasRender:!!e.render})),apiButtons:[]},bodyOptions:{position:e.toolPanel?.position??"right",isPanelOpen:t.isPanelOpen,expandIcon:n,collapseIcon:o,panels:l.map(e=>({id:e.id,title:e.title,icon:dt(e.icon),isExpanded:t.expandedSections.has(e.id)}))}}}function Ct(e,t,i,r){const n=ct(t),o=[],s=["tbw-grid-header","tbw-grid-tool-buttons","tbw-grid-tool-panel","tbw-grid-column","tbw-grid-detail","tbw-grid-responsive-card"];for(const l of s){e.querySelectorAll(`:scope > ${l}`).forEach(e=>o.push(e))}e.replaceChildren();for(const l of o)e.appendChild(l);if(n){const{headerOptions:n,bodyOptions:o}=yt(t,i,r),s=st({hasShell:!0,shellHeader:lt(n),shellBody:at(o)});e.appendChild(s)}else{const t=st({hasShell:!1});e.appendChild(t)}return n}function xt(e,t,i){const r=e.querySelector(`[data-section="${t}"]`);r&&r.classList.toggle("expanded",i)}nt.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 Rt="tbw-grid-styles";let Et="";const St=new Map;function _t(){const e=function(){let e=document.getElementById(Rt);return e||(e=document.createElement("style"),e.id=Rt,e.setAttribute("data-tbw-grid","true"),document.head.appendChild(e)),e}(),t=Array.from(St.values()).join("\n");e.textContent=`${Et}\n\n/* Plugin Styles */\n${t}`}async function At(e){if(Et)return;if("string"==typeof e&&e.length>0)return Et=e,void _t();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){p("TBW120",`Failed to extract grid.css from document stylesheets: ${e}`)}return null}();t?(Et=t,_t()):"undefined"!=typeof process&&"test"===process.env?.NODE_ENV||p("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 kt(e){e.startY=null,e.startX=null,e.lastY=null,e.lastX=null,e.lastTime=null,e.locked=!1}function Tt(e){e.momentumRaf&&(cancelAnimationFrame(e.momentumRaf),e.momentumRaf=0)}function It(e,t){if(null!==e.lastTime){performance.now()-e.lastTime>60&&(e.velocityY=0,e.velocityX=0)}(Math.abs(e.velocityY)>.1||Math.abs(e.velocityX)>.1)&&function(e,t){const i=.95,r=1;let n=performance.now();const o=()=>{const s=performance.now(),l=s-n;n=s;const a=l/16,d=Math.pow(i,a);e.velocityY*=d,e.velocityX*=d;const c=16*e.velocityY,u=16*e.velocityX,h=Math.abs(c)>=r,g=Math.abs(u)>=r;h&&(t.fauxScrollbar.scrollTop+=c),g&&t.scrollArea&&(t.scrollArea.scrollLeft+=u),e.momentumRaf=h||g?requestAnimationFrame(o):0};e.momentumRaf=requestAnimationFrame(o)}(e,t),kt(e)}function Mt(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){Tt(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){const{scrollTop:e,scrollHeight:t,clientHeight:i}=r.fauxScrollbar;if(o>0&&e<t-i||o<0&&e>0?r.fauxScrollbar.scrollTop+=o:0!==o&&window.scrollBy(0,o),r.scrollArea){const{scrollLeft:e,scrollWidth:t,clientWidth:i}=r.scrollArea;s>0&&e<t-i||s<0&&e>0?r.scrollArea.scrollLeft+=s:0!==s&&window.scrollBy(s,0)}return!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:u}=r.fauxScrollbar,h=c-u>0;let g=!1;if(r.scrollArea){const{scrollWidth:e,clientWidth:t}=r.scrollArea;g=e-t>0}return!!(d&&h||!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,It(t,i))},{passive:!0,signal:r}),e.addEventListener("pointercancel",e=>{e.pointerId===t.activePointerId&&(t.activePointerId=null,kt(t))},{passive:!0,signal:r}),e.addEventListener("lostpointercapture",e=>{e.pointerId===t.activePointerId&&(t.activePointerId=null,kt(t))},{passive:!0,signal:r})}const Lt=[{property:"editable",pluginName:"editing",level:"column",description:"",isUsed:e=>!0===e||"function"==typeof e},{property:"editor",pluginName:"editing",level:"column",description:""},{property:"editorParams",pluginName:"editing",level:"column",description:""},{property:"group",pluginName:"groupingColumns",level:"column",description:""},{property:"pinned",pluginName:"pinnedColumns",level:"column",description:"",isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e}],Pt=[{property:"rowEditable",pluginName:"editing",level:"config",description:"",isUsed:e=>"function"==typeof e},{property:"columnGroups",pluginName:"groupingColumns",level:"config",description:"",isUsed:e=>Array.isArray(e)&&e.length>0}];function Dt(e){return`import { ${Ft(e)}Plugin } from '@toolbox-web/grid/plugins/${t=e,t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}';`;var t}function Ft(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ht(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 Nt(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 Ot(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 qt(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 zt(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 u=n[c],h=l?.(u,c);if(void 0!==h){const e=i[c];return void((!e.measured||Math.abs(e.height-h)>1)&&(Ot(i,c,h),d=!0))}const g=e.offsetHeight;if(g>0){const e=i[c];(!e.measured||Math.abs(e.height-g)>1)&&(Ot(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,u,g,a),d=!0)}});const c=d?function(e){let t=0;for(const i of e)i.measured&&t++;return t}(i):0,u=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:u}}class $t{#i;state;constructor(e,t){this.#i=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.#i._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;return a=i.variableHeights&&i.positionCache?function(e){if(0===e.length)return 0;const t=e[e.length-1];return t.offset+t.height}(i.positionCache):e*i.rowHeight,a+s+l}initializePositionCache(){const e=this.state;if(!e.variableHeights)return;const t=this.#i,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=Nt(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.#i._rows;if(e<0||e>=r.length)return;const n=r[e];let o=t;void 0===o&&(o=this.#i._getPluginRowHeight(n,e)),void 0===o&&(o=i.rowHeight);const s=i.positionCache[e];if(s&&!(Math.abs(s.height-o)<1)&&(Ot(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.#i,n=r._bodyEl;if(!n)return;const o=n.querySelectorAll(".data-grid-row"),s=r.effectiveConfig?.getRowId,l=r._rows,a=zt({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.#i,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 u;e&&i.variableHeights&&this.initializePositionCache();const h=i.positionCache;i.variableHeights&&h&&h.length>0?(u=qt(h,c),-1===u&&(u=0)):u=Math.floor(c/d),u-=u%2,u<0&&(u=0);const g=r._adjustPluginVirtualStart(u,c,d);let p;if(void 0!==g&&g<u&&(u=g,u-=u%2,u<0&&(u=0)),i.variableHeights&&h&&h.length>0){const e=a+3*d;let t=0;for(p=u;p<o&&t<e;)t+=h[p].height,p++;const i=Math.ceil(a/d)+3;p-u<i&&(p=Math.min(u+i,o))}else{p=u+(Math.ceil(a/d)+3)}p>o&&(p=o);const f=i.start,w=i.end;if(!e&&u===f&&p===w)return!1;i.start=u,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(de.VIRTUALIZATION,"stale-refs-retry"),!1;if(e&&i.totalHeightEl){const e=this.calculateTotalSpacerHeight(o);i.totalHeightEl.style.height=`${e}px`}let b;b=i.variableHeights&&h&&h[u]?h[u].offset:u*d;const v=-(c-b);return n.style.transform=`translateY(${v}px)`,r._renderVisibleRows(u,p,r.__rowRenderEpoch),e&&i.variableHeights&&this.measureRenderedRowHeights(u,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 Bt{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;_hasProcessRows=!1;_hasRowStructurePlugins=!1;#G=new Map;eventListeners=new Map;queryHandlers=new Map;attachAll(e){const t=this.#N(e);for(const i of t)this.attach(i)}#N(e){if(e.length<2)return e;const t=new Map,i=new Map,r=[];for(const n of e){const e=n.constructor,o=t.get(e);if(!o){t.set(e,n),r.push(n);continue}const s=i.get(o)??[];s.push(n),i.set(o,s)}if(0===i.size)return r;for(const[n,o]of i)n.mergeConfigsFrom(o);return r}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??`${Ft(r)}Plugin requires ${Ft(e)}Plugin`,o=Dt(e);n&&g("TBW020",`Plugin dependency error:\n\n${t}.\n\n → Add the plugin to your gridConfig.plugins array BEFORE ${Ft(r)}Plugin:\n ${o}\n plugins: [new ${Ft(e)}Plugin(), new ${Ft(r)}Plugin()]`,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),e.attach(this.grid),this.#O();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)}}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,this._hasProcessRows=!1,this.#G.clear()}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){if(!this._hasProcessRows)return e;let t=e;for(const i of this.#q("processRows")){const e=i.processRows(t);e!==t&&(t=e)}return t}processColumns(e){let t=[...e];for(const i of this.#q("processColumns"))t=i.processColumns(t);return t}beforeRender(){for(const e of this.plugins)e.beforeRender?.()}afterRender(){for(const e of this.#q("afterRender"))e.afterRender()}afterCellRender(e){for(const t of this.#q("afterCellRender"))t.afterCellRender(e)}hasAfterCellRenderHook(){return this._hasAfterCellRender}afterRowRender(e){for(const t of this.#q("afterRowRender"))t.afterRowRender(e)}hasAfterRowRenderHook(){return this._hasAfterRowRender}#O(){this._hasAfterCellRender=this.plugins.some(e=>"function"==typeof e.afterCellRender),this._hasAfterRowRender=this.plugins.some(e=>"function"==typeof e.afterRowRender),this._hasProcessRows=this.plugins.some(e=>"function"==typeof e.processRows),this._hasRowStructurePlugins=this.plugins.some(e=>!0===e.constructor.manifest?.modifiesRowStructure),this.#G.clear()}#q(e){let t=this.#G.get(e);if(t)return t;t=this.plugins.filter(t=>e in t&&"function"==typeof t[e]);const i=t=>{const i=t.constructor.manifest?.hookPriority;if(!i)return 0;return i[e]??0};return t.some(e=>0!==i(e))&&t.sort((e,t)=>i(e)-i(t)),this.#G.set(e,t),t}onScrollRender(){for(const e of this.#q("onScrollRender"))e.onScrollRender()}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);void 0!==i&&t.push(i)}return t}for(const r of this.plugins){const i=r.handleQuery?.(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){w("TBW024",`Error in plugin event handler for "${e}": ${r}`,this.grid.getAttribute("id")??void 0)}}onKeyDown(e){for(const t of this.#q("onKeyDown"))if(t.onKeyDown(e))return!0;return!1}onCellClick(e){for(const t of this.#q("onCellClick"))if(t.onCellClick(e))return!0;return!1}onRowClick(e){for(const t of this.#q("onRowClick"))if(t.onRowClick(e))return!0;return!1}onHeaderClick(e){for(const t of this.#q("onHeaderClick"))if(t.onHeaderClick(e))return!0;return!1}onScroll(e){for(const t of this.#q("onScroll"))t.onScroll(e)}onCellMouseDown(e){for(const t of this.#q("onCellMouseDown"))if(t.onCellMouseDown(e))return!0;return!1}onCellMouseMove(e){for(const t of this.#q("onCellMouseMove"))if(t.onCellMouseMove(e))return!0;return!1}onCellMouseUp(e){for(const t of this.#q("onCellMouseUp"))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 Wt extends HTMLElement{static tagName="tbw-grid";static version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";static#z=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#$(){return this}#B=!1;#o;#s;#W=[];get#m(){return this.#K?.effective??{}}#V=!1;#j=!1;#U={rows:!1,columns:!1,gridConfig:!1,fitMode:!1};#Y;#X=0;#Z=null;#Q=!1;#J=!1;#ee=0;#te;#ie={startY:null,startX:null,lastY:null,lastX:null,lastTime:null,velocityY:0,velocityX:0,momentumRaf:0,locked:!1,activePointerId:null};#re;#ne;#oe;#se;#le={scrollTop:0,scrollLeft:0,scrollHeight:0,scrollWidth:0,clientHeight:0,clientWidth:0};#ae;#de;#ce;#ue;#he;#ge;get _pluginManager(){return this.#ae}#pe=!1;#fe;#we;#R;#K;#me=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}}();#be;#ve;#ye;#Ce=!1;#xe=new Set;#Re=new Map;#Ee;#Se=new Map;#_e=!1;_rows=[];#Ae=[];get _columns(){return this.#m.columns??[]}set _columns(e){this.#m.columns=e,this.#ke=void 0}#ke;get _visibleColumns(){return this.#ke??=this._columns.filter(e=>!e.hidden)}_invalidateVisibleColumnsCache(){this.#ke=void 0}_headerRowEl;_bodyEl;_rowPool=[];_resizeController;get _virtualization(){return this.#ue.state}set _virtualization(e){Object.assign(this.#ue.state,e)}_focusRow=0;_focusCol=0;_restoreFocusAfterRender=!1;_sortState=null;_gridTemplate="";__rowRenderEpoch=0;__didInitialAutoSize=!1;get __lightDomColumnsCache(){return this.#K?.lightDomColumnsCache}set __lightDomColumnsCache(e){this.#K&&(this.#K.lightDomColumnsCache=e)}get __originalColumnNodes(){return this.#K?.originalColumnNodes}set __originalColumnNodes(e){this.#K&&(this.#K.originalColumnNodes=e)}__originalOrder=[];__frameworkAdapter;__rowsBodyEl=null;get rows(){return this._rows}set rows(e){const t=Array.isArray(e)?e:[],i=this.#W;this.#W=t,i!==t&&this.#Te("rows")}get sourceRows(){return this.#W}set sourceRows(e){this.#W=Array.isArray(e)?e:[]}get columns(){return[...this._columns]}set columns(e){const t=this.#K?.getColumns();this.#K?.setColumns(e),t!==e&&this.#Te("columns")}get gridConfig(){return this.#m}set gridConfig(e){e&&this.__frameworkAdapter?.processConfig&&(e=this.__frameworkAdapter.processConfig(e));const t=this.#K?.getGridConfig();this.#K?.setGridConfig(e),t!==e&&(this.#K.clearLightDomCache(),this.#Te("gridConfig"))}get fitMode(){return this.#m.fitMode??"stretch"}set fitMode(e){const t=this.#K?.getFitMode();this.#K?.setFitMode(e),t!==e&&this.#Te("fitMode")}get loading(){return this.#Ce}set loading(e){const t=this.#Ce;this.#Ce=e,t!==e&&(e?(this.setAttribute("loading",""),this.setAttribute("aria-busy","true")):(this.removeAttribute("loading"),this.removeAttribute("aria-busy")),this.#Ie())}setRowLoading(e,t){const i=this.#xe.has(e);t?this.#xe.add(e):this.#xe.delete(e),i!==t&&this.#Me(e,t)}setCellLoading(e,t,i){let r=this.#Re.get(e);const n=r?.has(t)??!1;i?(r||(r=new Set,this.#Re.set(e,r)),r.add(t)):(r?.delete(t),0===r?.size&&this.#Re.delete(e)),n!==i&&this.#Le(e,t,i)}isRowLoading(e){return this.#xe.has(e)}isCellLoading(e,t){return this.#Re.get(e)?.has(t)??!1}clearAllLoading(){this.loading=!1;for(const e of this.#xe)this.#Me(e,!1);this.#xe.clear();for(const[e,t]of this.#Re)for(const i of t)this.#Le(e,i,!1);this.#Re.clear()}get effectiveConfig(){return this.#m}get disconnectSignal(){return this.#re||(this.#re=new AbortController),this.#re.signal}constructor(){super(),this.#Pe(),this.#o=new Promise(e=>this.#s=e),this.#ue=new $t(this),this.#he=new qe(this),this.#ge=new Je(this),this.#Y=new ce(this),this.#Y.setInitialReadyResolver(()=>this.#s?.()),this.#be=function(e,t){let i=!1;const r={get isInitialized(){return i},setInitialized(e){i=e},get isPanelOpen(){return e.isPanelOpen},get expandedSections(){return[...e.expandedSections]},openToolPanel(){if(e.isPanelOpen)return;if(0===e.toolPanels.size)return void p("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;mt(i,e),bt(i,e),wt(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;mt(i,e),bt(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 p("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),xt(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),xt(n,t,!1);const o=n.querySelector(`[data-section="${t}"] .tbw-accordion-content`);o&&(o.innerHTML="")}e.expandedSections.add(i),xt(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)?p("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)?p("TBW074",`Header content "${r.id}" already registered`,t.id):(e.headerContents.set(r.id,r),i&&ft(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)?p("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.#me,this),this.#K=new ue(this)}async#Pe(){await At('@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);--tbw-icon-expand: "▶";--tbw-icon-collapse: "▼";--tbw-icon-sort-asc: "▲";--tbw-icon-sort-desc: "▼";--tbw-icon-sort-none: "⇅";--tbw-icon-submenu-arrow: "▶";--tbw-icon-drag-handle: "⋮⋮";--tbw-icon-tool-panel: "☰";--tbw-icon-filter: "";--tbw-icon-filter-active: "";--tbw-icon-print: "🖨️";--tbw-icon-expand-mask: none;--tbw-icon-collapse-mask: none;--tbw-icon-sort-asc-mask: none;--tbw-icon-sort-desc-mask: none;--tbw-icon-sort-none-mask: none;--tbw-icon-submenu-arrow-mask: none;--tbw-icon-drag-handle-mask: none;--tbw-icon-tool-panel-mask: none;--tbw-icon-filter-mask: url("data:image/svg+xml,%3Csvg viewBox=\'0 0 16 16\' width=\'12\' height=\'12\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Cpath 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\'/%3E%3C/svg%3E");--tbw-icon-filter-active-mask: var(--tbw-icon-filter-mask);--tbw-icon-print-mask: none}}\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 [data-icon=expand]:empty:before{content:var(--tbw-icon-expand)}tbw-grid [data-icon=collapse]:empty:before{content:var(--tbw-icon-collapse)}tbw-grid [data-icon=sort-asc]:empty:before{content:var(--tbw-icon-sort-asc)}tbw-grid [data-icon=sort-desc]:empty:before{content:var(--tbw-icon-sort-desc)}tbw-grid [data-icon=sort-none]:empty:before{content:var(--tbw-icon-sort-none)}tbw-grid [data-icon=submenu-arrow]:empty:before{content:var(--tbw-icon-submenu-arrow)}tbw-grid [data-icon=drag-handle]:empty:before{content:var(--tbw-icon-drag-handle)}tbw-grid [data-icon=tool-panel]:empty:before{content:var(--tbw-icon-tool-panel)}tbw-grid [data-icon=print]:empty:before{content:var(--tbw-icon-print)}tbw-grid [data-icon=filter]:empty:before{content:var(--tbw-icon-filter)}tbw-grid [data-icon=filter-active]:empty:before{content:var(--tbw-icon-filter-active)}tbw-grid [data-icon]:empty:before{display:inline-block;vertical-align:middle;-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center}tbw-grid [data-icon=expand]:empty:before{-webkit-mask-image:var(--tbw-icon-expand-mask);mask-image:var(--tbw-icon-expand-mask)}tbw-grid [data-icon=collapse]:empty:before{-webkit-mask-image:var(--tbw-icon-collapse-mask);mask-image:var(--tbw-icon-collapse-mask)}tbw-grid [data-icon=sort-asc]:empty:before{-webkit-mask-image:var(--tbw-icon-sort-asc-mask);mask-image:var(--tbw-icon-sort-asc-mask)}tbw-grid [data-icon=sort-desc]:empty:before{-webkit-mask-image:var(--tbw-icon-sort-desc-mask);mask-image:var(--tbw-icon-sort-desc-mask)}tbw-grid [data-icon=sort-none]:empty:before{-webkit-mask-image:var(--tbw-icon-sort-none-mask);mask-image:var(--tbw-icon-sort-none-mask)}tbw-grid [data-icon=submenu-arrow]:empty:before{-webkit-mask-image:var(--tbw-icon-submenu-arrow-mask);mask-image:var(--tbw-icon-submenu-arrow-mask)}tbw-grid [data-icon=drag-handle]:empty:before{-webkit-mask-image:var(--tbw-icon-drag-handle-mask);mask-image:var(--tbw-icon-drag-handle-mask)}tbw-grid [data-icon=tool-panel]:empty:before{-webkit-mask-image:var(--tbw-icon-tool-panel-mask);mask-image:var(--tbw-icon-tool-panel-mask)}tbw-grid [data-icon=print]:empty:before{-webkit-mask-image:var(--tbw-icon-print-mask);mask-image:var(--tbw-icon-print-mask)}tbw-grid [data-icon=filter]:empty:before,tbw-grid [data-icon=filter-active]:empty:before{width:var(--tbw-icon-size, 1em);height:var(--tbw-icon-size, 1em);background:currentColor}tbw-grid [data-icon=filter]:empty:before{-webkit-mask-image:var(--tbw-icon-filter-mask);mask-image:var(--tbw-icon-filter-mask)}tbw-grid [data-icon=filter-active]:empty:before{-webkit-mask-image:var(--tbw-icon-filter-active-mask);mask-image:var(--tbw-icon-filter-active-mask)}.tbw-context-menu [data-icon]:empty:before{display:inline-block;width:1em;height:1em;vertical-align:middle}.tbw-context-menu [data-icon=submenu-arrow]:empty:before{content:var(--tbw-icon-submenu-arrow, "▶")}}\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)}@media(hover:hover){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.#ae?.getPlugin(e)}getPluginByName(e){return this.#ae?.getPluginByName(e)}requestRender(){this.#Y.requestPhase(de.ROWS,"plugin:requestRender")}requestColumnsRender(){this.#Y.requestPhase(de.COLUMNS,"plugin:requestColumnsRender")}requestRenderWithFocus(){this._restoreFocusAfterRender=!0,this.#Y.requestPhase(de.ROWS,"plugin:requestRenderWithFocus")}updateTemplate(){x(this)}requestAfterRender(){this.#Y.requestPhase(de.STYLE,"plugin:requestAfterRender")}requestVirtualRefresh(){this._virtualization.start=-1,this.refreshVirtualWindow(!1)}#De(){this.#ae=new Bt(this);const e=this.#m?.plugins,t=Array.isArray(e)?e:[],i=this.#m?.features;let r=[];i&&Oe&&(r=Oe(i));const n=r.length>0?[...r,...t]:t;this.#ae.attachAll(n)}#Fe(){!function(e){let t=!1;for(const{name:i,styles:r}of e)St.has(i)||(St.set(i,r),t=!0);t&&_t()}(this.#ae?.getPluginStyles()??[])}#He(){const e=this.#m?.plugins,t=Array.isArray(e)?e:[],i=this.#m?.features??void 0,r=i!==this.#ce;if((this.#de===t||void 0!==this.#de&&this.#de.length===t.length&&this.#de.every((e,i)=>e===t[i]))&&!r)return void(this.#de=t);this.#ae&&this.#ae.detachAll();for(const o of this.#me.toolPanels.keys()){const e=this.#me.lightDomToolPanelIds.has(o),t=this.#me.apiToolPanelIds.has(o);if(!e&&!t){const e=this.#me.panelCleanups.get(o);e&&(e(),this.#me.panelCleanups.delete(o)),this.#me.toolPanels.delete(o)}}for(const o of this.#me.headerContents.keys()){if(this.#me.apiHeaderContentIds.has(o))continue;const e=this.#me.headerContentCleanups.get(o);e&&(e(),this.#me.headerContentCleanups.delete(o)),this.#me.headerContents.delete(o)}this.#De(),this.#Fe(),this.#de=t,this.#ce=i,this.#Ge(),this.#Ne();const n=this.#Q;if(this.#Q=this.#ae?.getAll().some(e=>e.onScroll)??!1,!n&&this.#Q){const e=this.#$.querySelector(".tbw-grid-content")??this.#$.querySelector(".tbw-grid-root");this.#Oe(e)}}#qe(){this.#ae?.detachAll()}#Ne(){if(!this.#ae)return;const e=this.#ae.getToolPanels();for(const{panel:i}of e)this.#me.toolPanels.has(i.id)||this.#me.toolPanels.set(i.id,i);const t=this.#ae.getHeaderContents();for(const{content:i}of t)this.#me.headerContents.has(i.id)||this.#me.headerContents.set(i.id,i)}#ze(){const e=Wt.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",Wt.version),this.id||(this.id="tbw-grid-"+ ++Wt.#z),this._rows=Array.isArray(this.#W)?[...this.#W]:[],this.#re&&(this.#re.abort(),this.#pe=!1),this.#re=new AbortController,this.#se&&($e(this.#se),this.#se=void 0),this.#$e(),this.#K.parseLightDomColumns(this),this.#K.merge(),this.#De();const e=this.#m?.plugins;var t,i;this.#de=Array.isArray(e)?e:[],this.#ce=this.#m?.features??void 0,this.#Ne(),this.#B||(this.#Be(),this.#Fe(),this.#B=!0),this.#We(),this.#se=(t=()=>{this.#Ke()},i={timeout:100},ze?requestIdleCallback(t,i):window.setTimeout(()=>{const e=Date.now();t({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-e))})},1))}disconnectedCallback(){this.#se&&($e(this.#se),this.#se=void 0),this.#ee&&(clearTimeout(this.#ee),this.#ee=0),this.#qe(),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.#me),this.#be.setInitialized(!1),this.#ve?.(),this.#ve=void 0,this.#ye?.(),this.#ye=void 0,Tt(this.#ie),this.#re&&(this.#re.abort(),this.#re=void 0),this.#fe?.abort(),this.#fe=void 0,this.#pe=!1,this._resizeController&&this._resizeController.dispose(),this.#ne&&(this.#ne.disconnect(),this.#ne=void 0),this.#oe&&(this.#oe.disconnect(),this.#oe=void 0,this.#Ve=!1),ke(this),this.#je.clear(),this._virtualization.heightCache?.byKey.clear(),this.#de=void 0,this.#ce=void 0;for(let e=0;e<this._rowPool.length;e++)this._rowPool[e].remove();this._rowPool.length=0,this.__rowsBodyEl=null,this.#V=!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{p("TBW130",`Invalid JSON for '${e}' attribute: ${i}`,this.id)}else"fit-mode"===e&&(this.fitMode=i)}#We(){const e=this.#$.querySelector(".tbw-grid-content")??this.#$.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.#be.isInitialized){ft(this.#$,this.#me),pt(this.#$,this.#m?.shell,this.#me);const e=this.#m?.shell?.toolPanel?.defaultOpen;e&&this.#me.toolPanels.has(e)&&(this.openToolPanel(),this.#me.expandedSections.add(e)),this.#me.isPanelOpen&&(bt(this.#$,this.#me),wt(this.#$,this.#me,(this.#m,this.#m)),mt(this.#$,this.#me))}if(this.setAttribute("data-upgraded",""),this.#V=!0,this._resizeController=Ke(this),this.#Ue(),this.#Oe(e),this.#pe)return;this.#pe=!0;const t=this.disconnectSignal;Ne(this,this,this.#$,t),this.#Ge(),queueMicrotask(()=>this.#Ye()),this.#Y.requestPhase(de.FULL,"afterConnect")}#Ge(){const e=this.#m.rowHeight,t=this.#ae.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.#ue.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.#Xe())}#Xe(){if(this.#ae.hasRowHeightPlugin())return;const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;if(e.style.getPropertyValue("--tbw-row-height"))return;const t=this.#Ze(),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.#Y.requestPhase(de.VIRTUALIZATION,"measureRowHeight"))}#Ze(){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}#Qe(){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.#ue.initializePositionCache(),this._virtualization.totalHeightEl){const e=this.#ue.calculateTotalSpacerHeight(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}}#Oe(e){this.#fe?.abort(),this.#fe=new AbortController;const t=this.#fe.signal,i=e?.querySelector(".faux-vscroll"),r=e?.querySelector(".rows");if(this._virtualization.container=i??this,this.#Q=this.#ae?.getAll().some(e=>e.onScroll)??!1,i&&r){i.addEventListener("scroll",()=>{if(!this._virtualization.enabled&&!this.#Q)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=qt(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.#Z=e,this.#X||(this.#X=requestAnimationFrame(()=>{this.#X=0,null!==this.#Z&&(this.#Je(this.#Z),this.#Z=null)}))},{passive:!0,signal:t});const e=this.#$.querySelector(".tbw-scroll-area");this.#we=e,this._virtualization.scrollAreaEl=e,e&&this.#Q&&e.addEventListener("scroll",()=>{const t=this.#le;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.#ae?.onScroll(t)},{passive:!0,signal:t});const n=this.#$.querySelector(".tbw-grid-content"),o=this.#we;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}),Mt(n,this.#ie,{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(R.EDITING))return;const i=e.target;i.draggable||i.closest('[draggable="true"]')||e.preventDefault(),He(n,t)},{signal:s}),o.addEventListener("click",e=>{const t=e.target.closest(".data-grid-row");if(t&&Me(n,e,t),!document.activeElement?.closest(`.cell.${R.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&&Me(n,e,t)},{signal:s})),this.#ne?.disconnect(),this._virtualization.viewportEl&&(this.#ne=new ResizeObserver(()=>{this.#et(),this.#Y.requestPhase(de.VIRTUALIZATION,"resize-observer")}),this.#ne.observe(this._virtualization.viewportEl)),this.#$.addEventListener("focusin",()=>{this.dataset.hasFocus=""},{signal:t}),this.#$.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.#$.contains(t)||this.#he.isInExternalFocusContainer(t))||delete this.dataset.hasFocus},{signal:t})}#Ve=!1;#tt(){if(this.#Ve)return;const e=this._bodyEl?.querySelector(".data-grid-row");e&&(this.#Ve=!0,this.#oe?.disconnect(),this.#oe=new ResizeObserver(()=>{this.#Xe()}),this.#oe.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)}#it(e,t){this.#V&&this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}_emitDataChange(){this.#it("data-change",{rowCount:this._rows.length,sourceRowCount:this.#W.length}),function(e,t,i){if(i===t.lastAnnouncedSourceCount)return;const r=t.lastAnnouncedSourceCount;t.lastAnnouncedSourceCount=i,0===i&&r<0||o(e,s(e,"dataLoaded",i))}(this,this.#rt,this.#W.length)}#Ye(){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))})})}#Te(e){this.#U[e]=!0,this.#j||(this.#j=!0,queueMicrotask(()=>this.#nt()))}#nt(){if(!this.#j||!this.#V)return void(this.#j=!1);const e=this.#U;if(this.#j=!1,this.#U={rows:!1,columns:!1,gridConfig:!1,fitMode:!1},e.gridConfig)return this.#ot(),void(e.rows&&this.#st());e.columns&&this.#lt(),e.rows&&this.#st(),e.fitMode&&this.#at()}#st(){this._rows=Array.isArray(this.#W)?[...this.#W]:[],this.#_e=!0,this.#Y.requestPhase(de.ROWS,"applyRowsUpdate")}#dt(){this.#_e&&this._rebuildRowIdMap()}_rebuildRowIdMap(){this.#_e=!1,this.#Se.clear();const e=this.#m.getRowId;for(let t=0;t<this._rows.length;t++){const i=Ze(this._rows[t],e);void 0!==i&&this.#Se.set(i,{row:this._rows[t],index:t})}}#lt(){ke(this),this.#K.merge(),this.#Ue()}#at(){this.#K.merge();if("fixed"===this.#m.fitMode)this.__didInitialAutoSize=!1,v(this);else{for(let e=0;e<this._columns.length;e++){const t=this._columns[e];!t.__userResized&&t.__autoSized&&delete t.width}x(this)}}#ot(){ut(this,this.#me),ht(this,this.#me);const e=!!this.#$.querySelector(".has-shell"),t=!!this.#$.querySelector(".tbw-tool-panel"),i=this.#$.querySelectorAll(".tbw-accordion-section").length,r=this.#$.querySelector(".tbw-tool-panel")?.dataset.position??"right";this.#K.parseLightDomColumns(this),this.#K.merge(),this.#He(),this.#Ge(),gt(this,this.#me,this.#ze()),this.#K.markSourcesChanged(),this.#K.merge();const n=ct(this.#m?.shell),o=(this.#m?.shell?.toolPanels?.length??0)>0,s=this.#m?.shell?.toolPanels?.length??0,l=this.#m?.shell?.toolPanel?.position??"right";if(e!==n||!t&&o||t&&s!==i||t&&r!==l)return vt(this.#me),this.#Be(),this.#Fe(),this.#We(),void this._rebuildRowIdMap();e&&this.#ct(),this.#me.isPanelOpen&&wt(this.#$,this.#me,(this.#m,this.#m)),this._rebuildRowIdMap(),this.#Y.requestPhase(de.COLUMNS,"applyGridConfigUpdate")}#ct(){const e=this.#$.querySelector(".tbw-shell-header");if(!e)return;const t=this.#m.shell?.header?.title??this.#me.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()}#ut(){if(this.__rowRenderEpoch++,this.#ae){const e=this.#Ae.length>0?this.#Ae:this._columns,t=e.filter(e=>!e.hidden),i=e.filter(e=>e.hidden),r=this.#ae.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.#ht(e,r,i)}else this._columns=[...e]}}#ht(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}#gt(){ke(this);const e=this.#W;if(!Array.isArray(e))return this._rows=[],this._rebuildRowIdMap(),this._virtualization.variableHeights&&this.#ue.initializePositionCache(),void this._emitDataChange();if(!this._sortState&&this.#m.initialSort){const{field:e,direction:t}=this.#m.initialSort;this._columns.find(t=>t.field===e)&&(this._sortState={field:e,direction:"desc"===t?-1:1})}this._sortState&&(this.__originalOrder=this._rows);const t=function(e,t,i=!1){if(!e._sortState)return t;const r=e.effectiveConfig?.sortHandler??V;if(r===V)return i||(e.__originalOrder=t.slice()),X(t,e._sortState.field,e._sortState.direction,e._columns),t;i||(e.__originalOrder=t);const n=r(t,e._sortState,e._columns);return n&&"function"==typeof n.then?t:n}(this,this._sortState?[...e]:e,!0),i=this.#ae?.processRows(t)??t;this._rows=i,this._rebuildRowIdMap(),this._emitDataChange()}#pt(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.#te||(this.#te=(e,t,i)=>this.#ae?.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=Ae();e._rowPool.push(t)}if(e._rowPool.length>o){const t=e.__frameworkAdapter,i=t?.releaseCell;for(let r=o;r<e._rowPool.length;r++){const n=e._rowPool[r];if(i){const e=n.children;for(let r=0;r<e.length;r++){const n=e[r];n.firstElementChild&&i.call(t,n)}}n.parentNode===s&&n.remove()}e._rowPool.length=o}const c=n&&!1!==e.__hasRenderRowPlugins,u=e._hasAfterRowRenderHook?.()??!1,h=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=xe(w),n=x&&!C||e._activeEditRows===i;t&&!n?(w.__isCustomRow&&(w.className="data-grid-row",w.setAttribute("role","row"),w.__isCustomRow=!1),Re(w),Ie(e,w,o,i),w.__epoch=r,w.__rowDataRef=o):t&&n?(Te(e,w,o,i),w.__rowDataRef=o):(w.__isCustomRow&&(w.className="data-grid-row",w.setAttribute("role","row"),w.__isCustomRow=!1),Ie(e,w,o,i),w.__epoch=r,w.__rowDataRef=o)}else if(C){const t=xe(w),n=e._activeEditRows===i;t&&!n?(Re(w),Ie(e,w,o,i),w.__epoch=r,w.__rowDataRef=o):(Te(e,w,o,i),w.__rowDataRef=o)}else{const t=xe(w),n=x||e._activeEditRows===i;t&&!n?(Re(w),Ie(e,w,o,i),w.__epoch=r,w.__rowDataRef=o):Te(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");if(t){const e=t.split(" ");for(let t=0;t<e.length;t++)e[t]&&w.classList.remove(e[t])}try{const e=_(o),t="string"==typeof e?e.split(/\s+/):e;if(t&&t.length>0){let e="";for(let i=0;i<t.length;i++){const r=t[i];r&&"string"==typeof r&&(w.classList.add(r),e+=(e?" ":"")+r)}w.setAttribute("data-dynamic-classes",e)}else w.removeAttribute("data-dynamic-classes")}catch(g){p("TBW060",`rowClass callback error: ${g}`,e.id),w.removeAttribute("data-dynamic-classes")}}if(h){const e=h(o,i);void 0!==e&&e>0?w.style.setProperty("--tbw-row-height",`${e}px`):w.style.removeProperty("--tbw-row-height")}u&&e._afterRowRender?.({row:o,rowIndex:i,rowElement:w}),w.parentNode!==s&&s.appendChild(w)}}(this,e,t,i,this.#te),this.#xe.size>0)for(const r of this.#xe)this.#Me(r,!0)}#rt={rowCount:-1,colCount:-1,ariaLabel:void 0,ariaDescribedBy:void 0,lastAnnouncedSourceCount:-1};_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.#rt,this.__rowsBodyEl,this._bodyEl,e,t)}_requestSchedulerPhase(e,t){this.#Y.requestPhase(e,t)}_getPluginRowHeight(e,t){return this.#ae?.getRowHeight?.(e,t)}_adjustPluginVirtualStart(e,t,i){return this.#ae?.adjustVirtualStart(e,t,i)}_afterPluginRender(){this.#ae?.afterRender()}_emitPluginEvent(e,t){this.#ae?.emitPluginEvent(e,t)}_schedulerMergeConfig(){this.#K.parseLightDomColumns(this),this.#K.merge(),this.#He(),function(e,t,i){const r=Lt,n=Pt,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)}const l=e.features;function a(e){return!!l&&!1===l[e]}for(const c of n){const i=e[c.property];if((c.isUsed?c.isUsed(i):void 0!==i)&&!Ht(t,c.pluginName)&&!a(c.pluginName)){const e=c.description||`the "${c.property}" ${c.level} property`;s(c.pluginName,e,Dt(c.pluginName),c.property,!0)}}const d=e.columns;if(d&&d.length>0)for(const c of d)for(const e of r){const i=c[e.property];if((e.isUsed?e.isUsed(i):void 0!==i)&&!Ht(t,e.pluginName)&&!a(e.pluginName)){const t=c.field||"<unknown>",i=e.description||`the "${e.property}" ${e.level} property`;s(e.pluginName,i,Dt(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 ${Ft(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 ${Ft(t)}Plugin(), ...]`)}g([...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.#m,this.#ae?.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=`[${Ft(n.name)}Plugin] Configuration warning: ${t.message}`;"error"===t.severity?i.push(e):r.push(e)}}}if(r.length>0&&he())for(const n of r)p("TBW004",n,t);i.length>0&&g("TBW003",`Configuration error:\n\n${i.join("\n\n")}`,t)}(this.#ae?.getPlugins()??[],this.id),function(e,t){if(!he())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),p("TBW022",`${Ft(n.name)}Plugin and ${Ft(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.#ae?.getPlugins()??[],this.id),this.#ft(),this.#Ae=[...this._columns]}_schedulerProcessColumns(){this.#ut()}_schedulerProcessRows(){this.#gt()}_schedulerRenderHeader(){le(this)}_schedulerUpdateTemplate(){x(this)}_schedulerAfterRender(){this.#ae?.afterRender(),this._virtualization.enabled&&this._virtualization.totalHeightEl&&queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const e=this.#ue.calculateTotalSpacerHeight(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`});"fixed"!==this.#m.fitMode||this.__didInitialAutoSize||(this.__didInitialAutoSize=!0,v(this)),this._restoreFocusAfterRender&&(this._restoreFocusAfterRender=!1,De(this)),this._virtualization.enabled&&!this.#Ve&&this.#tt(),this.#J&&(this.#J=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.#Qe()})})),this.#Ce&&this.#Ie()}get _schedulerIsConnected(){return this.isConnected&&this.#V}get _hostElement(){return this}get _renderRoot(){return this.#$}_emit(e,t){this.#it(e,t)}get _accordionIcons(){return{expand:this.#m?.icons?.expand??n.expand,collapse:this.#m?.icons?.collapse??n.collapse}}get _shellState(){return this.#me}_clearRowPool(){const e=this.__frameworkAdapter,t=e?.releaseCell;if(t)for(let i=0;i<this._rowPool.length;i++){const r=this._rowPool[i].children;for(let i=0;i<r.length;i++){const n=r[i];n.firstElementChild&&t.call(e,n)}}this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++}_setup(){this.#Ue()}_applyAnimationConfig(e){this.#pt(e)}#ft(){!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.#rt,this.__rowsBodyEl,this.#m,this.#me)}#Ie(){const e=this.querySelector(".tbw-grid-root");var t;e&&(this.#Ce?(this.#Ee||(this.#Ee=function(e){const t=document.createElement("div");return t.className="tbw-loading-overlay",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.appendChild(Be("large",e)),t}(this.#m?.loadingRenderer)),function(e,t){e.appendChild(t)}(e,this.#Ee)):(t=this.#Ee,t?.remove()))}#Me(e,t){this.#dt();const i=this.#Se.get(e);if(!i)return;const r=this.findRenderedRowElement?.(i.index);r&&We(r,t)}#Le(e,t,i){this.#dt();const r=this.#Se.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)}#Ue(){if(this.isConnected&&this._headerRowEl&&this._bodyEl){if(this.#K.parseLightDomColumns(this),this.#R){const e=this.#R;this.#R=void 0,this.#K.merge();const t=this.#ae?.getAll()??[];this.#K.applyState(e,t)}this._bodyEl&&(this._bodyEl.style.display="",this._bodyEl.style.gridTemplateColumns=""),this.#Y.requestPhase(de.FULL,"setup")}}#Je(e){const t=this._virtualization.container,i=this.#we,r=i?.scrollLeft??0,n=t?.scrollHeight??0,o=i?.scrollWidth??0,s=t?.clientHeight??0,l=i?.clientWidth??0;if(this.refreshVirtualWindow(!1)&&this.#ae?.onScrollRender(),this._virtualization.variableHeights&&(this.#ee&&clearTimeout(this.#ee),this.#ee=window.setTimeout(()=>{this.#ee=0,this.#ue.measureRenderedRowHeights(this._virtualization.start,this._virtualization.end)},100)),this.#Q){const t=this.#le;t.scrollTop=e,t.scrollLeft=r,t.scrollHeight=n,t.scrollWidth=o,t.clientHeight=s,t.clientWidth=l,this.#ae?.onScroll(t)}this.#it("tbw-scroll",{scrollTop:e,scrollHeight:n,clientHeight:s,direction:"vertical"})}findHeaderRow(){return this.#$.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.#ae?.onCellClick(d)??!1;return this.#it("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.#ae?.onRowClick(n)??!1;return this.#it("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.#ae?.onHeaderClick(r)??!1}_dispatchKeyDown(e){return this.#ae?.onKeyDown(e)??!1}_getHorizontalScrollOffsets(e,t){return this.#ae?.getHorizontalScrollOffsets(e,t)??{left:0,right:0}}query(e,t){return this.#ae?.queryPlugins({type:e,context:t})??[]}_dispatchCellMouseDown(e){return this.#ae?.onCellMouseDown(e)??!1}_dispatchCellMouseMove(e){this.#ae?.onCellMouseMove(e)}_dispatchCellMouseUp(e){this.#ae?.onCellMouseUp(e)}_afterCellRender(e){this.#ae?.afterCellRender(e)}_hasAfterCellRenderHook(){return this.#ae?.hasAfterCellRenderHook()??!1}_afterRowRender(e){this.#ae?.afterRowRender(e)}_hasAfterRowRenderHook(){return this.#ae?.hasAfterRowRenderHook()??!1}async ready(){return this.#o}async forceLayout(){return 0===this.#Y.pendingPhase&&this.#Y.requestPhase(de.FULL,"forceLayout"),this.#Y.whenReady()}async getConfig(){return Object.freeze({...this.#m||{}})}getRowId(e){return Qe(e,this.id,this.#m.getRowId)}getRow(e){return this.#ge.getRow(e)}_getRowEntry(e){return this.#dt(),this.#Se.get(e)}updateRow(e,t,i="api"){this.#ge.updateRow(e,t,i)}updateRows(e,t="api"){this.#ge.updateRows(e,t)}animateRow(e,t){return Xe(this,e,t)}animateRows(e,t){return function(e,t,i){return Promise.all(t.map(t=>Xe(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):Xe(e,o,i)}(this,e,t)}async insertRow(e,t,i=!0){return this.#ge.insertRow(e,t,i)}async removeRow(e,t=!0){return this.#ge.removeRow(e,t)}async applyTransaction(e,t=!0){return this.#ge.applyTransaction(e,t)}applyTransactionAsync(e){return this.#ge.applyTransactionAsync(e)}focusCell(e,t){this.#he.focusCell(e,t)}get focusedCell(){return this.#he.focusedCell}scrollToRow(e,t){this.#he.scrollToRow(e,t)}scrollToRowById(e,t){this.#he.scrollToRowById(e,t)}setColumnVisible(e,t){const i=this.#K.setColumnVisible(e,t);return i&&this.requestStateChange(),i}toggleColumnVisibility(e){const t=this.#K.toggleColumnVisibility(e);return t&&this.requestStateChange(),t}isColumnVisible(e){return this.#K.isColumnVisible(e)}showAllColumns(){this.#K.showAllColumns(),this.requestStateChange()}getAllColumns(){return this.#K.getAllColumns()}setColumnOrder(e){this.#K.setColumnOrder(e),this.requestStateChange()}getColumnOrder(){return this.#K.getColumnOrder()}getColumnState(){const e=this.#ae?.getAll()??[];return this.#K.collectState(e)}get columnState(){return this.getColumnState()}applyColumnState(e){e&&(this.#B?this.#wt(e):(this.#R=e,this.#K.initialColumnState=e))}#wt(e){const t=this._columns,i=this._sortState,r=this.#ae?.getAll()??[];this.#K.applyState(e,r);if(!e.columns.some(e=>void 0!==e.sort)&&this.#mt(t,i))return this.#ke=void 0,x(this),void this.#Y.requestPhase(de.STYLE,"column-width");this.#Ue()}#mt(e,t){const i=this._columns,r=this._sortState;if(t?.field!==r?.field||t?.direction!==r?.direction)return!1;if(e.length!==i.length)return!1;for(let n=0;n<e.length;n++){const t=e[n],r=i[n];if(t.field!==r.field)return!1;if(!!t.hidden!=!!r.hidden)return!1}return!0}get sortModel(){return this._sortState?{field:this._sortState.field,direction:1===this._sortState.direction?"asc":"desc"}:null}sort(e,t){if(null===e){if(!this._sortState)return;const e=this._sortState.field;this._sortState=null,this.__rowRenderEpoch++;for(let t=0;t<this._rowPool.length;t++)this._rowPool[t].__epoch=-1;return this._rows=this.__originalOrder.slice(),this.__originalOrder=[],le(this),this.refreshVirtualWindow(!0),this.dispatchEvent(new CustomEvent("sort-change",{detail:{field:e,direction:0}})),this._pluginManager?.emitPluginEvent?.("sort-change",{field:e,direction:0}),void this.requestStateChange?.()}const i=this._columns.find(t=>t.field===e);i&&(t?(this._sortState||(this.__originalOrder=this._rows.slice()),te(this,i,"desc"===t?-1:1)):ee(this,i))}requestStateChange(){const e=this.#ae?.getAll()??[];this.#K.requestStateChange(e)}resetColumnState(){this.#R=void 0,this.__originalOrder=[];const e=this.#ae?.getAll()??[];this.#K.resetState(e),this.#K.merge(),this.#Ue()}get isToolPanelOpen(){return this.#be.isPanelOpen}get defaultRowHeight(){return this._virtualization.rowHeight}get expandedToolPanelSections(){return this.#be.expandedSections}openToolPanel(){this.#be.openToolPanel()}closeToolPanel(){this.#be.closeToolPanel()}toggleToolPanel(){this.#be.toggleToolPanel()}toggleToolPanelSection(e){this.#be.toggleToolPanelSection(e)}getToolPanels(){return this.#be.getToolPanels()}registerToolPanel(e){this.#me.apiToolPanelIds.add(e.id),this.#be.registerToolPanel(e)}unregisterToolPanel(e){this.#me.apiToolPanelIds.delete(e),this.#be.unregisterToolPanel(e)}getHeaderContents(){return this.#be.getHeaderContents()}registerHeaderContent(e){this.#me.apiHeaderContentIds.add(e.id),this.#be.registerHeaderContent(e)}unregisterHeaderContent(e){this.#me.apiHeaderContentIds.delete(e),this.#be.unregisterHeaderContent(e)}getToolbarContents(){return this.#be.getToolbarContents()}registerToolbarContent(e){this.#be.registerToolbarContent(e)}unregisterToolbarContent(e){this.#be.unregisterToolbarContent(e)}#bt=!1;refreshShellHeader(){this.#bt||(this.#bt=!0,queueMicrotask(()=>{if(this.#bt=!1,!this.isConnected)return;this.#$e(),this.#K.markSourcesChanged(),this.#K.merge(),vt(this.#me);(function(e,t,i,r){const n=e.querySelector(`.${R.ROOT}`),o=n?.querySelector(".tbw-grid-content");if(!n||!o)return Ct(e,t,i,r);o.remove();const s=ct(t);if(n.replaceChildren(),s){n.className=`${R.ROOT} has-shell`;const{headerOptions:e,bodyOptions:s}=yt(t,i,r),l=lt(e),a=at(s),d=a.querySelector(".tbw-grid-content");d&&d.replaceWith(o),n.appendChild(l),n.appendChild(a)}else n.className=R.ROOT,n.appendChild(o);return s})(this.#$,this.#m?.shell,{isPanelOpen:this.#me.isPanelOpen,expandedSections:this.#me.expandedSections},this.#m?.icons)&&(this.#vt(),this.#be.setInitialized(!0)),this.#yt()}))}#yt(){const e=this.#$.querySelector(".tbw-grid-content")??this.#$.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.#be.isInitialized){ft(this.#$,this.#me),pt(this.#$,this.#m?.shell,this.#me);const e=this.#m?.shell?.toolPanel?.defaultOpen;e&&this.#me.toolPanels.has(e)&&(this.openToolPanel(),this.#me.expandedSections.add(e)),this.#me.isPanelOpen&&(bt(this.#$,this.#me),wt(this.#$,this.#me,(this.#m,this.#m)),mt(this.#$,this.#me))}this._resizeController=Ke(this),this.#Oe(e),this.#Y.requestPhase(de.COLUMNS,"shellRefresh")}#je=new Map;registerStyles(e,t){let i=this.#je.get(e);i||(i=new CSSStyleSheet,this.#je.set(e,i)),i.replaceSync(t),this.#Ct()}unregisterStyles(e){this.#je.delete(e)&&this.#Ct()}getRegisteredStyles(){return Array.from(this.#je.keys())}#Ct(){const e=Array.from(this.#je.values()),t=document.adoptedStyleSheets.filter(e=>!Array.from(this.#je.values()).includes(e));document.adoptedStyleSheets=[...t,...e]}registerExternalFocusContainer(e){this.#he.registerExternalFocusContainer(e)}unregisterExternalFocusContainer(e){this.#he.unregisterExternalFocusContainer(e)}containsFocus(e){return this.#he.containsFocus(e)}#$e(){ut(this,this.#me),ht(this,this.#me),gt(this,this.#me,this.#ze())}#xt(){const e=this.#$.querySelector(".tbw-shell-header");if(!e)return;vt(this.#me);const t=function(e,t,i){const r=e?.header?.title??t.lightDomTitle??"",n=!!r;let o="";void 0!==i&&(o="string"==typeof i?F(i):i.outerHTML);const 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,u=t.toolPanels.size>0,h=c&&u,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(h&&(p+='<div class="tbw-toolbar-separator"></div>'),u){const e=t.isPanelOpen;p+=`<button class="${e?"tbw-toolbar-btn active":"tbw-toolbar-btn"}" data-panel-toggle data-icon="tool-panel" 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.#m.shell,this.#me,this.#m.icons?.toolPanel),i=document.createElement("div");i.innerHTML=t;const r=i.firstElementChild;r&&(e.replaceWith(r),this.#vt(),pt(this.#$,this.#m?.shell,this.#me))}#Ke(){const e=()=>{const e=this.#me.lightDomTitle,t=this.#me.hasToolButtonsContainer;this.#$e();const i=this.#me.lightDomTitle,r=this.#me.hasToolButtonsContainer;(i&&!e||r&&!t)&&(this.#K.markSourcesChanged(),this.#K.merge(),this.#xt())},t=()=>{this.__lightDomColumnsCache=void 0,this.#Ue()};this.#K.registerLightDomHandler("tbw-grid-header",e),this.#K.registerLightDomHandler("tbw-grid-tool-buttons",e),this.#K.registerLightDomHandler("tbw-grid-tool-panel",e),this.#K.registerLightDomHandler("tbw-grid-column",t),this.#K.registerLightDomHandler("tbw-grid-detail",t),this.#K.observeLightDOM(this)}refreshColumns(){this.__lightDomColumnsCache=void 0,ke(this),this.#K.parseLightDomColumns(this);const e=this.#me.lightDomTitle,t=this.#me.hasToolButtonsContainer;this.#$e();const i=this.#me.lightDomTitle,r=this.#me.hasToolButtonsContainer;(i&&!e||r&&!t)&&(this.#K.markSourcesChanged(),this.#K.merge(),this.#xt()),this.#Y.requestPhase(de.COLUMNS,"refreshColumns")}#et(){this.#ue.updateCachedGeometry()}refreshVirtualWindow(e=!1,t=!1){return this.#ue.refreshVirtualWindow(e,t)}invalidateRowHeight(e,t){this.#ue.invalidateRowHeight(e,t)}#Be(){this.#$e(),this.#K.markSourcesChanged(),this.#K.merge();const e=this.#m?.shell;Ct(this.#$,e,{isPanelOpen:this.#me.isPanelOpen,expandedSections:this.#me.expandedSections},this.#m?.icons)&&(this.#vt(),this.#be.setInitialized(!0))}#vt(){!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.#$,this.#m,this.#me,{onPanelToggle:()=>this.toggleToolPanel(),onSectionToggle:e=>this.toggleToolPanelSection(e)}),this.#ve?.(),this.#ve=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 u=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`},h=()=>{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",u),document.removeEventListener("mouseup",h)},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",u),document.addEventListener("mouseup",h)};return n.addEventListener("mousedown",g),()=>{n.removeEventListener("mousedown",g),document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",h)}}(this.#$,this.#m?.shell,e=>{this.style.setProperty("--tbw-tool-panel-width",`${e}px`)}),this.#ye?.(),this.#ye=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.#m?.shell,this.#me,()=>this.closeToolPanel())}}customElements.get(Wt.tagName)||customElements.define(Wt.tagName,Wt),globalThis.DataGridElement=Wt;function Kt(e,t,i=!0){let r=e;if(i&&(r=r.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.utility)),t?.length){const e=new Set(t);r=r.filter(t=>e.has(t.field))}return r}function Vt(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}function jt(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 Ut(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 Yt(e){if(null==e)return 100;if("number"==typeof e)return e;const t=parseFloat(e);return isNaN(t)?100:t}function Xt(e){return e.map(e=>Yt(e.width))}function Zt(e){const t=[];let i=0;for(const r of e)t.push(i),i+=Yt(r.width);return t}function Qt(e){return e.reduce((e,t)=>e+Yt(t.width),0)}function Jt(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 ei="@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 ti(e,t){return("function"==typeof e?e(t):e).filter(e=>!0!==e.hidden&&("function"!=typeof e.hidden||!e.hidden(t)))}function ii(e,t){return!0===e.disabled||"function"==typeof e.disabled&&e.disabled(t)}function ri(e,t,i,r){const n=document.createElement("div");n.className="tbw-context-menu",n.setAttribute("role","menu");const o=e.some(e=>!e.separator&&e.icon);for(const s of e){if(s.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",s.cssClass&&e.classList.add(s.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",s.id),e.setAttribute("tabindex","-1");const l=ii(s,t);if(l&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),s.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=F(s.icon),e.appendChild(t)}else if(o){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=s.name,e.appendChild(a),s.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(s.shortcut))s.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=s.shortcut,t.appendChild(e)}e.appendChild(t)}if(s.subMenu?.length){const n=document.createElement("span");n.className="tbw-context-menu-arrow",n.dataset.icon=z("submenuArrow"),void 0!==r&&("string"==typeof r?n.innerHTML=F(r):r instanceof HTMLElement&&n.appendChild(r.cloneNode(!0))),e.appendChild(n),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!s.subMenu)return;const n=ri(ti(s.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||!s.action||s.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),i(s)}),n.appendChild(e)}return n}const ni="getContextMenuItems";let oi=null,si=null,li=0;const ai=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:e=>{const t=e.grid;t?.query?.("clipboard:copy")}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:e=>{const t=e.grid;t?.query?.("export:csv")}}];class di extends ${static manifest={queries:[{type:ni,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:ai}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),li++}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","--tbw-icon-submenu-arrow"];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 di.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(!si&&"undefined"!=typeof document&&ei&&(si=document.createElement("style"),si.id="tbw-context-menu-styles",si.textContent=ei,document.head.appendChild(si)),!oi){oi=new AbortController;const e=oi.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(){li--,li>0||(oi&&(oi.abort(),oi=null),si&&(si.remove(),si=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(ni,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=ti(this.config.items??ai,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=ri(o,e,t=>{t.action&&t.action(e),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.grid?.gridConfig?.icons?.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,u=0;if(d){const e=d.getBoundingClientRect();c=e.left+e.width/2,u=e.bottom}const h=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:h};return this.openMenuAt(g,c,u,!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 ci(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 ui="__tbw_null__";function hi(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 ci(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?ui:"",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===ui?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 gi(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 pi{#Rt=new Map;#Et;constructor(e){this.#Et=e}setInvalid(e,t,i=""){let r=this.#Rt.get(e);r||(r=new Map,this.#Rt.set(e,r)),r.set(t,i),this.#Et(e,t,!0)}clearInvalid(e,t){const i=this.#Rt.get(e);i&&(i.delete(t),0===i.size&&this.#Rt.delete(e)),this.#Et(e,t,!1)}clearRowInvalid(e){const t=this.#Rt.get(e);if(t){const i=Array.from(t.keys());this.#Rt.delete(e),i.forEach(t=>this.#Et(e,t,!1))}}clearAllInvalid(){const e=Array.from(this.#Rt.entries());this.#Rt.clear(),e.forEach(([e,t])=>{t.forEach((t,i)=>this.#Et(e,i,!1))})}isCellInvalid(e,t){return this.#Rt.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#Rt.get(e)?.get(t)}hasInvalidCells(e){const t=this.#Rt.get(e);return!!t&&t.size>0}getInvalidFields(e){return new Map(this.#Rt.get(e)??[])}}function fi(e,t,i){const r=e.get(t);return!!r&&!wi(r,i)}function wi(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(!wi(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(!wi(i[e],r[e]))return!1;return!0}return!1}function mi(e,t,i){e.set(t,structuredClone(i))}function bi(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 vi{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 fi(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&&fi(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&&!wi(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)&&fi(this.baselines,e,t),hasBaseline:this.baselines.has(e)}}markPristine(e,t){mi(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&&mi(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&&fi(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&&fi(this.baselines,i,r)&&t.push(i)}for(const i of this.newRowIds)t.push(i);return t}revertRow(e,t){const i=bi(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&&bi(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 yi='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function Ci(e){return"string"==typeof e&&("__proto__"!==e&&"constructor"!==e&&"prototype"!==e)}function xi(e){}function Ri(e,t){return!1===e.onBeforeEditClose?.(t)}function Ei(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:u,editorValueCallbacks:h}=e;let g;try{g=a.getRowId?.(t)}catch{}const f=g?e=>a.updateRow(g,e,"cascade"):xi,w=Ci(r.field)?t[r.field]:void 0;o.classList.add("editing"),u.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=g?a._getRowEntry(g):void 0,s=o?.row??t,l=o?.index??i;e.commitCellValue(l,r,n,s)},y=()=>{if(b=!0,Ci(r.field)){const e=g?a._getRowEntry(g):void 0;(e?.row??t)[r.field]=w}},C=document.createElement("div");C.className="tbw-editor-host",o.firstElementChild&&a.__frameworkAdapter?.releaseCell?.(o),o.innerHTML="",o.appendChild(C),C.addEventListener("keydown",t=>{if(!t.defaultPrevented){if("Enter"===t.key){const e=t.target;if(e&&"true"===e.getAttribute?.("aria-expanded")&&e.hasAttribute?.("aria-controls"))return}if("Enter"===t.key){if(d){t.stopPropagation(),t.preventDefault();const e=C.querySelector("input,textarea,select");return void(e&&v(gi(e,r,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=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 i=r.getTypeDefault(t.type,e._hostElement);if(i?.editor)return i.editor}}(a,x)??hi(r),S=w,_=`${i}:${r.field}`,A=[];h.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),u=i.__compiledEditor;u?c.innerHTML=u({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(!Ci(t))return"";const i=r[t];return null==i?"":String(i)})||"")});const h=c.querySelector("input,textarea,select");if(h){h instanceof HTMLInputElement&&"checkbox"===h.type?h.checked=!!n:h.value=String(n??"");let t=!1;h.addEventListener("blur",()=>{t||o(gi(h,i,n))}),h.addEventListener("keydown",r=>{const l=r;if("Enter"===l.key){if(Ri(e.config,l))return;l.stopPropagation(),l.preventDefault(),t=!0,o(gi(h,i,n)),e.exitRowEdit(a,!1)}if("Escape"===l.key){if(Ri(e.config,l))return;l.stopPropagation(),l.preventDefault(),s(),e.exitRowEdit(a,!0)}}),h instanceof HTMLInputElement&&"checkbox"===h.type&&h.addEventListener("change",()=>o(h.checked)),l||setTimeout(()=>h.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(yi);e?.focus({preventScroll:!0})})}else if("function"==typeof E){const i=E({row:t,rowId:g??"",value:S,field:r.field,column:r,commit:v,cancel:y,updateRow:f,onValueChange:k,grid:e.grid});if("string"==typeof i)C.innerHTML=i,function(e,t,i,r){const n=e.querySelector("input,textarea,select");n&&(n.addEventListener("blur",()=>{i(gi(n,t,r))}),n instanceof HTMLInputElement&&"checkbox"===n.type?n.addEventListener("change",()=>i(n.checked)):n instanceof HTMLSelectElement&&n.addEventListener("change",()=>i(gi(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(i instanceof Node){C.appendChild(i);i instanceof HTMLInputElement||i instanceof HTMLSelectElement||i instanceof HTMLTextAreaElement?k(e=>{i instanceof HTMLInputElement&&"checkbox"===i.type?i.checked=!!e:i.value=String(e??"")}):o.setAttribute("data-editor-managed","")}else!i&&C.hasChildNodes()&&o.setAttribute("data-editor-managed","");s||queueMicrotask(()=>{const e=C.querySelector(yi);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:g??"",value:S,field:r.field,column:r,commit:v,cancel:y,updateRow:f,onValueChange:k,grid:e.grid};if(E.mount)try{E.mount({placeholder:i,context:n,spec:E})}catch(T){p("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 _i(e,t,i,r={}){const n=r.delimiter??",",o=r.newline??"\n",s=r.quoteStrings??!0,l=[],a=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)});l.push(e.join(n))}for(const d of e){const e=t.map(e=>{let t=W(d,e);return i.processCell&&(t=i.processCell(t,e.field,d)),Si(t,s)});l.push(e.join(n))}return a+l.join(o)}function Ai(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 ki(e){return JSON.stringify(Ti(e))}function Ti(e){if(null==e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Ti);const t={};for(const i of Object.keys(e).sort())t[i]=Ti(e[i]);return t}class Ii{#St=new Map;#_t=0;register(e){const t=ki(e),i=this.#St.get(t);if(i)return i.id;this.#_t++;const r=`s${this.#_t}`;return this.#St.set(t,{id:r,style:e}),r}getStyleId(e){return this.#St.get(ki(e))?.id}get size(){return this.#St.size}toXml(){if(0===this.#St.size)return"";let e="\n<Styles>";for(const{id:t,style:i}of this.#St.values())e+=Mi(t,i);return e+="\n</Styles>",e}}function Mi(e,t){let i=`\n<Style ss:ID="${e}">`;if(t.font&&(i+="<Font",t.font.name&&(i+=` ss:FontName="${t.font.name}"`),t.font.size&&(i+=` ss:Size="${t.font.size}"`),t.font.bold&&(i+=' ss:Bold="1"'),t.font.italic&&(i+=' ss:Italic="1"'),t.font.color&&(i+=` ss:Color="${t.font.color}"`),i+="/>"),t.fill){const e=t.fill.pattern??"Solid";i+=`<Interior ss:Color="${t.fill.color}" ss:Pattern="${e}"/>`}return t.numberFormat&&(i+=`<NumberFormat ss:Format="${t.numberFormat}"/>`),t.alignment&&(i+="<Alignment",t.alignment.horizontal&&(i+=` ss:Horizontal="${t.alignment.horizontal}"`),t.alignment.vertical&&(i+=` ss:Vertical="${t.alignment.vertical}"`),t.alignment.wrapText&&(i+=' ss:WrapText="1"'),i+="/>"),t.borders&&(i+="<Borders>",t.borders.top&&(i+=Li("Top",t.borders.top)),t.borders.bottom&&(i+=Li("Bottom",t.borders.bottom)),t.borders.left&&(i+=Li("Left",t.borders.left)),t.borders.right&&(i+=Li("Right",t.borders.right)),i+="</Borders>"),i+="</Style>",i}function Li(e,t){let i=`<Border ss:Position="${e}" ss:LineStyle="Continuous" ss:Weight="${function(e){switch(e){case"Thin":return 1;case"Medium":return 2;case"Thick":return 3}}(t.style)}"`;return t.color&&(i+=` ss:Color="${t.color}"`),i+="/>",i}function Pi(e,t,i,r,n){if(t.cellStyle){const o=t.cellStyle(i,r,n);if(o)return e.register(o)}const o=t.columnStyles?.[r];return o?e.getStyleId(o):t.defaultStyle?e.getStyleId(t.defaultStyle):void 0}function Di(e,t){const i=Math.min(t.length,50);let r=(e.header??e.field).length;for(let n=0;n<i;n++){const i=t[n][e.field],o=null==i?0:String(i).length;o>r&&(r=o)}return r+2}function Fi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Hi(e,t,i){const r=i.excelStyles,n=r?function(e){const t=new Ii;if(e.headerStyle&&t.register(e.headerStyle),e.defaultStyle&&t.register(e.defaultStyle),e.columnStyles)for(const i of Object.values(e.columnStyles))t.register(i);return t}(r):void 0;let o='<?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">';if(n){if(r.cellStyle)for(const i of e)for(const e of t){const t=W(i,e),o=r.cellStyle(t,e.field,i);o&&n.register(o)}o+=n.toXml()}o+='\n<Worksheet ss:Name="Sheet1">\n<Table>',r&&(o+=function(e,t,i){const r=i.columnWidths,n=i.autoFitColumns;if(!r&&!n)return"";let o="";for(const s of e){let e=r?.[s.field];null==e&&n&&(e=Di(s,t)),o+=null!=e?`\n<Column ss:Width="${7*e}"/>`:"\n<Column/>"}return o}(t,e,r));const s=r?.headerStyle&&n?n.getStyleId(r.headerStyle):void 0;if(!1!==i.includeHeaders){o+="\n<Row>";for(const e of t){const t=e.header||e.field;o+=`<Cell${s?` ss:StyleID="${s}"`:""}><Data ss:Type="String">${Fi(i.processHeader?i.processHeader(t,e.field):t)}</Data></Cell>`}o+="</Row>"}for(const l of e){o+="\n<Row>";for(const e of t){let t=W(l,e);i.processCell&&(t=i.processCell(t,e.field,l));let s="String",a="";null==t?a="":"number"!=typeof t||isNaN(t)?t instanceof Date?(s="DateTime",a=t.toISOString()):a=Fi(String(t)):(s="Number",a=String(t));const d=n&&r?Pi(n,r,t,e.field,l):void 0;o+=`<Cell${d?` ss:StyleID="${d}"`:""}><Data ss:Type="${s}">${a}</Data></Cell>`}o+="</Row>"}return o+="\n</Table>\n</Worksheet>\n</Workbook>",o}const Gi="(Blank)";function Ni(e){if("number"==typeof e)return e;if(e instanceof Date)return e.getTime();const t=Number(e);if(!isNaN(t))return t;return new Date(e).getTime()}function Oi(e,t,i=!1,r){if(!t.length)return e;const n=t.map(e=>function(e,t,i){const r=e.field,n=e.operator,o=i?e=>i(e[r],e):e=>e[r];if("blank"===n)return e=>{const t=o(e);return null==t||""===t||"number"==typeof t&&isNaN(t)};if("notBlank"===n)return e=>{const t=o(e);return null!=t&&""!==t&&!("number"==typeof t&&isNaN(t))};if(i&&("notIn"===n||"in"===n)){const t=e.value;if("notIn"===n){if(!Array.isArray(t))return()=>!0;const e=new Set(t);return t=>{const n=i(t[r],t),o=Array.isArray(n)?n:null!=n?[n]:[];return 0===o.length?!e.has(Gi):!o.some(t=>e.has(t))}}if(!Array.isArray(t))return()=>!1;const o=new Set(t);return e=>{const t=i(e[r],e),n=Array.isArray(t)?t:null!=t?[t]:[];return 0===n.length?o.has(Gi):n.some(e=>o.has(e))}}if("notIn"===n){if(!Array.isArray(e.value))return()=>!0;const t=new Set(e.value);return e=>{const i=e[r];return null==i||""===i?!t.has(Gi):!t.has(i)}}if("in"===n){if(!Array.isArray(e.value))return()=>!1;const t=new Set(e.value);return e=>{const i=e[r];return null==i||""===i?t.has(Gi):t.has(i)}}const s="number"===e.type&&!i,l=e=>null==e||""===e||"number"==typeof e&&isNaN(e);if("greaterThan"===n){const t=Ni(e.value);return s?e=>{const i=e[r];return!l(i)&&i>t}:e=>{const i=o(e);if(l(i))return!1;const r=Ni(i);return!isNaN(r)&&r>t}}if("greaterThanOrEqual"===n){const t=Ni(e.value);return s?e=>{const i=e[r];return!l(i)&&i>=t}:e=>{const i=o(e);if(l(i))return!1;const r=Ni(i);return!isNaN(r)&&r>=t}}if("lessThan"===n){const t=Ni(e.value);return s?e=>{const i=e[r];return!l(i)&&i<t}:e=>{const i=o(e);if(l(i))return!1;const r=Ni(i);return!isNaN(r)&&r<t}}if("lessThanOrEqual"===n){const t=Ni(e.value);return s?e=>{const i=e[r];return!l(i)&&i<=t}:e=>{const i=o(e);if(l(i))return!1;const r=Ni(i);return!isNaN(r)&&r<=t}}if("between"===n){const t=Ni(e.value),i=Ni(e.valueTo);return s?e=>{const n=e[r];return!l(n)&&(n>=t&&n<=i)}:e=>{const r=o(e);if(l(r))return!1;const n=Ni(r);return!isNaN(n)&&n>=t&&n<=i}}const a=t?String(e.value):String(e.value).toLowerCase();return"contains"===n?t?e=>{const t=o(e);return null!=t&&String(t).includes(a)}:e=>{const t=o(e);return null!=t&&String(t).toLowerCase().includes(a)}:"notContains"===n?t?e=>{const t=o(e);return null!=t&&!String(t).includes(a)}:e=>{const t=o(e);return null!=t&&!String(t).toLowerCase().includes(a)}:"equals"===n?t?e=>{const t=o(e);return null!=t&&String(t)===a}:e=>{const t=o(e);return null!=t&&String(t).toLowerCase()===a}:"notEquals"===n?t?e=>{const t=o(e);return null!=t&&String(t)!==a}:e=>{const t=o(e);return null!=t&&String(t).toLowerCase()!==a}:"startsWith"===n?t?e=>{const t=o(e);return null!=t&&String(t).startsWith(a)}:e=>{const t=o(e);return null!=t&&String(t).toLowerCase().startsWith(a)}:"endsWith"===n?t?e=>{const t=o(e);return null!=t&&String(t).endsWith(a)}:e=>{const t=o(e);return null!=t&&String(t).toLowerCase().endsWith(a)}:()=>!0}(e,i,r?.get(e.field)));return 1===n.length?e.filter(n[0]):e.filter(e=>{for(let t=0;t<n.length;t++)if(!n[t](e))return!1;return!0})}function qi(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(Gi),[...r].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t)))}const zi="__tbw_expander";function $i(e){return e.field===zi}function Bi(e){return!0===e.utility}function Wi(e){return e?e.toISOString().split("T")[0]:""}function Ki(e){return e?"string"==typeof e?e:"number"==typeof e?Wi(new Date(e)):"":""}function Vi(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)=>"number"==typeof e&&"number"==typeof t?e-t:d(e).localeCompare(d(t)));const c=document.createElement("div");c.className="tbw-filter-search";const u=document.createElement("input");u.type="text",u.placeholder="Search...",u.className="tbw-filter-search-input",u.value=o.get(s)??"",c.appendChild(u),e.appendChild(c);const h=document.createElement("div");h.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),h.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(h);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:"number"==typeof e&&"number"==typeof t?e-t: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(u.value),e.appendChild(b),u.addEventListener("input",()=>{clearTimeout(S),S=setTimeout(()=>{o.set(s,u.value),E(u.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 ji(e,t){if("number"==typeof e)return e;if("string"==typeof e){const i=parseFloat(e);return isNaN(i)?t:i}return t}class Ui extends ${static manifest={events:[{type:"filter-change",description:"Emitted when filter criteria change. Broadcast to both DOM consumers and plugin bus."}],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}getDataRows(){const e=this.sourceRows;if(e.length>0)return e;const t=this.rows;return 0===t.length?t:t.filter(e=>null!=e&&!0!==e.__loading)}getFilterValues(){const e=this.grid.effectiveConfig?.columns;if(!e)return;let t;for(const i of e)if(i.field)if(i.filterValue)t||(t=new Map),t.set(i.field,i.filterValue);else if(i.valueAccessor){t||(t=new Map);const e=i;t.set(i.field,(t,i)=>W(i,e))}return t}filters=new Map;cachedResult=null;cacheKey=null;cachedInputSpot=null;openPanelField=null;panelElement=null;panelAnchorElement=null;panelButtonElement=null;searchText=new Map;excludedValues=new Map;panelAbortController=null;globalStylesInjected=!1;columnLookup=null;columnLookupRef=null;getColumnByField(e){const t=this.grid.effectiveConfig?.columns;if(!t)return;let i=this.columnLookup;if(t!==this.columnLookupRef||!i){i=new Map;for(const e of t)e.field&&i.set(e.field,e);this.columnLookup=i,this.columnLookupRef=t}return i.get(e)}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.getColumnByField(i),r=e?.filterValue??(e?.valueAccessor?(t,i)=>W(i,e):void 0);t.push({field:i,filterValue:r})}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(Gi),r.set(n,[...o].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t))));return r}(this.getDataRows(),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.getDataRows();if(!i||0===i.length)return void this.excludedValues.delete(e);const r=t.value,n=new Set(r.map(e=>null==e?Gi: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.columnLookup=null,this.columnLookupRef=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("filter:get-model"===e.type){if(!this.filters.size)return;return Object.fromEntries(this.filters)}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){if(!this.filters.size)return e;const t=[...this.filters.values()];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;if(!o)for(const[l,a]of this.filters)"set"===a.type&&"in"===a.operator&&this.syncExcludedValues(l,a);const s=Oi(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(Bi(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");return o.classList.toggle("active",n),e.classList.toggle("filtered",n),n?e.setAttribute("aria-description","Filtered"):e.removeAttribute("aria-description"),void(t!==n&&this.setIcon(o,n?"filterActive":"filter"))}o=document.createElement("button"),o.className="tbw-filter-btn",o.setAttribute("aria-label",`Filter ${i.header??r}`),this.setIcon(o,n?"filterActive":"filter"),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 s=e.querySelector(".resize-handle");s?e.insertBefore(o,s):e.appendChild(o)})}setFilter(e,t,i){if(null===t)this.filters.delete(e),this.syncExcludedValues(e,null);else{const i={...t,field:e};this.filters.set(e,i),this.syncExcludedValues(e,i)}if(this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,i?.silent)this.emitPluginEvent("filter-change",{filters:[...this.filters.values()]});else{this.broadcast("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.();const i=this.getColumnByField(e)?.header??e;o(this.gridElement,s(this.gridElement,null===t?"filterCleared":"filterApplied",i))}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.emitPluginEvent("filter-change",{filters:[...this.filters.values()]}):(this.broadcast("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.()),this.requestRender()}clearAllFilters(e){this.filters.clear(),this.excludedValues.clear(),this.searchText.clear(),this.applyFiltersInternal(e?.silent),e?.silent||o(this.gridElement,s(this.gridElement,"allFiltersCleared"))}clearFieldFilter(e,t){if(this.filters.delete(e),this.excludedValues.delete(e),this.searchText.delete(e),this.applyFiltersInternal(t?.silent),!t?.silent){const t=this.getColumnByField(e)?.header??e;o(this.gridElement,s(this.gridElement,"filterCleared",t))}}isFieldFiltered(e){return this.filters.has(e)}getFilteredRowCount(){return this.cachedResult?.length??this.rows.length}getActiveFilters(){return this.getFilters()}getUniqueValues(e){const t=this.getColumnByField(e),i=t?.filterValue;return qi(this.getDataRows(),e,i)}getStaleFilters(){const e=[];for(const[t,i]of this.filters){if("set"!==i.type)continue;const r=this.getUniqueValues(t);if("notIn"===i.operator&&Array.isArray(i.value)){const t=new Set(i.value);0===r.filter(e=>!t.has(e)).length&&e.push(i)}else if("in"===i.operator&&Array.isArray(i.value)){const t=new Set(i.value);0===r.filter(e=>t.has(e)).length&&e.push(i)}}return e}getBlankMode(e){const t=this.filters.get(e);return"blank"===t?.operator?"blanksOnly":"notBlank"===t?.operator?"nonBlanksOnly":"all"}toggleBlankFilter(e,t){if("all"===t){const t=this.filters.get(e);if(t?.valueTo&&"object"==typeof t.valueTo){const i=t.valueTo;this.setFilter(e,i)}else this.setFilter(e,null);return}const i=this.filters.get(e),r=i&&"blank"!==i.operator&&"notBlank"!==i.operator?{type:i.type,operator:i.operator,value:i.value,valueTo:i.valueTo}:i?.valueTo;this.setFilter(e,{type:i?.type??"text",operator:"blanksOnly"===t?"blank":"notBlank",value:"",valueTo:r})}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);right:anchor(right);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,i.classList.add("active"),this.panelButtonElement=i,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=t.filterValue??(t.valueAccessor?(e,i)=>W(i,t):void 0),o=qi(this.getDataRows(),e,n);document.body.appendChild(r),this.positionPanel(r,i),this.renderPanelContent(e,t,r,o),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?Gi: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.filterType??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,u=ji(s?.min??l?.min,d),h=ji(s?.max??l?.max,c),g=s?.step??l?.step??1,p=r.get(n);let f=u,w=h;const m="blank"===p?.operator;"between"===p?.operator?(f=ji(p.value,u),w=ji(p.valueTo,h)):"greaterThanOrEqual"===p?.operator?f=ji(p.value,u):"lessThanOrEqual"===p?.operator&&(w=ji(p.value,h));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(u),C.max=String(h),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(u),S.max=String(h),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(u),T.max=String(h),T.step=String(g),T.value=String(f);const I=document.createElement("input");I.type="range",I.className="tbw-filter-range-thumb tbw-filter-range-thumb-max",I.min=String(u),I.max=String(h),I.step=String(g),I.value=String(w),_.appendChild(A),_.appendChild(k),_.appendChild(T),_.appendChild(I),e.appendChild(_);const M=document.createElement("label");M.className="tbw-filter-blank-option";const L=document.createElement("input");L.type="checkbox",L.className="tbw-filter-blank-checkbox",L.checked=m;const P=document.createTextNode("Blank");M.appendChild(L),M.appendChild(P);const D=e=>{C.disabled=e,S.disabled=e,T.disabled=e,I.disabled=e,b.classList.toggle("tbw-filter-disabled",e),_.classList.toggle("tbw-filter-disabled",e)};D(m),L.addEventListener("change",()=>{D(L.checked)}),e.appendChild(M);const F=()=>{const e=parseFloat(T.value),t=parseFloat(I.value),i=h-u,r=(e-u)/i*100,n=(t-u)/i*100;k.style.left=`${r}%`,k.style.width=n-r+"%"};T.addEventListener("input",()=>{const e=Math.min(parseFloat(T.value),parseFloat(I.value));T.value=String(e),C.value=String(e),F()}),I.addEventListener("input",()=>{const e=Math.max(parseFloat(I.value),parseFloat(T.value));I.value=String(e),S.value=String(e),F()}),C.addEventListener("input",()=>{const e=parseFloat(C.value);let t=Number.isFinite(e)?e:u;t=Math.max(u,Math.min(t,parseFloat(S.value))),T.value=String(t),F()}),S.addEventListener("input",()=>{const e=parseFloat(S.value);let t=Number.isFinite(e)?e:h;t=Math.min(h,Math.max(t,parseFloat(C.value))),I.value=String(t),F()}),F();const H=document.createElement("div");H.className="tbw-filter-buttons";const G=document.createElement("button");G.className="tbw-filter-apply-btn",G.textContent="Apply",G.addEventListener("click",()=>{if(L.checked)return void t.applyTextFilter("blank","");const e=parseFloat(C.value),i=parseFloat(S.value),r=Number.isFinite(e)?e:u,n=Number.isFinite(i)?i:h;r!==u||n!==h?t.applyTextFilter("between",r,n):t.clearFilter()}),H.appendChild(G);const N=document.createElement("button");N.className="tbw-filter-clear-btn",N.textContent="Clear Filter",N.addEventListener("click",()=>{t.clearFilter()}),H.appendChild(N),e.appendChild(H)}(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,u=Ki(s?.min)||Ki(l?.min)||Wi(d),h=Ki(s?.max)||Ki(l?.max)||Wi(c),g=r.get(n);let p="",f="";const w="blank"===g?.operator;"between"===g?.operator?(p=Ki(g.value)||"",f=Ki(g.valueTo)||""):"greaterThanOrEqual"===g?.operator?p=Ki(g.value)||"":"lessThanOrEqual"===g?.operator&&(f=Ki(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",u&&(y.min=u),h&&(y.max=h),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",u&&(E.min=u),h&&(E.max=h),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 I=document.createElement("button");I.className="tbw-filter-apply-btn",I.textContent="Apply",I.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(I);const M=document.createElement("button");M.className="tbw-filter-clear-btn",M.textContent="Clear Filter",M.addEventListener("click",()=>{t.clearFilter()}),T.appendChild(M),e.appendChild(T)}(i,l,r,this.filters):Vi(i,l,r,o,{caseSensitive:this.config.caseSensitive,debounceMs:this.config.debounceMs},this.searchText)}}setupPanelCloseHandler(e,t){this.panelAbortController=new AbortController;const{signal:i}=this.panelAbortController;setTimeout(()=>{i.aborted||document.addEventListener("click",i=>{e.contains(i.target)||i.target===t||this.closeFilterPanel()},{signal:i})},0)}closeFilterPanel(){const e=this.panelElement;if(e&&(e.remove(),this.panelElement=null),this.panelAnchorElement&&(this.panelAnchorElement.style.anchorName="",this.panelAnchorElement=null),this.panelButtonElement){const e=this.openPanelField;e&&this.filters.has(e)||this.panelButtonElement.classList.remove("active"),this.panelButtonElement=null}this.openPanelField=null,this.panelAbortController?.abort(),this.panelAbortController=null}static supportsAnchorPositioning=null;static checkAnchorPositioningSupport(){return null===Ui.supportsAnchorPositioning&&(Ui.supportsAnchorPositioning=CSS.supports("anchor-name","--test")),Ui.supportsAnchorPositioning}positionPanel(e,t){const i=t.closest(".header-row")??t;if(i.style.anchorName="--tbw-filter-anchor",this.panelAnchorElement=i,Ui.checkAnchorPositioningSupport()){i.style.anchorName="",t.style.anchorName="--tbw-filter-anchor",this.panelAnchorElement=t;const r=i.getBoundingClientRect().bottom-t.getBoundingClientRect().bottom;return e.style.marginTop=`${r+4}px`,void requestAnimationFrame(()=>{const i=e.getBoundingClientRect(),r=t.getBoundingClientRect();i.top<r.top&&e.classList.add("tbw-filter-panel-above")})}const r=i.getBoundingClientRect(),n=t.getBoundingClientRect();e.style.position="fixed",e.style.top=`${r.bottom+4}px`,e.style.left=`${n.right}px`,requestAnimationFrame(()=>{const t=e.getBoundingClientRect();e.style.left=n.right-t.width+"px";n.right-t.width<8&&(e.style.left=`${n.left}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){const n=this.getColumnByField(e),o=n?.filterType??n?.type??"text";this.filters.set(e,{field:e,type:o,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.emitPluginEvent("filter-change",{filters:t}):(this.broadcast("filter-change",{filters:t,filteredRowCount:i.length,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.()),this.requestRender()};return void(i&&"function"==typeof i.then?i.then(r):r(i))}e?this.emitPluginEvent("filter-change",{filters:t}):(this.broadcast("filter-change",{filters:t,filteredRowCount:0,selected:this.computeSelected()}),this.config.trackColumnState&&this.grid.requestStateChange?.()),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 Yi(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,u=t[t.length-1];u&&!u.implicit&&u.id===a?u.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){const t=function(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}(e),i=function(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}(e,t);return{merged:i,embedded:t}}function Zi(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 Qi(e,t,i){return i?.valueAccessor?W(e,i):e?.[t]}function Ji(e){return null==e||""===e||"number"==typeof e&&isNaN(e)}const er={sum:(e,t,i)=>{let r=0;for(let n=0;n<e.length;n++){const o=Qi(e[n],t,i);if(Ji(o))continue;const s=Number(o);isNaN(s)||(r+=s)}return r},avg:(e,t,i)=>{if(!e.length)return 0;let r=0,n=0;for(let o=0;o<e.length;o++){const s=Qi(e[o],t,i);if(Ji(s))continue;const l=Number(s);isNaN(l)||(r+=l,n++)}return n>0?r/n:0},count:e=>e.length,min:(e,t,i)=>{if(!e.length)return 0;let r=1/0;for(let n=0;n<e.length;n++){const o=Qi(e[n],t,i);if(Ji(o))continue;const s=Number(o);isNaN(s)||s<r&&(r=s)}return r===1/0?0:r},max:(e,t,i)=>{if(!e.length)return 0;let r=-1/0;for(let n=0;n<e.length;n++){const o=Qi(e[n],t,i);if(Ji(o))continue;const s=Number(o);isNaN(s)||s>r&&(r=s)}return r===-1/0?0:r},first:(e,t,i)=>e[0]?Qi(e[0],t,i):void 0,last:(e,t,i)=>e.length?Qi(e[e.length-1],t,i):void 0},tr=new Map,ir={register(e,t){tr.set(e,t)},unregister(e){tr.delete(e)},get(e){if(void 0!==e)return"function"==typeof e?e:tr.get(e)??er[e]},run(e,t,i,r){const n=this.get(e);return n?n(t,i,r):void 0},has:e=>tr.has(e)||e in er,list:()=>[...Object.keys(er),...tr.keys()]},rr={sum:e=>{let t=0;for(let i=0;i<e.length;i++)t+=e[i];return t},avg:e=>{if(!e.length)return 0;let t=0;for(let i=0;i<e.length;i++)t+=e[i];return t/e.length},count:e=>e.length,min:e=>{if(!e.length)return 0;let t=e[0];for(let i=1;i<e.length;i++)e[i]<t&&(t=e[i]);return t},max:e=>{if(!e.length)return 0;let t=e[0];for(let i=1;i<e.length;i++)e[i]>t&&(t=e[i]);return t},first:e=>e[0]??0,last:e=>e[e.length-1]??0};function nr({rows:e,config:t,expanded:i,initialExpanded:r,groupSortDirections:n}){const o=t.groupOn;if("function"!=typeof o)return[];const s={key:"__root__",value:null,depth:-1,rows:[],children:new Map};if(e.forEach(e=>{let t=o(e);null==t||!1===t?t=["__ungrouped__"]:Array.isArray(t)||(t=[t]);let i=s;t.forEach((t,r)=>{const n=null==t?"∅":String(t),o="__root__"===i.key?n:i.key+"||"+n;let s=i.children.get(n);s||(s={key:o,value:t,depth:r,rows:[],children:new Map,parent:i},i.children.set(n,s)),s.rows.push(e),i=s})}),1===s.children.size&&s.children.has("__ungrouped__")){if(s.children.get("__ungrouped__").rows.length===e.length)return[]}const l=new Map;for(let h=0;h<e.length;h++)l.set(e[h],h);const a=new Set([...i,...r??[]]),d=e=>{const t=[...e.children.values()],i=e===s?0:e.depth+1,r=n?.get(i)??1;return t.sort((e,t)=>{const i=e.value,n=t.value;return null==i&&null==n?0:null==i?r:null==n?-r:i>n?r:i<n?-r:0}),t},c=[],u=e=>{if(e===s){for(const t of d(e))u(t);return}const t=a.has(e.key);if(c.push({kind:"group",key:e.key,value:e.value,depth:e.depth,rows:e.rows,expanded:t}),t)if(e.children.size)for(const i of d(e))u(i);else e.rows.forEach(e=>c.push({kind:"data",row:e,rowIndex:l.get(e)??-1}))};return u(s),c}function or(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}function sr({groups:e,expanded:t,groupRows:i,loadingGroups:r,parentPath:n=[]}){const o=[],s=n.length;for(const l of e){const e=[...n,l.key],a=t.has(l.key),d=i.get(l.key)??[],c=r.has(l.key);if(o.push({kind:"group",key:l.key,value:l.value,depth:s,rows:d,expanded:a}),a)if(l.children?.length){const n=sr({groups:l.children,expanded:t,groupRows:i,loadingGroups:r,parentPath:e});o.push(...n)}else c?o.push({kind:"data",row:{__loading:!0,__groupKey:l.key},rowIndex:-1}):d.forEach((e,t)=>{o.push({kind:"data",row:e,rowIndex:t})})}return o}function lr(e,t,i=[]){for(const r of e){const e=[...i,r.key];if(r.key===t)return e;if(r.children?.length){const i=lr(r.children,t,e);if(i.length>0)return i}}return[]}function ar(e,t){return e.has(t)?e.delete(t):e.add(t),e}function dr(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 cr extends ${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}}}";static dependencies=[{name:"serverSide",required:!1,reason:"Fetches detail data via datasource:fetch-children on expand"}];get#At(){return this.grid}get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,animation:"slide"}}attach(e){super.attach(e),this.parseLightDomDetail(),this.on("datasource:children",e=>{const t=e;if("master-detail"!==t.context?.source)return;t.claimed=!0;const i=t.context.row;if(i&&this.expandedRows.has(i)){this.detailDataMap.set(i,t.rows),this.loadingDetails.delete(i);const e=this.detailElements.get(i);e&&(e.remove(),this.detailElements.delete(i),this.measuredDetailHeights.delete(i)),this.requestRender()}})}parseLightDomDetail(){const e=this.gridElement;if(!e)return;const t=e.querySelector("tbw-grid-detail");if(!t)return;const i=this.#At.__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)=>F(G(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.#kt(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)}#kt(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;loadingDetails=new Set;detailDataMap=new Map;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:cr.DEFAULT_DETAIL_HEIGHT}toggleAndEmit(e,t){if(e?.__isGroupRow)return;this.expandedRows=ar(this.expandedRows,e);const i=this.expandedRows.has(e);if(i){if(this.rowsToAnimate.add(e),!this.detailDataMap.has(e)){const i=this.grid?.query?.("datasource:is-active",null);i&&(this.loadingDetails.add(e),this.grid.query("datasource:fetch-children",{context:{source:"master-detail",row:e,rowIndex:t}}))}}else this.loadingDetails.delete(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(),this.loadingDetails.clear(),this.detailDataMap.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($i)}(t);if(i)return t;const r=(n=this.name,{field:zi,header:"",width:32,resizable:!1,sortable:!1,filterable:!1,lockPosition:!0,utility:!0,meta:{expanderColumn:!0,expanderPlugin:n}});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,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.#Tt())}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusCol,i=this.grid._focusRow,r=this.visibleColumns[t];if(!r||!$i(r))return;const n=this.rows[i];return n?(e.preventDefault(),this.toggleAndEmit(n,i),this.requestRenderWithFocus(),!0):void 0}afterRender(){this.#It(),this.#Tt()}#It(){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.#Tt()}#Tt(){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.#At.__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=dr(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.#kt(i,e,d)})}}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){return e.add(t),e}(this.expandedRows,t),this.requestRender())}collapse(e){const t=this.rows[e];t&&(this.expandedRows=function(e,t){return e.delete(t),e}(this.expandedRows,t),this.requestRender())}toggle(e){const t=this.rows[e];t&&!t.__isGroupRow&&(this.expandedRows=ar(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}getDetailData(e){const t=this.rows[e];return t?this.detailDataMap.get(t):void 0}isDetailLoading(e){const t=this.rows[e];return!!t&&this.loadingDetails.has(t)}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.#At;"function"==typeof e.refreshColumns?e.refreshColumns():this.requestRender()}}}function ur(e,t){const i=!0===e?.__loading;return i===(!0===t?.__loading)?0:i?1:-1}function hr(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 gr(e,t){const i=e.findIndex(e=>e.field===t);return i>=0?i+1:void 0}function pr(e,t){return e.find(e=>e.field===t)?.direction}function fr(e){return e.pinned??e.meta?.pinned}function wr(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 mr(e,t){const i=fr(e);return!!i&&"left"===wr(i,t)}function br(e,t){const i=fr(e);return!!i&&"right"===wr(i,t)}function vr(e){for(let t=0;t<e.length;t++)if(null!=e[t].pinned||null!=e[t].meta?.pinned)return!0;return!1}function yr(e,t){const i={groupEndAdjustments:{addGroupEnd:new Set,removeGroupEnd:new Set},leftOffsets:new Map,rightOffsets:new Map,splitGroups:[]},r=Array.from(e.querySelectorAll(".header-row .cell"));if(!r.length)return i;const n=me(e),o=new Map,s=new Map;let l=0;for(const u of t)if(mr(u,n)){const t=r.find(e=>e.getAttribute("data-field")===u.field);t&&(o.set(u.field,l),t.classList.add(R.STICKY_LEFT),t.style.position="sticky",t.style.left=l+"px",e.querySelectorAll(`.data-grid-row .cell[data-field="${u.field}"]`).forEach(e=>{e.classList.add(R.STICKY_LEFT),e.style.position="sticky",e.style.left=l+"px"}),l+=t.offsetWidth)}let a=0;for(const u of[...t].reverse())if(br(u,n)){const t=r.find(e=>e.getAttribute("data-field")===u.field);t&&(s.set(u.field,a),t.classList.add(R.STICKY_RIGHT),t.style.position="sticky",t.style.right=a+"px",e.querySelectorAll(`.data-grid-row .cell[data-field="${u.field}"]`).forEach(e=>{e.classList.add(R.STICKY_RIGHT),e.style.position="sticky",e.style.right=a+"px"}),a+=t.offsetWidth)}const d=[],c=function(e,t,i,r,n){const o={addGroupEnd:new Set,removeGroupEnd:new Set},s=Array.from(e.querySelectorAll(".header-group-row .header-group-cell"));if(!s.length)return o;for(const l of s){const e=l.style.gridColumn;if(!e)continue;const s=e.match(/^(\d+)\s*\/\s*span\s+(\d+)$/);if(!s)continue;const a=parseInt(s[1],10)-1,d=a+parseInt(s[2],10)-1,c=t.slice(a,d+1);if(!c.length)continue;const u=c.every(e=>mr(e,r)),h=c.every(e=>br(e,r));if(u){const e=c[0].field,t=i.find(t=>t.getAttribute("data-field")===e);t&&(l.classList.add(R.STICKY_LEFT),l.style.position="sticky",l.style.left=t.style.left)}else if(h){const e=c[c.length-1].field,t=i.find(t=>t.getAttribute("data-field")===e);t&&(l.classList.add(R.STICKY_RIGHT),l.style.position="sticky",l.style.right=t.style.right)}else if(l.classList.contains("implicit-group"))xr(l,c,a,i,r,o);else{const e=c.some(e=>mr(e,r)),t=c.some(e=>br(e,r));(e||t)&&Rr(l,c,a,i,r,o,n)}}return o}(e,t,r,n,d);if(c.addGroupEnd.size>0||c.removeGroupEnd.size>0){for(const t of c.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 c.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{groupEndAdjustments:c,leftOffsets:o,rightOffsets:s,splitGroups:d}}function Cr(e,t){return mr(e,t)?"left":br(e,t)?"right":"none"}function xr(e,t,i,r,n,o){const s=[];for(let d=0;d<t.length;d++){const e=Cr(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(R.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(R.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 Rr(e,t,i,r,n,o,s){const l=[];for(let y=0;y<t.length;y++){const e=Cr(t[y],n),r=l[l.length-1];r&&r.state===e?r.cols.push(t[y]):l.push({state:e,cols:[t[y]],colStart:i+y})}if(l.length<=1)return;const a=e.parentElement;if(!a)return;const d=e.textContent||"",c=e.getAttribute("data-group")||"",u=e.nextSibling;a.removeChild(e);const h=l.findIndex(e=>"left"===e.state);let g=-1;for(let y=l.length-1;y>=0;y--)if("right"===l[y].state){g=y;break}const p=h>=0?h:g,f=h>=0&&h+1<l.length?h+1:g>=0&&g-1>=0?g-1:-1;let w,m,b,v="";for(let y=0;y<l.length;y++){const t=l[y],i=document.createElement("div");if(i.className=e.className,i.setAttribute("data-group",c),i.style.gridColumn=`${t.colStart+1} / span ${t.cols.length}`,"left"===t.state){const e=t.cols[0].field,n=r.find(t=>t.getAttribute("data-field")===e);n&&(i.classList.add(R.STICKY_LEFT),i.style.position="sticky",i.style.left=n.style.left,n.style.left),y===p&&(i.style.borderRightStyle="none",w=i,v=t.cols[t.cols.length-1].field)}else if("right"===t.state){const e=t.cols[t.cols.length-1].field,n=r.find(t=>t.getAttribute("data-field")===e);n&&(i.classList.add(R.STICKY_RIGHT),i.style.position="sticky",i.style.right=n.style.right),y===p&&(i.style.borderLeftStyle="none",w=i,v=t.cols[0].field)}if(y===f){i.style.overflow="visible";const e=document.createElement("span");e.textContent=d,e.style.position="relative",e.style.zIndex="36",e.style.display="block",e.style.overflow="hidden",e.style.textOverflow="ellipsis",e.style.whiteSpace="nowrap",i.appendChild(e),m=i,b=e}u?a.insertBefore(i,u):a.appendChild(i)}w&&m&&b&&v&&s.push({groupId:c,label:d,pinnedFragment:w,scrollableFragment:m,floatLabel:b,pinnedField:v,isTransferred:!1,floatOffset:0})}function Er(e){e.querySelectorAll(`.${R.STICKY_LEFT}, .${R.STICKY_RIGHT}`).forEach(e=>{e.classList.remove(R.STICKY_LEFT,R.STICKY_RIGHT),e.style.position="",e.style.left="",e.style.right=""})}const Sr="canMoveColumn";function _r(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=Lr(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 Ar(e){const t=document.createElement("div");return t.className=`tbw-aggregation-rows tbw-aggregation-rows-${e}`,t.setAttribute("role","presentation"),t}function kr(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?Tr(t,o,i,r):Ir(t,o,i,r),e.appendChild(t)}}function Tr(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}=Mr(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 Ir(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}=Mr(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 Mr(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=ir.get(o.aggFunc);e&&(r=e(i,t.field,t)),n=o.formatter}else{const e=ir.get(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 Lr(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=F(r):i.appendChild(r),i}function Pr(e,t,i,r,n){const o=i?.sourceRows,s=i?.rows,l=Array.isArray(o)?o.length:e.length,a=Array.isArray(s)?s.length:e.length,d=l>0?l:a;return{totalRows:d,filteredRows:n?.cachedResult?.length??(a<l?a:d),selectedRows:r?.selected?.size??0,columns:t,rows:e,grid:i}}function Dr(e){const t=document.createElement("div");return t.className="tbw-status-panel tbw-status-panel-custom",t.appendChild(e),t}function Fr(e,t){const i=document.createElement("div");i.className="tbw-pinned-rows",i.setAttribute("role","presentation"),i.setAttribute("aria-live","polite"),e.id&&i.setAttribute("data-pinned-row-id",e.id);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");o.className="tbw-pinned-rows-right";const s={left:r,center:n,right:o},l=Array.isArray(e.render)?e.render:[{zone:"left",render:e.render}];for(const a of l){const e=a.zone??"left",i=a.render(t);if(null==i)continue;const r=i.classList?.contains("tbw-status-panel");s[e].appendChild(r?i:Dr(i))}return 0===r.children.length&&0===n.children.length&&0===o.children.length?null:(i.appendChild(r),i.appendChild(n),i.appendChild(o),i)}function Hr(e,t,i,r,n=!1){const o=Ar(t);return kr(o,[e],i,r,n),o}function Gr(e){return"function"==typeof e?e:function(e){return rr[e]??rr.sum}(e)}function Nr(e,t){return[...e,t].join("|")}function Or(e,t){const i=t.rowGroupFields??[],r=t.columnGroupFields??[],n=t.valueFields??[],o=function(e,t,i="asc"){if(0===t.length)return["value"];const r=new Set;for(const o of e){const e=t.map(e=>String(o[e]??"")).join("|");r.add(e)}const n=[...r].sort();return"desc"===i?n.reverse():n}(e,r,t.sortColumns),s=qr(e,i,r,o,n,0,"");t.sortRows&&Wr(s,t.sortRows,n);const 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=Nr([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 qr(e,t,i,r,n,o,s){const l=[];if(0===t.length){const t=zr(e,i,r,n),a=$r(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,u=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[h,g]of u){const e=s?`${s}|${h}`:h,t=zr(g,i,r,n),a=$r(t);let u;c&&(u=qr(g,d,i,r,n,o+1,e)),l.push({rowKey:e,rowLabel:h||"(blank)",depth:o,values:t,total:a,isGroup:c,children:u,rowCount:g.length})}return l}function zr(e,t,i,r){const n={};if(0===t.length){for(const t of r){const i=[];for(let n=0;n<e.length;n++){const r=e[n][t.field];if(null==r||""===r)continue;const o=Number(r);isNaN(o)||i.push(o)}const r=Gr(t.aggFunc);n[Nr(["value"],t.field)]=i.length>0?r(i):null}return n}const o=new Map;for(let s=0;s<e.length;s++){const i=e[s];let r=String(i[t[0]]??"");for(let e=1;e<t.length;e++)r+="|",r+=String(i[t[e]]??"");const n=o.get(r);n?n.push(i):o.set(r,[i])}for(const s of i){const e=o.get(s);if(e&&0!==e.length)for(const t of r){const i=[];for(let n=0;n<e.length;n++){const r=e[n][t.field];if(null==r||""===r)continue;const o=Number(r);isNaN(o)||i.push(o)}const r=Gr(t.aggFunc);n[Nr([s],t.field)]=i.length>0?r(i):null}else for(const t of r)n[Nr([s],t.field)]=null}return n}function $r(e){let t=0;for(const i of Object.values(e))t+=i??0;return t}function Br(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}function Wr(e,t,i){const r="desc"===t.direction?-1:1;e.sort((e,n)=>{if("value"===t.by){if(t.valueField??i[0]?.field){return((e.total??0)-(n.total??0))*r}}return e.rowLabel.localeCompare(n.rowLabel)*r});for(const n of e)n.children?.length&&Wr(n.children,t,i)}function Kr(e,t,i){if(0===t.length)return;const r=new Set(i.map(e=>e.field)),n=t.map(e=>"value"===e.by?e.valueField?t=>((e,t)=>{if(null!=e.values[t])return"number"==typeof e.values[t]?e.values[t]:0;if(r.has(t)){const i=`|${t}`;let r=0,n=!1;for(const t of Object.keys(e.values))t.endsWith(i)&&(r+="number"==typeof e.values[t]?e.values[t]:0,n=!0);if(n)return r}return e.total??0})(t,e.valueField):e=>e.total??0:null);e.sort((e,i)=>{for(let r=0;r<t.length;r++){const o=t[r],s="desc"===o.direction?-1:1;let l=0;if("value"===o.by){const t=n[r];l=(t(e)-t(i))*s}else l=e.rowLabel.localeCompare(i.rowLabel)*s;if(0!==l)return l}return 0});for(const o of e)o.children?.length&&Kr(o.children,t,i)}const Vr=["sum","avg","count","min","max","first","last"];function jr(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(Ur("Options",()=>function(e,t){const{config:i,callbacks:r,signal:n}=t,o=document.createElement("div");return o.className="tbw-pivot-options",o.appendChild(Qr("Enable Pivot View",e,e=>{r.onTogglePivot(e)},n)),o.appendChild(Qr("Show Row Totals",i.showTotals??!0,e=>{r.onOptionChange("showTotals",e)},n)),o.appendChild(Qr("Show Grand Total",i.showGrandTotal??!0,e=>{r.onOptionChange("showGrandTotal",e)},n)),o}(i,o))),s.appendChild(Ur("Row Groups",()=>Yr("rowGroups",o))),s.appendChild(Ur("Column Groups",()=>Yr("columnGroups",o))),s.appendChild(Ur("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",n.appendChild(e)}else for(const s of o)n.appendChild(Zr(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(Ur("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{const e=document.createElement("div");if(e.className="tbw-pivot-fields-list",l.length>=6){const t=document.createElement("input");t.type="text",t.placeholder="Filter fields…",t.className="tbw-pivot-field-search",t.addEventListener("input",()=>{const i=t.value.toLowerCase();for(const t of e.querySelectorAll(".tbw-pivot-field-chip")){const e=t;e.style.display=e.textContent?.toLowerCase().includes(i)?"":"none"}},{signal:r}),n.appendChild(t)}for(const t of l){const i=document.createElement("div");i.className="tbw-pivot-field-chip available",i.textContent=t.header,i.draggable=!0,i.title=`Drag to add "${t.field}" to a zone`,i.addEventListener("dragstart",e=>{e.dataTransfer?.setData("text/plain",t.field),i.classList.add(R.DRAGGING)},{signal:r}),i.addEventListener("dragend",()=>{i.classList.remove(R.DRAGGING)},{signal:r}),e.appendChild(i)}n.appendChild(e)}return n}(o))),e.appendChild(s),()=>{n.abort(),s.remove()}}function Ur(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 Yr(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",o.appendChild(e)}else for(const l of s)o.appendChild(Xr(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"),n=t.dataTransfer?.getData("source-zone");if(!i)return;const s=o.querySelectorAll(".tbw-pivot-field-chip");let l=s.length;for(let e=0;e<s.length;e++){const i=s[e].getBoundingClientRect();if(t.clientY<i.top+i.height/2){l=e;break}}!n||n===e||"rowGroups"!==n&&"columnGroups"!==n?n===e?r.onReorderFieldInZone(i,e,l):r.onAddFieldToZone(i,e):r.onMoveFieldBetweenZones(i,n,e)},{signal:n}),o}function Xr(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(R.DRAGGING)},{signal:n}),o.addEventListener("dragend",()=>{o.classList.remove(R.DRAGGING)},{signal:n}),o}function Zr(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="function"==typeof e.aggFunc,d=document.createElement("select");if(d.className="tbw-pivot-agg-select",d.title="Aggregation function",a){const e=document.createElement("option");e.value="__custom__",e.textContent="CUSTOM",e.selected=!0,d.appendChild(e),d.disabled=!0}for(const u of Vr){const t=document.createElement("option");t.value=u,t.textContent=u.toUpperCase(),a||(t.selected=u===e.aggFunc),d.appendChild(t)}d.addEventListener("change",()=>{i.onUpdateValueAggFunc(e.field,d.value)},{signal:r});const c=document.createElement("button");return c.className="tbw-pivot-chip-remove",c.innerHTML="×",c.title="Remove value field",c.addEventListener("click",t=>{t.stopPropagation(),i.onRemoveValueField(e.field)},{signal:r}),s.appendChild(l),s.appendChild(d),n.appendChild(s),n.appendChild(c),n}function Qr(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}function Jr(e,t,i){return t.className="data-grid-row pivot-grand-total-row",t.innerHTML="",i.forEach((i,r)=>{const n=document.createElement("div");if(n.className="cell",n.setAttribute("data-col",String(r)),0===r){const e=document.createElement("span");e.className="pivot-label",e.textContent="Grand Total",n.appendChild(e)}else{const t=e[i.field];n.textContent=null!=t?i.format?i.format(t,e):String(t):""}t.appendChild(n)}),!0}class en extends ${static manifest={modifiesRowStructure:!0,hookPriority:{onHeaderClick:-10,processRows:100},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."}],queries:[{type:"sort:get-sort-config",description:"Returns the current pivot sort configuration"}]};static dependencies=[{name:"multiSort",required:!1,reason:"Queries sort model for pivot column sorting"}];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)}@media(hover:hover){.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-direction:column;gap:var(--tbw-spacing-sm, .375rem);min-height:40px}.tbw-pivot-field-search{width:100%;padding:.25rem .5rem;border:1px solid var(--tbw-color-border, #d0d5dd);border-radius:var(--tbw-radius-sm, .25rem);font-size:var(--tbw-font-size-sm, .875rem);background:var(--tbw-color-bg, #fff);color:var(--tbw-color-fg, #1a1a2e);outline:none}.tbw-pivot-field-search:focus{border-color:var(--tbw-color-primary, #3b82f6)}.tbw-pivot-fields-list{display:flex;flex-wrap:wrap;gap:var(--tbw-spacing-sm, .375rem)}.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;valueFormatters=new Map;columnTotals={};activeSortField=null;activeSortDir=null;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,this.valueFormatters.clear(),this.columnTotals={},this.activeSortField=null,this.activeSortDir=null,this.config.sortRows=void 0}getToolPanel(){if(!1!==(this.config?.showToolPanel??this.userConfig?.showToolPanel??!0))return{id:en.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.buildValueFormatters(),this.defaultExpanded=this.config.defaultExpanded??!0,this.pivotResult=Or(e,this.config);const i=this.getMultiSortConfigs();if(i&&Kr(this.pivotResult.rows,i,this.config.valueFields??[]),0===this.expandedKeys.size&&!this.userHasToggledExpand){const e=Br(this.pivotResult.rows);this.expandedKeys=function(e,t){if(!0===e||void 0===e)return new Set(t);if(!1===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}(this.defaultExpanded,e)}this.config.valueDisplayMode&&"raw"!==this.config.valueDisplayMode&&(this.columnTotals=function(e,t,i){const r={};return function e(n){for(const o of n)if(o.isGroup&&o.children?.length)o.children&&e(o.children);else for(const e of t)for(const t of i){const i=Nr([e],t.field);r[i]=(r[i]??0)+(o.values[i]??0)}}(e),r}(this.pivotResult.rows,this.pivotResult.columnKeys,this.config.valueFields??[]));const r=this.config.indentWidth??20,n=!0===this.defaultExpanded||void 0===this.defaultExpanded,o=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,n).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*r,__pivotTotal:e.total,...e.values}));this.keysToAnimate.clear();const s=new Set;for(const l of o){const e=l.__pivotRowKey;s.add(e),!this.previousVisibleKeys.has(e)&&l.__pivotDepth>0&&this.keysToAnimate.add(e)}return this.previousVisibleKeys=s,this.config.grandTotalInRowModel&&this.config.showGrandTotal&&this.pivotResult&&o.push({__pivotRowKey:"__grandTotal",__pivotLabel:"Grand Total",__pivotIsGrandTotal:!0,__pivotDepth:0,__pivotTotal:this.pivotResult.grandTotal,...this.pivotResult.totals}),o}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,sortable:!0});for(const r of this.pivotResult.columnKeys)for(const e of this.config.valueFields??[]){const i=Nr([r],e.field),n=e.header||this.fieldHeaderMap.get(e.field)||e.field,o="function"==typeof e.aggFunc?"custom":e.aggFunc,s=this.valueFormatters.get(e.field);t.push({field:i,header:`${r} - ${n} (${o})`,width:120,type:"number",sortable:!0,...s?{format:e=>null!=e?s(Number(e)):""}:{}})}return this.config.showTotals&&t.push({field:"__pivotTotal",header:"Total",width:100,type:"number",sortable:!0}),t}renderRow(e,t,i){const r=e;return r.__pivotIsGrandTotal?Jr(r,t,this.gridColumns):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,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?r.format?r.format(t,e):String(t):""}t.appendChild(o)}),!0}(r,t,{columns:this.gridColumns,rowIndex:i,onToggle:e=>this.toggle(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?i.format?i.format(t,e):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}handleQuery(e){if("sort:get-sort-config"===e.type){const e=this.getMultiSortConfigs();return e||(this.config.sortRows??null)}}onHeaderClick(e){if(!this.isActive)return!1;const t=e.field;if(!this.isPivotField(t))return!1;if(this.isMultiSortActive())return!1;const i=this.mapFieldToSortConfig(t);if(!i)return!1;const r=this.activeSortDir;let n;n=this.activeSortField!==t?"asc":"asc"===r?"desc":null,this.activeSortField=n?t:null,this.activeSortDir=n,this.config.sortRows=n?{...i,direction:n}:void 0,this.emit("pivot-config-change",{property:"sortRows"}),this.refresh();const l=this.gridElement;if(l){const i=e.column.header??t;o(l,n?s(l,"sortApplied",i,"asc"===n?"ascending":"descending"):s(l,"sortCleared"))}return!0}isPivotField(e){return"__pivotLabel"===e||"__pivotTotal"===e||e.includes("|")}isMultiSortActive(){const e=this.grid?.query?.("sort:get-model",null);return Array.isArray(e)&&e.length>0}getMultiSortConfigs(){const e=this.grid?.query?.("sort:get-model",null);if(!e||0===e.length)return null;const t=e[0];if(!Array.isArray(t)||0===t.length)return null;const i=[];for(const r of t){if(!this.isPivotField(r.field))continue;const e=this.mapFieldToSortConfig(r.field);e&&i.push({...e,direction:r.direction})}return i.length>0?i:null}mapFieldToSortConfig(e){return"__pivotLabel"===e?{by:"label"}:"__pivotTotal"===e?{by:"value"}:e.includes("|")?{by:"value",valueField:e}:null}afterRender(){this.isActive&&this.config.showGrandTotal&&this.pivotResult&&!this.config.grandTotalInRowModel?this.renderGrandTotalFooter():this.cleanupGrandTotalFooter(),this.isActive&&!this.isMultiSortActive()&&this.updateSortIndicators();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()}updateSortIndicators(){const e=this.gridElement;if(!e)return;const t=this.activeSortField,i=this.activeSortDir,r=t?null:this.config.sortRows,n=e.querySelectorAll(".header-row .cell[data-field]");for(const o of n){const e=o.getAttribute("data-field");if(!e||!this.isPivotField(e))continue;let n=null;t===e?n=i:r&&("label"===r.by&&"__pivotLabel"===e?n=r.direction??"asc":"value"!==r.by||"__pivotTotal"!==e||r.valueField?"value"===r.by&&r.valueField&&e===r.valueField&&(n=r.direction??"asc"):n=r.direction??"asc"),this.updateSortIndicator(o,n)}}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));Jr({__pivotRowKey:"__grandTotal",__pivotLabel:"Grand Total",__pivotIsGrandTotal:!0,__pivotTotal:this.pivotResult.grandTotal,...this.pivotResult.totals},this.grandTotalFooter,this.gridColumns),this.grandTotalFooter.setAttribute("role","presentation")}cleanupGrandTotalFooter(){this.grandTotalFooter&&(this.grandTotalFooter.remove(),this.grandTotalFooter=null)}toggle(e){this.userHasToggledExpand=!0;const t=this.expandedKeys.has(e);t?this.expandedKeys.delete(e):this.expandedKeys.add(e),this.emitToggle(e,!t),this.requestRender()}expand(e){this.userHasToggledExpand=!0,this.expandedKeys.add(e),this.emitToggle(e,!0),this.requestRender()}collapse(e){this.userHasToggledExpand=!0,this.expandedKeys.delete(e),this.emitToggle(e,!1),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=Br(this.pivotResult.rows);for(const t of e)this.expandedKeys.add(t)}isExpanded(e){return this.expandedKeys.has(e)}getExpandedGroups(){return[...this.expandedKeys]}enablePivot(){0===this.originalColumns.length&&this.captureOriginalColumns(),this.isActive=!0,this.emit("pivot-state-change",{active:!0}),this.requestRender()}disablePivot(){this.isActive=!1,this.pivotResult=null,this.emit("pivot-state-change",{active:!1}),this.requestRender()}isPivotActive(){return this.isActive}getPivotResult(){return this.pivotResult}setRowGroupFields(e){this.config.rowGroupFields=e,this.emitConfigChange("rowGroupFields"),this.refresh()}setColumnGroupFields(e){this.config.columnGroupFields=e,this.emitConfigChange("columnGroupFields"),this.refresh()}setValueFields(e){this.config.valueFields=e,this.emitConfigChange("valueFields"),this.refresh()}refresh(){this.pivotResult=null,this.requestRender()}showPanel(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(en.PANEL_ID)||this.grid.toggleToolPanelSection(en.PANEL_ID)}hidePanel(){this.grid.closeToolPanel()}togglePanel(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(en.PANEL_ID)}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(en.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),this.emitConfigChange("rowGroups"===t?"rowGroupFields":"columnGroupFields",e,t)},onRemoveFieldFromZone:(e,t)=>{this.removeFieldFromZone(e,t),this.emitConfigChange("rowGroups"===t?"rowGroupFields":"columnGroupFields",e,t)},onReorderFieldInZone:(e,t,i)=>{this.reorderFieldInZone(e,t,i),this.emitConfigChange("rowGroups"===t?"rowGroupFields":"columnGroupFields",e,t)},onMoveFieldBetweenZones:(e,t,i)=>{this.moveFieldBetweenZones(e,t,i),this.emitConfigChange("rowGroups"===i?"rowGroupFields":"columnGroupFields",e,i)},onAddValueField:(e,t)=>{this.addValueField(e,t),this.emitConfigChange("valueFields",e,"values")},onRemoveValueField:e=>{this.removeValueField(e),this.emitConfigChange("valueFields",e,"values")},onUpdateValueAggFunc:(e,t)=>{this.updateValueAggFunc(e,t),this.emitConfigChange("valueFields",e,"values")},onOptionChange:(e,t)=>{this.config[e]=t,this.emitConfigChange(e),this.isActive&&this.refresh()},getAvailableFields:()=>this.getAvailableFields()};return jr(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()}reorderFieldInZone(e,t,i){const r="rowGroups"===t?[...this.config.rowGroupFields??[]]:[...this.config.columnGroupFields??[]],n=r.indexOf(e);-1!==n&&n!==i&&(r.splice(n,1),r.splice(i>n?i-1:i,0,e),"rowGroups"===t?this.config.rowGroupFields=r:this.config.columnGroupFields=r,this.refreshIfActive())}moveFieldBetweenZones(e,t,i){"rowGroups"===t?this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(t=>t!==e):this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(t=>t!==e),"rowGroups"===i?this.config.rowGroupFields=[...this.config.rowGroupFields??[],e]:this.config.columnGroupFields=[...this.config.columnGroupFields??[],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()}emitToggle(e,t){const i=this.rows.find(t=>t.__pivotRowKey===e);this.emit("pivot-toggle",{key:e,expanded:t,label:i?.__pivotLabel??e,depth:i?.__pivotDepth??0})}emitConfigChange(e,t,i){this.emit("pivot-config-change",{property:e,field:t,zone:i})}buildValueFormatters(){this.valueFormatters.clear();const e=this.config.valueFields??[];for(const t of e)if(t.format)this.valueFormatters.set(t.field,t.format);else{if(this.originalColumns.find(e=>e.field===t.field)){const e=(this.grid.getAllColumns?.()??this.grid.columns??[]).find(e=>e.field===t.field);if(e?.format){const i=e.format;this.valueFormatters.set(t.field,e=>i(e,{}))}}}}}const tn="tbw-print-isolation-style";async function rn(e,t={}){const{orientation:i="landscape"}=t,r=e.id;document.querySelectorAll(`#${CSS.escape(r)}`).length>1&&p("TBW093",`Multiple elements found with id="${r}". Print isolation may not work correctly. Ensure each grid has a unique ID.`,r,"print"),document.getElementById(tn)?.remove();const n=function(e,t){const i=document.createElement("style");return i.id=tn,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(tn)?.remove(),e()};window.addEventListener("afterprint",t),window.print(),setTimeout(()=>{window.removeEventListener("afterprint",t),document.getElementById(tn)?.remove(),e()},5e3)})}const nn={button:!1,orientation:"landscape",warnThreshold:500,maxRows:0,includeTitle:!0,includeTimestamp:!0,title:"",isolate:!1};function on(e){if(!0===e.lockPosition)return!1;if(!0===e.utility)return!1;const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}function sn(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 ln="canMoveColumn";const an=new Map;function dn(e){const t=an.get(e);if(!t)return;if(t.hasPrimitives)return;const i=[];for(const r of t.refs){const e=r.deref();if(void 0===e)return;i.push(e)}return i}function cn(e){an.delete(e)}function un(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const e=new Uint32Array(2);return crypto.getRandomValues(e),`drag-${Date.now().toString(36)}-${e[0].toString(36)}${e[1].toString(36)}`}return`drag-${Date.now().toString(36)}-${(++hn).toString(36)}`}let hn=0,gn=null;function pn(){return gn}function fn(){gn=null}const wn="application/x-tbw-grid-rows+json";function mn(e){const t=e.match(/^application\/x-tbw-grid-rows\+json;zone=(.*)$/);if(!t)return null;try{return decodeURIComponent(t[1])}catch{return t[1]}}function bn(e){return JSON.stringify(e)}function vn(e,t,i,r){if(!e)return{overIndex:null,insertIndex:r,isBefore:!1};const n=i(e);if(n<0)return{overIndex:null,insertIndex:r,isBefore:!1};const o=e.getBoundingClientRect(),s=t<o.top+o.height/2;return{overIndex:n,insertIndex:s?n:n+1,isBefore:s}}const yn="__tbw_row_drag";let Cn=null;const xn=new Set;function Rn(){if("undefined"==typeof BroadcastChannel)return null;if(Cn)return Cn;try{Cn=new BroadcastChannel("tbw-row-drag-drop"),Cn.addEventListener("message",e=>{const t=e.data;if(t&&"tbw-row-drag-drop:transfer"===t.type)for(const i of Array.from(xn))try{i(t)}catch{}})}catch{Cn=null}return Cn}class En extends ${name="rowDragDrop";aliases=["reorderRows","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[draggable=true]{cursor:grab}.data-grid-row[draggable=true].dragging{cursor:grabbing}.tbw-row-drag-clone{position:fixed;top:-10000px;left:-10000px;pointer-events:none}.tbw-row-drag-count{position:fixed;top:-1000px;left:-1000px;pointer-events:none;background:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));color:var(--tbw-color-accent-fg);font:600 12px/1.4 system-ui,sans-serif;border-radius:999px;padding:2px 8px;box-shadow:0 2px 6px var(--tbw-color-shadow);z-index:9999}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before,.data-grid-row.drop-target.drop-after:after{content:"";position:absolute;left:0;right:0;height:var(--tbw-drop-indicator-width, 2px);background-color:var(--tbw-drop-indicator-color, var(--tbw-row-reorder-indicator, var(--tbw-color-accent)));z-index:10;pointer-events:none}.data-grid-row.drop-target.drop-before:before{top:0}.data-grid-row.drop-target.drop-after:after{bottom:0}.tbw-grid--drop-target-active{outline:2px dashed var(--tbw-drop-indicator-color, var(--tbw-color-accent));outline-offset:-2px}.tbw-grid--drop-target-rejected{outline:2px dashed var(--tbw-color-danger);outline-offset:-2px}.tbw-grid--auto-scrolling{cursor:ns-resize}.data-grid-row.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}}';static manifest={events:[{type:"row-move",description:"Intra-grid row reorder.",cancelable:!0},{type:"row-drag-start",description:"Cross-grid drag started on this grid.",cancelable:!0},{type:"row-drag-end",description:"Drag finished on this grid (regardless of outcome)."},{type:"row-drop",description:"Cross-grid drop landing on this grid.",cancelable:!0},{type:"row-transfer",description:"Cross-grid transfer completed (fires on both grids)."}]};get defaultConfig(){return{enableKeyboard:!0,dragHandlePosition:"left",dragHandleWidth:40,debounceMs:150,animation:"flip",operation:"move",autoScroll:!0,dragFrom:"handle"}}shouldRenderDragHandle(){const e=this.config.showDragHandle;return!1!==e&&(!0===e||"row"!==this.config.dragFrom)}get rowIsDraggable(){return"row"===this.config.dragFrom||"both"===this.config.dragFrom}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}isDragging=!1;draggedRowIndex=null;draggedRows=[];draggedIndices=[];dragSessionId=null;dragAccepted=!1;dropRowIndex=null;pendingMove=null;debounceTimer=null;lastFocusCol=0;autoScroller=null;gridId="";remoteTransferListener=e=>this.onRemoteTransfer(e);get internalGrid(){return this.grid}attach(e){super.attach(e);const t=this.gridElement;var i;t&&(this.gridId=t.id||`tbw-grid-${un().slice(0,8)}`,t.id||(t.id=this.gridId),this.setupDelegatedDragListeners(),i=this.remoteTransferListener,xn.add(i),Rn())}detach(){this.clearDebounceTimer(),this.autoScroller?.stop(),this.autoScroller=null,function(e){if(xn.delete(e),0===xn.size&&Cn){try{Cn.close()}catch{}Cn=null}}(this.remoteTransferListener),this.dragSessionId&&cn(this.dragSessionId),fn(),this.resetDragState(),super.detach()}processColumns(e){if(!this.shouldRenderDragHandle())return[...e];const t={field:yn,header:"",width:this.config.dragHandleWidth??40,resizable:!1,sortable:!1,filterable:!1,lockPosition:!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,"dragHandle"),e}};return"right"===this.config.dragHandlePosition?[...e,t]:[t,...e]}afterRender(){this.applyRowDraggable()}onScrollRender(){this.applyRowDraggable()}applyRowDraggable(){const e=this.internalGrid._bodyEl;if(!e)return;const t=this.rowIsDraggable,i=e.querySelectorAll(".data-grid-row");for(const r of i)t?"true"!==r.getAttribute("draggable")&&r.setAttribute("draggable","true"):r.hasAttribute("draggable")&&r.removeAttribute("draggable")}onKeyDown(e){if(!this.config.enableKeyboard)return;if(!e.ctrlKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key)return;const t=this.internalGrid,i=t._focusRow,r=t._rows??this.sourceRows;if(i<0||i>=r.length)return;const n="up"===("ArrowUp"===e.key?"up":"down")?i-1:i+1;if(n<0||n>=r.length)return;const o=r[i];return this.canMoveRow(i,n)?(this.handleKeyboardMove(o,i,n,t._focusCol),e.preventDefault(),e.stopPropagation(),!0):void 0}onCellClick(){this.flushPendingMove()}moveRow(e,t){const i=[...this.sourceRows];e<0||e>=i.length||t<0||t>=i.length||e!==t&&this.canMoveRow(e,t)&&this.executeIntraGridMove(i[e],e,t,"keyboard")}canMoveRow(e,t){const i=this.internalGrid._rows??this.sourceRows;if(e<0||e>=i.length)return!1;if(t<0||t>=i.length)return!1;if(e===t)return!1;const r=i[e],n=this.grid?.query?.("canMoveRow",r);if(Array.isArray(n)&&n.includes(!1))return!1;if(this.config.canDrag&&!this.config.canDrag(r,e))return!1;if(this.config.canMove){const i=t<e?"up":"down";if(!this.config.canMove(r,e,t,i))return!1}if(this.config.canDrop){const i={sessionId:"intra",sourceGridId:this.gridId,dropZone:this.config.dropZone??"",rows:[r],rowIndices:[e],operation:"move"};if(!this.config.canDrop(i,t))return!1}return!0}setupDelegatedDragListeners(){const e=this.gridElement;if(!e)return;const t=this.disconnectSignal;e.addEventListener("dragstart",e=>this.onDragStart(e),{signal:t}),e.addEventListener("dragend",()=>this.onDragEnd(),{signal:t}),e.addEventListener("dragover",e=>this.onDragOver(e),{signal:t}),e.addEventListener("dragleave",e=>this.onDragLeave(e),{signal:t}),e.addEventListener("drop",e=>this.onDrop(e),{signal:t})}onDragStart(e){const t=e.target;if(!t)return;const i=t.closest(".dg-row-drag-handle");let r=null,n=!1;if(i)r=i.closest(".data-grid-row"),n=!0;else if(this.rowIsDraggable){if(this.isInteractiveDragOrigin(t))return;r=t.closest(".data-grid-row")}if(!r)return;const o=this.getRowIndex(r);if(o<0)return;const{rows:s,indices:l}=this.resolveDraggedRows(o);if(0===s.length)return;if(this.config.canDrag&&!this.config.canDrag(s[0],o))return void e.preventDefault();const a=this.config.operation??"move",d=this.config.dropZone??"",c=un(),u={rows:s,indices:l,operation:a,dropZone:d};if(this.emitCancelable("row-drag-start",u))return void e.preventDefault();this.isDragging=!0,this.draggedRowIndex=o,this.draggedRows=s,this.draggedIndices=l,this.dragSessionId=c,this.dragAccepted=!1;const h=this.config.serializeRow??(e=>e),g={sessionId:c,sourceGridId:this.gridId,dropZone:d,rows:s.map(h),rowIndices:l,operation:a};if(e.dataTransfer){e.dataTransfer.effectAllowed="copy"===a?"copyMove":"move";try{e.dataTransfer.setData(wn,bn(g)),d&&e.dataTransfer.setData(`${wn};zone=${encodeURIComponent(d)}`,bn(g)),e.dataTransfer.setData("text/plain",function(e,t){const i=t.filter(e=>!e.utility&&"string"==typeof e.field&&""!==e.field),r=[];for(const n of e){const e=i.map(e=>{const t=n[e.field];return null==t?"":String(t).replace(/[\t\r\n]+/g," ")});r.push(e.join("\t"))}return r.join("\n")}(s,this.columns))}catch{}if(s.length>1){const t=document.createElement("div");t.className="tbw-row-drag-count",t.textContent=`${s.length} rows`,document.body.appendChild(t);try{e.dataTransfer.setDragImage(t,10,10)}catch{}setTimeout(()=>t.remove(),0)}else this.attachRowCloneDragImage(e,r,n?i:null)}!function(e,t,i){const r=[];let n=!1;for(const o of t)null!==o&&"object"==typeof o?r.push(new WeakRef(o)):n=!0;an.set(e,{refs:r,hasPrimitives:n,meta:i})}(c,s),function(e,t){gn={sessionId:e,payload:t}}(c,g),r.classList.add(R.DRAGGING),this.gridElement.classList.add("tbw-grid--drag-source")}static INTERACTIVE_DRAG_SELECTORS='input,textarea,select,button,a,[contenteditable=""],[contenteditable="true"],.dg-cell-editor,.tbw-checkbox-cell';isInteractiveDragOrigin(e){return null!==e.closest(En.INTERACTIVE_DRAG_SELECTORS)}attachRowCloneDragImage(e,t,i){if(!e.dataTransfer)return;const r=t.getBoundingClientRect(),n=t.cloneNode(!0);n.classList.add("tbw-row-drag-clone"),n.classList.remove("dragging","drop-target","drop-before","drop-after","flip-animating","row-focus"),n.removeAttribute("aria-selected"),n.style.width=`${r.width}px`,n.style.height=`${r.height}px`,this.gridElement.appendChild(n);let o=e.clientX-r.left,s=e.clientY-r.top;if(i){const e=i.getBoundingClientRect();o=e.left-r.left+e.width/2,s=e.top-r.top+e.height/2}o=Math.max(0,Math.min(r.width,o)),s=Math.max(0,Math.min(r.height,s));try{e.dataTransfer.setDragImage(n,o,s)}catch{}setTimeout(()=>n.remove(),0)}onDragOver(e){const t=e.dataTransfer;if(!t)return;const i=t.types?Array.from(t.types):[];if(!function(e){for(const t of e)if(t===wn||t.startsWith(`${wn};`))return!0;return!1}(i)&&!this.isDragging)return;const r=this.config.dropZone??"",n=pn(),o=this.isDragging&&n?.payload.sourceGridId===this.gridId;if(!o){if(!r)return;const e=function(e,t){for(const i of e)if(mn(i)===t)return i;return null}(i,r);if(!(e||n&&n.payload.dropZone===r))return}e.preventDefault(),t&&(t.dropEffect=n?.payload.operation??this.config.operation??"move");const s=e.target.closest(".data-grid-row"),l=this.internalGrid._rows??[],a=vn(s,e.clientY,e=>this.getRowIndex(e),l.length);if(o&&null!==a.overIndex&&a.overIndex===this.draggedRowIndex)this.clearDropTargetClasses();else{if(n&&this.config.canDrop){const e=this.config.canDrop(n.payload,a.insertIndex);if(this.gridElement.classList.toggle("tbw-grid--drop-target-active",e),this.gridElement.classList.toggle("tbw-grid--drop-target-rejected",!e),!e)return void this.clearDropTargetClasses()}else this.gridElement.classList.add("tbw-grid--drop-target-active");this.dropRowIndex=a.insertIndex,this.applyDropPositionClasses(s,a.isBefore),!1!==this.config.autoScroll&&(this.ensureAutoScroller(),this.autoScroller?.onPointerMove(e.clientY))}}onDragLeave(e){const t=e.target.closest(".data-grid-row");t&&t.classList.remove("drop-target","drop-before","drop-after"),e.currentTarget&&!this.gridElement.contains(e.relatedTarget)&&(this.gridElement.classList.remove("tbw-grid--drop-target-active","tbw-grid--drop-target-rejected"),this.autoScroller?.stop())}onDrop(e){e.preventDefault(),this.autoScroller?.stop(),this.gridElement.classList.remove("tbw-grid--drop-target-active","tbw-grid--drop-target-rejected"),this.clearDropTargetClasses();const t=e.dataTransfer;if(!t)return;const i=pn();let r=i?.payload??null,n=null;if(r){const e=dn(r.sessionId);e&&(n=e)}else{if(r=function(e){if(!e)return null;try{const t=JSON.parse(e);if("string"!=typeof t?.sessionId||"string"!=typeof t?.sourceGridId||"string"!=typeof t?.dropZone||!Array.isArray(t?.rows)||!Array.isArray(t?.rowIndices)||"move"!==t.operation&&"copy"!==t.operation)return null;for(const e of t.rowIndices)if("number"!=typeof e||!Number.isInteger(e)||e<0)return null;return t}catch{return null}}(t.getData(wn)),r){const e=dn(r.sessionId);e&&(n=e)}}if(!r)return;const o=e.target.closest(".data-grid-row"),s=this.internalGrid._rows??[],l=vn(o,e.clientY,e=>this.getRowIndex(e),s.length);let a=this.dropRowIndex??l.insertIndex;const d=r.sourceGridId===this.gridId,c=this.config.dropZone??"";if(d){const e=r.rowIndices[0];if(1===r.rowIndices.length&&a>e&&a--,e===a)return;const t=(n??r.rows)[0];if(!this.canMoveRow(e,a))return;return void this.executeIntraGridMove(t,e,a,"drag")}if(!c||c!==r.dropZone)return;if(this.config.canDrop&&!this.config.canDrop(r,a))return this.gridElement.classList.add("tbw-grid--drop-target-rejected"),void setTimeout(()=>this.gridElement.classList.remove("tbw-grid--drop-target-rejected"),200);const u=this.config.deserializeRow??(e=>e),h=n??r.rows.map(e=>u(e)),g={payload:r,sourceGridId:r.sourceGridId,targetIndex:a,operation:r.operation};if(this.emitCancelable("row-drop",g))return;const p=[...s];p.splice(a,0,...h),this.grid.rows=p;const f=this.findPeerOnGrid(r.sourceGridId);if("move"===r.operation&&f){const e=document.getElementById(r.sourceGridId);if(e){const t=(e._rows??e.rows??[]).slice(),i=[...r.rowIndices].sort((e,t)=>t-e);for(const e of i)e>=0&&e<t.length&&t.splice(e,1);e.rows=t}}f&&(f.dragAccepted=!0);const w={rows:h,fromGridId:r.sourceGridId,toGridId:this.gridId,fromIndices:r.rowIndices,toIndex:a,operation:r.operation};this.emit("row-transfer",w),f?f.emitTransfer(w):function(e){const t=Rn();if(t)try{t.postMessage(e)}catch{}}({type:"tbw-row-drag-drop:transfer",sessionId:r.sessionId,sourceGridId:r.sourceGridId,toGridId:this.gridId,dropZone:c,rowIndices:r.rowIndices,toIndex:a,operation:r.operation,serializedRows:r.rows})}onRemoteTransfer(e){if(e.sourceGridId!==this.gridId)return;const t=this.config.dropZone??"";if(!t||e.dropZone!==t)return;const i=this.config.deserializeRow??(e=>e),r=e.serializedRows.map(e=>i(e));if("move"===e.operation){const t=(this.internalGrid._rows??this.sourceRows).slice(),i=[...e.rowIndices].sort((e,t)=>t-e);for(const e of i)e>=0&&e<t.length&&t.splice(e,1);this.grid.rows=t}this.dragAccepted=!0,this.emit("row-transfer",{rows:r,fromGridId:e.sourceGridId,toGridId:e.toGridId,fromIndices:e.rowIndices,toIndex:e.toIndex,operation:e.operation})}onDragEnd(){if(this.dragSessionId&&cn(this.dragSessionId),fn(),this.autoScroller?.stop(),this.gridElement.classList.remove("tbw-grid--drag-source"),this.isDragging){const e={rows:this.draggedRows,indices:this.draggedIndices,accepted:this.dragAccepted};this.emit("row-drag-end",e)}this.clearDragClasses(),this.resetDragState()}emitTransfer(e){this.emit("row-transfer",e)}findPeerOnGrid(e){const t=document.getElementById(e);return t?.getPluginByName?t.getPluginByName("rowDragDrop")??null:null}resolveDraggedRows(e){const t=this.internalGrid._rows??this.sourceRows,i=t[e],r=this.grid?.getPluginByName?.("selection");if(r?.getSelectedRowIndices){const i=r.getSelectedRowIndices();if(i.includes(e)&&i.length>1){const e=[...i].sort((e,t)=>e-t);return{rows:e.map(e=>t[e]),indices:e}}}return{rows:[i],indices:[e]}}ensureAutoScroller(){if(this.autoScroller)return;const e=this.gridElement.querySelector(".rows-viewport");if(!e)return;const t="object"==typeof this.config.autoScroll?this.config.autoScroll:void 0;this.autoScroller=function(e,t={},i){const r=t.edgeSize??60,n=t.speed??8,o=t.maxSpeed??24;let s=null,l=null,a=!1;const d=e=>{e!==a&&(a=e,i?.(e))},c=()=>{if(s=null,null===l)return void d(!1);const t=e.getBoundingClientRect();let i=0;if(l<t.top+r){const e=1-Math.max(0,l-t.top)/r;i=-Math.round(n+(o-n)*e)}else if(l>t.bottom-r){const e=1-Math.max(0,t.bottom-l)/r;i=Math.round(n+(o-n)*e)}if(0===i)return void d(!1);const a=e.scrollTop;e.scrollTop=a+i,e.scrollTop!==a?(d(!0),s=requestAnimationFrame(c)):d(!1)};return{onPointerMove(e){l=e,null===s&&(s=requestAnimationFrame(c))},stop(){null!==s&&(cancelAnimationFrame(s),s=null),l=null,d(!1)},get isScrolling(){return a}}}(e,t,e=>{this.gridElement.classList.toggle("tbw-grid--auto-scrolling",e)})}applyDropPositionClasses(e,t){this.clearDropTargetClasses(),e&&(e.classList.add("drop-target"),e.classList.toggle("drop-before",t),e.classList.toggle("drop-after",!t))}clearDropTargetClasses(){this.gridElement?.querySelectorAll(".data-grid-row.drop-target").forEach(e=>{e.classList.remove("drop-target","drop-before","drop-after")})}clearDragClasses(){this.gridElement?.querySelectorAll(".data-grid-row").forEach(e=>{e.classList.remove(R.DRAGGING,"drop-target","drop-before","drop-after")})}resetDragState(){this.isDragging=!1,this.draggedRowIndex=null,this.draggedRows=[],this.draggedIndices=[],this.dragSessionId=null,this.dragAccepted=!1,this.dropRowIndex=null,this.pendingMove=null}getRowIndex(e){const t=e.querySelector(".cell[data-row]");return t?parseInt(t.getAttribute("data-row")??"-1",10):-1}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}handleKeyboardMove(e,t,i,r){this.pendingMove?this.pendingMove.currentIndex=i:this.pendingMove={originalIndex:t,currentIndex:i,row:e},this.lastFocusCol=r;const n=this.internalGrid,o=[...n._rows??this.sourceRows],[s]=o.splice(t,1);o.splice(i,0,s),n._rows=o,n._focusRow=i,n._focusCol=r,n.refreshVirtualWindow(!0),De(n),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=this.internalGrid,n={row:i,fromIndex:e,toIndex:t,rows:[...r._rows??this.sourceRows],source:"keyboard"};this.emitCancelable("row-move",n)&&(r._rows=[...this.sourceRows],r._focusRow=e,r._focusCol=this.lastFocusCol,r.refreshVirtualWindow(!0),De(r))}executeIntraGridMove(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 u=c-l.getBoundingClientRect().top;Math.abs(u)>1&&s.push({el:l,deltaY:u})}),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)})}}function Sn(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 _n(e){const t=Sn(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function An(e){return e.map(_n)}function kn(e,t,i){return i.some(i=>function(e,t,i){const r=Sn(i);return e>=r.startRow&&e<=r.endRow&&t>=r.startCol&&t<=r.endCol}(e,t,i))}function Tn(e){const t=[],i=Sn(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 In(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function Mn(e,t){const i=Sn(e),r=Sn(t);return i.startRow===r.startRow&&i.startCol===r.startCol&&i.endRow===r.endRow&&i.endCol===r.endCol}const Ln="__tbw_checkbox";function Pn(e,t){return Math.floor(e/t)}function Dn(){return new DOMException("Aborted","AbortError")}function Fn(e,t,i,r,n){const o=function(e,t){return{start:e*t,end:(e+1)*t}}(t,i);return function(e,t){return t.aborted?Promise.reject(Dn()):"object"!=typeof(i=e)||null===i||"function"!=typeof i.subscribe||"function"==typeof i.then?new Promise((i,r)=>{const n=()=>r(Dn());t.addEventListener("abort",n,{once:!0}),Promise.resolve(e).then(e=>{t.removeEventListener("abort",n),i(e)},e=>{t.removeEventListener("abort",n),r(e)})}):new Promise((i,r)=>{let n=!1;const o=e.subscribe({next:e=>{n||(n=!0,i(e),o.unsubscribe())},error:e=>{n||(n=!0,r(e))},complete:()=>{n||(n=!0,r(new Error("getRows observable completed without emitting a value")))}});n||t.addEventListener("abort",()=>{n||(n=!0,o.unsubscribe(),r(Dn()))},{once:!0})});var i}(e.getRows({startNode:o.start,endNode:o.end,sortModel:r.sortModel,filterModel:r.filterModel,signal:n}),n)}function Hn(e,t,i){const r=Pn(e,t),n=i.get(r);if(!n)return;return n[e%t]}function Gn(e){return e.scrollWidth>e.clientWidth}function Nn(){return"function"==typeof HTMLElement.prototype?.showPopover}function On(e,t,i){return void 0!==e.id?String(e.id):i?`${i}-${t}`:String(t)}function qn(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}function zn(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=On(l,s,i),d=l[n];if(Array.isArray(d)&&d.length>0){o.add(a);const e=zn(d,t,a,r+1);for(const t of e)o.add(t)}}return o}function $n(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=On(l,s,r);if(a===t)return[a];const d=l[o];if(Array.isArray(d)&&d.length>0){const e=$n(d,t,i,a,n+1);if(e)return[a,...e]}}return null}function Bn(e,t,i,r){const n=$n(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 Wn(e,t){const i=Math.min(t,e.length-1);if(i<0)return 0;let r=i;for(;r>0&&e[r].depth>0;)r--;let n=0;for(let o=0;o<=r;o++)0===e[o].depth&&n++;return n-1}function Kn(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;if(null!=e&&!Array.isArray(e)&&e)return!0}return!1}function Vn(e,t,i){const r=[...e.undoStack,t];for(;r.length>i;)r.shift();return{undoStack:r,redoStack:[]}}function jn(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 Un(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}}class Yn extends ${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(R.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.lockVisible||i.meta?.lockVisibility)return;return[{id:"visibility/hide-column",label:"Hide Column",icon:"👁",order:30,action:()=>this.hideColumn(i.field)}]}}getToolPanel(){return{id:Yn.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(Yn.PANEL_ID)||this.grid.toggleToolPanelSection(Yn.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(Yn.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(Yn.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)}canMoveColumn(e){const t=this.grid.columns.find(t=>t.field===e.field);if(!t)return!1;const i=this.grid.query("canMoveColumn",t);return i.length>0&&!i.includes(!1)}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,"dragHandle"),e.title="Drag to reorder group",o.insertBefore(e,s)}r.appendChild(o);const u=this.grid.getAllColumns().filter(e=>!e.utility);for(const h of t){const e=u.findIndex(e=>e.field===h.field),t=this.createColumnRow(h,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&&this.canMoveColumn(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&&this.canMoveColumn(e)){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,"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(R.DRAGGING),r.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&e.classList.add(R.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(R.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(R.DRAGGING),r.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&e.classList.add(R.DRAGGING)})):this.draggedField&&r.querySelector(`.tbw-visibility-row[data-field="${this.draggedField}"]`)?.classList.add(R.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=Gi,e.BaseGridPlugin=$,e.CORE_CONSUMED_ADAPTER_METHODS=["canHandle","createRenderer","createEditor","processConfig","getTypeDefault","createToolPanelRenderer","parseDetailElement","parseResponsiveCardElement","releaseCell","unmount"],e.ClipboardPlugin=class extends ${static manifest={queries:[{type:"clipboard:copy",description:"Triggers a copy operation and returns the copied text"}]};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}handleQuery(e){if("clipboard:copy"===e.type)return this.copy(),!0}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#Lt(e.target),!0)}#Lt(e){const t=this.#Pt();if(t&&0===t.ranges.length){const t=this.#Dt(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=jt(t,this.config),r=this.#Pt(),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,u=[],h=i[0]?.length??0;for(let p=0;p<h&&s+p<=a;p++){const e=this.visibleColumns[s+p];e&&u.push(e.field)}const g={rows:i,text:t,target:c,fields:u};this.emit("paste",g),this.#Ft(g)}#Ft(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??Ut)(e,this.grid)}#Pt(){const e=this.grid?.query("getSelection");return e?.[0]}#Ht(e){const t=this.#Pt();let i,r;if(e?.columns)i=Kt(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=Kt(this.visibleColumns.slice(r,n+1))}else i=Kt(this.columns);if(e?.rowIndices)r=Vt(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}}#Gt(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=W(a,e);return s?s(t,e.field,a):this.#Nt(e,t,a)});l.push(t.join(r))}return l.join(n)}#Nt(e,t,i){if(e.format)try{const r=e.format(t,i);return null==r?"":String(r)}catch{}if(e.renderer||e.viewRenderer){const t=this.#Ot(e.field,i);if(null!=t)return t}return function(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}(t)}#Ot(e,t){const i=this.gridElement;if(!i)return null;const r=this.rows.indexOf(t);if(-1===r)return null;const n=i.querySelector(`.cell[data-row="${r}"][data-field="${e}"]`);return n?n.textContent?.trim()??null:null}#Dt(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.#Ht(e);return 0===t.length||0===i.length?"":this.#Gt(t,i,e)}async copy(e){const{columns:t,rows:i}=this.#Ht(e);if(0===t.length||0===i.length)return"";const r=this.#Gt(t,i,e);return await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){p("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?jt(e,this.config):null}getLastCopied(){return this.lastCopied}},e.ColumnVirtualizationPlugin=class extends ${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=Xt(t),this.columnOffsets=Zt(t),this.totalWidth=Qt(t),this.endCol=t.length-1}detach(){this.#qt(),this.columnWidths=[],this.columnOffsets=[],this.originalColumns=[],this.isVirtualized=!1,this.startCol=0,this.endCol=0,this.scrollLeft=0,this.totalWidth=0}#qt(){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=Xt(e),this.columnOffsets=Zt(e),this.totalWidth=Qt(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=Jt(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=di,e.DEFAULT_A11Y_MESSAGES=i,e.DEFAULT_ANIMATION_CONFIG=r,e.DEFAULT_GRID_ICONS=n,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",CELL_ACTIVATE:"cell-activate",GROUP_TOGGLE:"group-toggle",COLUMN_STATE_CHANGE:"column-state-change",DATA_CHANGE:"data-change",TBW_SCROLL:"tbw-scroll"},e.DataGridElement=Wt,e.EditingPlugin=class extends ${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:max(var(--tbw-row-height),calc(1lh + 2 * var(--tbw-cell-padding-v, .25em) + var(--tbw-border-width, 1px)));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;align-self:stretch;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#zt(){return"grid"===this.config.mode}#$t(e,t){const i=this.#At.effectiveConfig?.rowEditable;if(i&&!i(t))return!1;const{editable:r}=e;return"function"==typeof r?r(t):!0===r}#Bt(e){return!0===e.editable||"function"==typeof e.editable}#Wt=-1;#Kt;#Vt;#jt=-1;#Ut=new Map;#Yt=new Set;#Xt=new Map;#Zt=!1;#Qt=-1;#Jt;#ei=!1;#ti=!1;#ii=!1;#ri=null;#ni=new vi;#oi;get#At(){return this.grid}attach(e){super.attach(e);const t=this.disconnectSignal,i=this.#At;if(this.#Jt=new pi((e,t,i)=>{this.#si(e,t,i)}),this.#oi={grid:i,isGridMode:this.#zt,config:this.config,editingCells:this.#Yt,editorValueCallbacks:this.#Xt,isEditSessionActive:()=>-1!==this.#Wt,commitCellValue:(e,t,i,r)=>this.#li(e,t,i,r),exitRowEdit:(e,t)=>this.#ai(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.#ni.changedRowIds,configurable:!0}),e.resetChangedRows=e=>this.resetChangedRows(e),document.addEventListener("keydown",e=>{if(!this.#zt&&"Escape"===e.key&&-1!==this.#Wt){if(Ri(this.config,e))return;this.#ai(this.#Wt,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",e=>{if(this.#zt)return;if(-1===this.#Wt)return;const t=i.findRenderedRowElement?.(this.#Wt);if(!t)return;if((e.composedPath&&e.composedPath()||[]).includes(t))return;const r=e.target;if(!r||this.gridElement.contains(r)||!this.grid.containsFocus?.(r)){if(r&&!this.gridElement.contains(r)){const e=i.findRenderedRowElement?.(this.#Wt);if(e&&function(e,t){if(!e)return!1;const i=t.querySelectorAll('[aria-expanded="true"][aria-controls]');for(let r=0;r<i.length;r++){const n=i[r].getAttribute("aria-controls");if(!n)continue;const o=t.ownerDocument?.getElementById(n);if(o&&o.contains(e))return!0}return!1}(r,e))return}Ri(this.config,e)||queueMicrotask(()=>{-1!==this.#Wt&&this.#ai(this.#Wt,!1)})}},{signal:t}),this.config.focusTrap&&this.gridElement.addEventListener("focusout",e=>{if(this.#zt)return;if(-1===this.#Wt)return;const t=e.relatedTarget;t&&this.grid.containsFocus?.(t)||t&&this.gridElement.contains(t)||queueMicrotask(()=>{-1!==this.#Wt&&this.#di()})},{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.#Xt.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.#ni.isRowDirty(n,r);this.emit("dirty-change",{rowId:n,row:r,original:this.#ni.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.#zt&&(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(yi)){if(this.#ti)return t.blur(),void this.gridElement.focus();const e=i._focusRow,r=i._focusCol,n=this.#ri;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.#ri={rowIndex:e,colIndex:r,field:i,value:n[i]}}}this.#ei=!0}},{signal:t}),this.gridElement.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.gridElement.contains(t)||this.grid.containsFocus?.(t))&&t.matches(yi)||(this.#ei=!1,this.#ri=null)},{signal:t}),this.gridElement.addEventListener("keydown",e=>{if("Escape"===e.key&&this.#ei){if(Ri(this.config,e))return void queueMicrotask(()=>{if(this.#ei){this.#ci();const e=document.activeElement;e&&this.gridElement.contains(e)&&(e.blur(),this.gridElement.focus()),this.#ei=!1,this.#ti=!0}});this.#ci();const t=document.activeElement;t&&this.gridElement.contains(t)&&(t.blur(),this.gridElement.focus()),this.#ei=!1,this.#ti=!0,e.preventDefault(),e.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",e=>{e.target.matches(yi)&&(this.#ti=!1)},{signal:t}))}detach(){this.#At._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#Wt=-1,this.#Kt=void 0,this.#Vt=void 0,this.#jt=-1,this.#Ut.clear(),this.#ni.clear(),this.#Yt.clear(),this.#Xt.clear(),this.#ei=!1,this.#ti=!1,this.#ri=null,this.#ii=!1,super.detach()}handleQuery(e){if("isEditing"===e.type)return this.#zt||-1!==this.#Wt}onCellClick(e){if(this.#zt)return!1;const t=this.#At,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.#Bt(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.#At;if("Escape"===e.key){if(this.#zt&&this.#ei){this.#ci();const e=document.activeElement;return e&&this.gridElement.contains(e)&&(e.blur(),this.gridElement.focus()),this.#ei=!1,this.#ti=!0,this.requestAfterRender(),!0}if(-1!==this.#Wt&&!this.#zt)return Ri(this.config,e)||this.#ai(this.#Wt,!0),!0}if(this.#zt&&!this.#ei&&("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key))return!1;if(this.#zt&&this.#ei&&("ArrowUp"===e.key||"ArrowDown"===e.key))return!0;if(("ArrowUp"===e.key||"ArrowDown"===e.key)&&-1!==this.#Wt&&!this.#zt)return!0;if("Tab"===e.key&&(-1!==this.#Wt||this.#zt)){if(e.preventDefault(),this.#ii)return this.#ai(this.#Wt,!1),!0;const t=!e.shiftKey;return this.#ui(t),!0}if(" "===e.key||"Spacebar"===e.key){if(-1!==this.#Wt)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.#$t(n,o)&&"boolean"===n.type){const t=n.field;if(Ci(t)){const r=!o[t];return this.#li(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.#zt&&!this.#ei)return this.#di(),!0;if(-1!==this.#Wt){const t=e.target;return(!t||"true"!==t.getAttribute?.("aria-expanded")||!t.hasAttribute?.("aria-controls"))&&!!Ri(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.#Bt(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}});return this.gridElement.dispatchEvent(d),d.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(r),!0)}}return!1}if("F2"===e.key){if(-1!==this.#Wt||this.#zt)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.#$t(n,o)&&n.field)return e.preventDefault(),this.beginCellEdit(i,n.field),!0}return!1}return!1}processColumns(e){const t=this.#At,i=t.effectiveConfig?.typeDefaults,r=t.__frameworkAdapter;return i||r?.getTypeDefault?e.map(e=>{if(!e.type)return e;let n;if(i?.[e.type]?.editorParams&&(n=i[e.type].editorParams),!n&&r?.getTypeDefault){const i=r.getTypeDefault(e.type,t._hostElement);i?.editorParams&&(n=i.editorParams)}return n?{...e,editorParams:{...n,...e.editorParams}}:e}):e}processRows(e){const t=this.#At;if(this.config.dirtyTracking&&t.getRowId&&this.#ni.capture(e,e=>{try{return t.getRowId?.(e)}catch{return}}),-1===this.#Wt||this.#zt)return e;const i=this.#Kt,r=this.#Vt;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.#Wt!==o&&this.#hi(this.#Wt,o),n)}afterRender(){const e=this.#At;if(-1!==this.#Wt&&this.#Vt&&!this.#zt&&e._rows[this.#Wt]!==this.#Vt){const t=e._rows.indexOf(this.#Vt);if(-1===t)return void setTimeout(()=>this.cancelActiveRowEdit(),0);this.#hi(this.#Wt,t)}if(this.#Zt&&(this.#Zt=!1,this.#gi(e)),-1!==this.#Qt){const t=this.#Qt;this.#Qt=-1,e.animateRow?.(t,"change")}const t=this.#ni.drainCapturedFlag();if(null!=t&&this.emit("baselines-captured",{count:t}),!this.#zt&&0!==this.#Yt.size)for(const i of this.#Yt){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.#pi(a,n,d,o,l,!0)}}afterCellRender(e){const{row:t,rowIndex:i,column:r,colIndex:n,cellElement:o}=e,s=this.#$t(r,t);if(s)o.removeAttribute("aria-readonly");else if(o.setAttribute("aria-readonly","true"),this.#zt&&o.classList.contains("editing")){o.classList.remove("editing");const e=t[r.field];o.textContent=null==e?"":String(e)}this.#zt&&s&&(o.classList.contains("editing")||this.#pi(t,i,r,n,o,!0,e.rowElement))}afterRowRender(e){if(!this.config.dirtyTracking)return;const t=this.#At,i=t.getRowId?.(e.row);if(!i)return;const{isNew:r,isCommittedDirty:n,hasBaseline:o}=this.#ni.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.#ni.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.#ni.getChangedRows(e=>this.grid.getRow(e))}get changedRowIds(){return this.#ni.getChangedRowIds()}get activeEditRow(){return this.#Wt}get activeEditCol(){return this.#jt}isRowEditing(e){return this.#Wt===e}isCellEditing(e,t){return this.#Yt.has(`${e}:${t}`)}isRowChanged(e){const t=this.#At,i=t._rows[e];if(!i)return!1;try{const e=t.getRowId?.(i);return!!e&&this.#ni.isRowChanged(e)}catch{return!1}}isRowChangedById(e){return this.#ni.isRowChanged(e)}isDirty(e){if(!this.config.dirtyTracking)return!1;if(this.#ni.newRowIds.has(e))return!0;const t=this.grid.getRow(e);return!!t&&this.#ni.isRowDirty(e,t)}isPristine(e){return!this.isDirty(e)}get dirty(){if(!this.config.dirtyTracking)return!1;const e=this.#At;return this.#ni.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.#ni.markPristine(e,t),this.emit("dirty-change",{rowId:e,row:t,original:t,type:"pristine"}))}markAsNew(e){if(!this.config.dirtyTracking)return;this.#ni.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.#ni.markDirty(e),this.emit("dirty-change",{rowId:e,row:t,original:this.#ni.getOriginalRow(e),type:"modified"}))}markAllPristine(){if(!this.config.dirtyTracking)return;const e=this.#At;this.#ni.markAllPristine(t=>e._getRowEntry(t)?.row)}getOriginalRow(e){if(this.config.dirtyTracking)return this.#ni.getOriginalRow(e)}hasBaseline(e){return!!this.config.dirtyTracking&&this.#ni.hasBaseline(e)}getDirtyRows(){if(!this.config.dirtyTracking)return[];const e=this.#At;return this.#ni.getDirtyRows(t=>e._getRowEntry(t)?.row)}get dirtyRowIds(){if(!this.config.dirtyTracking)return[];const e=this.#At;return this.#ni.getDirtyRowIds(t=>e._getRowEntry(t)?.row)}revertRow(e){if(!this.config.dirtyTracking)return;const t=this.grid.getRow(e);t&&this.#ni.revertRow(e,t)&&(this.emit("dirty-change",{rowId:e,row:t,original:this.#ni.getOriginalRow(e),type:"reverted"}),this.requestRender())}revertAll(){if(!this.config.dirtyTracking)return;const e=this.#At;this.#ni.revertAll(t=>e._getRowEntry(t)?.row),this.requestRender()}setInvalid(e,t,i=""){this.#Jt.setInvalid(e,t,i)}clearInvalid(e,t){this.#Jt.clearInvalid(e,t)}clearRowInvalid(e){this.#Jt.clearRowInvalid(e)}clearAllInvalid(){this.#Jt.clearAllInvalid()}isCellInvalid(e,t){return this.#Jt.isCellInvalid(e,t)}getInvalidMessage(e,t){return this.#Jt.getInvalidMessage(e,t)}hasInvalidCells(e){return this.#Jt.hasInvalidCells(e)}getInvalidFields(e){return this.#Jt.getInvalidFields(e)}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#ni.changedRowIds.clear(),this.#ni.committedDirtyRowIds.clear(),this.#fi(),e||this.emit("changed-rows-reset",{rows:t,ids:i});const r=this.#At;r._rowPool?.forEach(e=>e.classList.remove("changed"))}beginCellEdit(e,t){const i=this.#At,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.#$t(n,o))return;const s=i.findRenderedRowElement?.(e),l=s?.querySelector(`.cell[data-col="${r}"]`);l&&(this.#ii=!0,this.#wi(e,r,l))}beginBulkEdit(e){const t=this.#At;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return;const i=t._columns?.some(e=>this.#Bt(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.#ii=!1,this.#mi(e,n),Array.from(r.children).forEach((i,r)=>{const o=t._visibleColumns[r];if(o&&this.#$t(o,n)){const t=i;t.classList.contains("editing")||this.#pi(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(yi);try{t?.focus({preventScroll:!0})}catch{}}},0))}commitActiveRowEdit(){-1!==this.#Wt&&this.#ai(this.#Wt,!1)}cancelActiveRowEdit(){-1!==this.#Wt&&this.#ai(this.#Wt,!0)}#si(e,t,i){const r=this.#At,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.#Jt.getInvalidMessage(e,t);i&&a.setAttribute("title",i)}else a.removeAttribute("data-invalid"),a.removeAttribute("title")}#hi(e,t){this.#Wt=t;const i=new Set,r=`${e}:`;for(const s of this.#Yt)s.startsWith(r)?i.add(`${t}:${s.substring(r.length)}`):i.add(s);this.#Yt.clear();for(const s of i)this.#Yt.add(s);const n=this.#Ut.get(e);void 0!==n&&(this.#Ut.delete(e),this.#Ut.set(t,n));const o=[];for(const[s,l]of this.#Xt)s.startsWith(r)&&(o.push([`${t}:${s.substring(r.length)}`,l]),this.#Xt.delete(s));for(const[s,l]of o)this.#Xt.set(s,l);this.#fi()}#wi(e,t,i){const r=this.#At,n=r._rows[e],o=r._visibleColumns[t];n&&o&&this.#$t(o,n)&&(i.classList.contains("editing")||(this.#Wt!==e&&this.#mi(e,n),this.#jt=t,this.#pi(n,e,o,t,i,!1)))}#ci(){const e=this.#ri;if(!e)return;const t=this.#At,i=t._rows?.[e.rowIndex];i&&(i[e.field]=e.value);const r=`${e.rowIndex}:${e.field}`,n=this.#Xt.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.#ni.isRowDirty(e,i)||(this.#ni.changedRowIds.delete(e),this.emit("dirty-change",{rowId:e,row:i,original:this.#ni.getOriginalRow(e),type:"reverted"})):this.#ni.changedRowIds.delete(e))}this.requestRender(),this.#ri=null}#di(){const e=this.#At,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(yi);e&&(this.#ti=!1,e.focus(),this.#ei=!0,e instanceof HTMLInputElement&&("text"===e.type||"number"===e.type)&&e.select())}}#ui(e){const t=this.#At,i=t._rows,r=this.#zt?t._focusRow:this.#Wt,n=i[r],o=t._visibleColumns.map((e,t)=>n&&this.#$t(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(yi);e?.focus({preventScroll:!0})}return void De(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.#$t(e,n)?t:-1).filter(e=>e>=0);if(0===o.length)return;this.#zt?(t._focusRow=l,t._focusCol=e?o[0]:o[o.length-1],De(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(yi);e?.focus({preventScroll:!0})}},0)):(this.#ai(r,!1),t._focusRow=l,t._focusCol=e?o[0]:o[o.length-1],this.beginBulkEdit(l),De(t,{forceHorizontalScroll:!0}))}}#fi(){const e=this.#At;e._activeEditRows=this.#Wt,e._rowEditSnapshots=this.#Ut}#mi(e,t){if(this.#Wt!==e){-1!==this.#Wt&&this.#ai(this.#Wt,!1),this.#Ut.set(e,{...t}),this.#Wt=e,this.#Vt=t;const i=this.#At;try{this.#Kt=i.getRowId?.(t)??void 0}catch{this.#Kt=void 0}this.#fi(),this.#zt||(this.emit("edit-open",{rowIndex:e,rowId:this.#Kt??"",row:t}),o(this.gridElement,s(this.gridElement,"editingStarted",e)))}}#ai(e,t){if(this.#Wt!==e)return;const i=this.#At,r=this.#Ut.get(e),n=i.findRenderedRowElement?.(e);let l=this.#Kt;const a=l?i._getRowEntry(l):void 0,d=a?.row??this.#Vt??i._rows[e];if(!l&&d)try{l=i.getRowId?.(d)}catch{}if(!t&&n&&d){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=d[t],r=gi(o,n,i);i!==r&&this.#li(e,n,r,d)}})}if(t||this.#zt||!d||this.emit("before-edit-close",{rowIndex:e,rowId:l??"",row:d}),t&&r&&d)Object.keys(r).forEach(e=>{d[e]=r[e]}),l&&(this.#ni.changedRowIds.delete(l),this.#ni.committedDirtyRowIds.delete(l),this.clearRowInvalid(l));else if(!t&&d){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,d),i=l?this.#ni.changedRowIds.has(l):t,n=this.emitCancelable("row-commit",{rowIndex:e,rowId:l??"",row:d,oldValue:r,newValue:d,changed:i,changedRows:this.changedRows,changedRowIds:this.changedRowIds});n&&r?(Object.keys(r).forEach(e=>{d[e]=r[e]}),l&&(this.#ni.changedRowIds.delete(l),this.#ni.committedDirtyRowIds.delete(l),this.clearRowInvalid(l))):n||(l&&this.config.dirtyTracking&&(this.#ni.isRowDirty(l,d)?this.#ni.committedDirtyRowIds.add(l):this.#ni.committedDirtyRowIds.delete(l)),t&&this.isAnimationEnabled&&(this.#Qt=e))}this.#Ut.delete(e),this.#Wt=-1,this.#Kt=void 0,this.#Vt=void 0,this.#jt=-1,this.#ii=!1,this.#fi();for(const o of this.#Yt)o.startsWith(`${e}:`)&&this.#Yt.delete(o);for(const o of this.#Xt.keys())o.startsWith(`${e}:`)&&this.#Xt.delete(o);if(this.#Zt=!0,n){const e=i.__frameworkAdapter,t=n.querySelectorAll(".cell.editing");e?.releaseCell&&t.forEach(t=>{e.releaseCell(t)}),t.forEach(e=>{e.classList.remove("editing"),function(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing")}(e.parentElement)}),i.refreshVirtualWindow(!0)}else this.#gi(i),this.#Zt=!1;!this.#zt&&d&&(this.emit("edit-close",{rowIndex:e,rowId:l??"",row:d,reverted:t}),t||o(this.gridElement,s(this.gridElement,"editingCommitted",e)))}#li(e,t,i,r){const n=t.field;if(!Ci(n))return;const o=r[n];if(o===i)return;const s=this.#At;let l;try{l=this.grid.getRowId(r)}catch{}const a=!l||!this.#ni.changedRowIds.has(l),d=l?e=>this.grid.updateRow(l,e,"cascade"):xi;let c=!1;const u=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:u}))return;if(l&&!c&&this.isCellInvalid(l,n)&&this.clearInvalid(l,n),r[n]=i,K(r,n),l&&this.#ni.changedRowIds.add(l),this.#fi(),this.config.dirtyTracking&&l){const e=this.#ni.isRowDirty(l,r);this.emit("dirty-change",{rowId:l,row:r,original:this.#ni.getOriginalRow(l),type:e?"modified":"pristine"})}this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:n,oldValue:o,newValue:i});const h=s.findRenderedRowElement?.(e);h&&h.classList.add("changed")}#pi(e,t,i,r,n,o,s){Ei(this.#oi,e,t,i,r,n,o,s)}#gi(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 ${static manifest={queries:[{type:"export:csv",description:"Triggers a CSV export"}]};name="export";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;handleQuery(e){if("export:csv"===e.type)return this.exportCsv(),!0}resolveExportData(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,mode:t?.mode??"raw",columns:t?.columns,rowIndices:t?.rowIndices,excelStyles:t?.excelStyles,fileExtension:t?.fileExtension},n=Kt(this.columns,t?.columns,i.onlyVisible);let o;if(t?.rowIndices)o=Vt(this.rows,t.rowIndices);else if(i.onlySelected){const e=this.getSelectionState();o=e?.selected?.size?Vt(this.rows,[...e.selected]):[...this.rows]}else o=[...this.rows];return{columns:n,rows:o,fullParams:r}}resolveCellOutput(e,t,i,r,n){let o=e;if("formatted"===r){const r=this.#bi(t);if(r)try{const t=r(e,i);o=null==t?"":String(t)}catch{o=null==e?"":String(e)}else o="date"===t.type?pe(e):"boolean"===t.type?!!e:e}return n&&(o=n(o,t.field,i)),o}performExport(e,t){const{columns:i,rows:r,fullParams:n}=this.resolveExportData(e,t);this.isExportingFlag=!0;let o=n.fileName??"export";const s=this.#vi(i);try{switch(e){case"csv":{const e=_i(this.#yi(r,i,n),s,{...n,processCell:void 0},{bom:!0});o=o.endsWith(".csv")?o:`${o}.csv`,function(e,t){Ai(new Blob([e],{type:"text/csv;charset=utf-8;"}),t)}(e,o);break}case"excel":{const e=Hi(this.#yi(r,i,n),s,{...n,processCell:void 0}),t=n.fileExtension??".xls",l=t.startsWith(".")?t:`.${t}`;o=o.endsWith(l)?o:`${o}${l}`,function(e,t){Ai(new Blob([e],{type:"application/vnd.ms-excel;charset=utf-8;"}),t)}(e,o);break}case"json":{const e=this.#yi(r,i,n),t=JSON.stringify(e,null,2);o=o.endsWith(".json")?o:`${o}.json`;Ai(new Blob([t],{type:"application/json"}),o);break}}this.lastExportInfo={format:e,timestamp:new Date},this.emit("export-complete",{format:e,fileName:o,rowCount:r.length,columnCount:i.length})}finally{this.isExportingFlag=!1}}#yi(e,t,i){const r=i.mode??"raw";return e.map(e=>{const n={};for(const o of t){const t=W(e,o);n[o.field]=this.resolveCellOutput(t,o,e,r,i.processCell)}return n})}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}export(e){const{columns:t,rows:i,fullParams:r}=this.resolveExportData("json",e);return this.#yi(i,t,r)}getResolvedColumns(e){return Kt(this.columns,e?.columns,this.config.onlyVisible)}formatCsv(e,t,i){const{columns:r,fullParams:n}=this.resolveExportData("csv",t);return _i(e,this.#vi(r),n,i)}formatExcel(e,t){const{columns:i,fullParams:r}=this.resolveExportData("excel",t);return Hi(e,this.#vi(i),r)}#vi(e){return e.map(e=>e.valueAccessor?{...e,valueAccessor:void 0}:e)}#bi(e){if(e.format)return e.format;if(!e.type)return;const t=this.grid,i=t?.__frameworkAdapter;if(!i?.getTypeDefault)return;const r=i.getTypeDefault(e.type,t?._hostElement);return r?.format}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=Ui,e.FitModeEnum=t,e.GridCSSVars={COLOR_BG:"--tbw-color-bg",COLOR_FG:"--tbw-color-fg",COLOR_FG_MUTED:"--tbw-color-fg-muted",COLOR_BORDER:"--tbw-color-border",COLOR_ACCENT:"--tbw-color-accent",COLOR_HEADER_BG:"--tbw-color-header-bg",COLOR_HEADER_FG:"--tbw-color-header-fg",COLOR_SELECTION:"--tbw-color-selection",COLOR_ROW_HOVER:"--tbw-color-row-hover",COLOR_ROW_ALT:"--tbw-color-row-alt",ROW_HEIGHT:"--tbw-row-height",HEADER_HEIGHT:"--tbw-header-height",CELL_PADDING:"--tbw-cell-padding",FONT_FAMILY:"--tbw-font-family",FONT_SIZE:"--tbw-font-size",BORDER_RADIUS:"--tbw-border-radius",FOCUS_OUTLINE:"--tbw-focus-outline"},e.GridClasses=R,e.GridDataAttrs=E,e.GridElement=Wt,e.GridSelectors=S,e.GroupingColumnsPlugin=class extends ${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;#Ci=new Set;#xi=[];#Ri=new Map;attach(e){super.attach(e),this.gridElement.addEventListener("column-move",this.#Ei,{signal:this.disconnectSignal})}detach(){this.groups=[],this.isActive=!1,this.#Ci.clear(),this.#xi=[],this.#Ri.clear()}#Ei=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.#Si(n,r))return t.preventDefault(),void this.#_i(i)}this.#Ai(r)};#Ai(e){this.#Ci.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.#Ci.add(e[i])}}#Si(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}#_i(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.#ki()}#ki(){let e;if(this.#xi.length>0)e=this.#xi.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||g("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.#xi=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});n=e.map(e=>{const t=i.get(e.field);return t&&!e.group?{...e,group:t}:e})}else this.#xi=[],this.#Ri.clear(),n=[...e];const o=Yi(n);if(0===o.length)return this.isActive=!1,this.groups=[],n;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.#Ci.clear();for(const s of o){const e=s.columns[s.columns.length-1];e?.field&&this.#Ci.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=Yi(i);if(0===r.length)return;if(this.#Ri.size>0)for(const l of r){const e=this.#Ri.get(l.id);e&&(l.renderer=e)}this.#Ci.clear();const n=Xi(r);for(let l=0;l<n.merged.length;l++){const e=n.merged[l],t=e.columns[e.columns.length-1];t?.field&&l<n.merged.length-1&&this.#Ci.add(t.field)}const o=function(e,t,i,r){if(0===e.length)return null;const n=document.createElement("div");n.className="header-group-row",n.setAttribute("role","row");const{merged:o}=r??Xi(e);for(const s of o){const e=String(s.id),r=e.startsWith("__implicit__"),o=Zi(s,t);if(!o)continue;const[l,a]=o,d=a-l+1,c=r?"":s.label||s.id,u=document.createElement("div");u.className="cell header-group-cell",r&&u.classList.add("implicit-group"),u.setAttribute("data-group",e),u.style.gridColumn=`${l+1} / span ${d}`;const h=!r&&(s.renderer||i)||void 0;if(h&&!r){const t=h({id:e,label:String(c),columns:s.columns,firstIndex:l,isImplicit:!1});t instanceof HTMLElement?u.appendChild(t):"string"==typeof t?u.innerHTML=F(t):u.textContent=c}else u.textContent=c;n.appendChild(u)}return n}(r,i,this.config.groupHeaderRenderer,n);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,r){if(!t.length||!e)return;const{merged:n,embedded:o}=r??Xi(t),s=new Map;for(const a of n)if(!String(a.id).startsWith("__implicit__"))for(const e of a.columns)e.field&&s.set(e.field,a.id);for(let a=0;a<t.length;a++){const e=t[a];if(String(e.id).startsWith("__implicit__")&&o.has(String(e.id)))for(let i=a-1;i>=0;i--)if(!String(t[i].id).startsWith("__implicit__")){for(const r of e.columns)r.field&&s.set(r.field,t[i].id);break}}const l=Array.from(e.querySelectorAll(".cell[data-field]"));l.forEach(e=>{const t=e.getAttribute("data-field")||"",i=s.get(t);i&&(e.classList.add("grouped"),e.getAttribute("data-group")||e.setAttribute("data-group",i))});for(const a of n){const e=a.columns[a.columns.length-1],t=l.find(t=>t.getAttribute("data-field")===e.field);t&&t.classList.add("group-end")}}(s,r,0,n))}afterCellRender(e){this.isActive&&this.config.showGroupBorders&&e.cellElement.classList.toggle("group-end",this.#Ci.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 ${static manifest={modifiesRowStructure:!0,hookPriority:{processRows:10,onHeaderClick:-1},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."}],events:[{type:"group-toggle",description:"Emitted when groups are expanded/collapsed. Broadcast to both DOM consumers and plugin bus."},{type:"group-expand",description:"Emitted when a pre-defined group is expanded."},{type:"group-collapse",description:"Emitted when a pre-defined group is collapsed."}],queries:[{type:"canMoveRow",description:"Returns false for group header rows (cannot be reordered)"},{type:"grouping:get-grouped-fields",description:"Returns the column field names that match group depth levels (string[])"},{type:"datasource:viewport-mapping",description:"Translates flat viewport row indices to top-level group indices for ServerSide pagination."}],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)}]};static dependencies=[{name:"multiSort",required:!1,reason:"Queries sort model for coordinated group sorting"},{name:"serverSide",required:!1,reason:"Consumes datasource events for lazy-loaded grouped data"}];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)}@media(hover:hover){.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;preDefinedGroups=[];groupRowsMap=new Map;loadingGroups=new Set;groupedFields=[];userGroupSortDirections=new Map;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,this.preDefinedGroups=[],this.groupRowsMap.clear(),this.loadingGroups.clear(),this.groupedFields=[],this.userGroupSortDirections.clear()}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}if("grouping:get-grouped-fields"===e.type)return[...this.groupedFields];if("datasource:viewport-mapping"===e.type){const{viewportStart:t,viewportEnd:i}=e.context;if(0===this.flattenedRows.length)return;if(0===this.preDefinedGroups.length&&!Array.isArray(this.config.groups))return;const r=this.getActiveGroups();return{startNode:this.getTopLevelGroupIndex(t),endNode:this.getTopLevelGroupIndex(i)+1,totalLoadedNodes:r.length}}}getTopLevelGroupIndex(e){let t=-1;const i=Math.min(e,this.flattenedRows.length-1);for(let r=0;r<=i;r++){const e=this.flattenedRows[r];"group"===e.kind&&0===e.depth&&t++}return Math.max(0,t)}attach(e){super.attach(e),this.on("datasource:data",e=>{const t=e;t.claimed||(t.claimed=!0,this.preDefinedGroups=t.rows,this.groupRowsMap.clear(),this.loadingGroups.clear(),this.hasAppliedDefaultExpanded=!1,this.requestRender())}),this.on("datasource:children",e=>{const t=e;if("grouping-rows"!==t.context?.source)return;t.claimed=!0;const i=t.context.groupKey;i&&(this.groupRowsMap.set(i,t.rows),this.loadingGroups.delete(i),this.requestRender())})}onHeaderClick(e){const t=this.groupedFields.indexOf(e.field);if(-1===t)return;if(!e.column.sortable)return;const i=t,r=this.userGroupSortDirections.get(i)??1;return this.userGroupSortDirections.set(i,1===r?-1:1),this.requestRender(),!0}resolveGroupSortDirections(e){const t=this.config;if("function"!=typeof t.groupOn||0===e.length)return void(this.groupedFields=[]);const i=this.columns.map(e=>e.field),r=function(e,t,i){const r=new Map;if(0===e.length)return r;const n=e[0];let o=t(n);if(null==o||!1===o)return r;Array.isArray(o)||(o=[o]);for(let s=0;s<o.length;s++){const e=o[s];for(const t of i)if(n[t]===e){r.set(s,t);break}}return r}([...e],t.groupOn,i);if(this.groupedFields=[...r.values()],0===r.size)return;const n=new Map(this.userGroupSortDirections);if(n.size<r.size){const e=new Map,t=this.grid?.query?.("sort:get-model",null);if(Array.isArray(t)&&t.length>0){const i=t[0];if(Array.isArray(i))for(const t of i)e.set(t.field,"desc"===t.direction?-1:1)}if(0===e.size){const t=this.grid;t._sortState&&e.set(t._sortState.field,t._sortState.direction)}for(const[i,o]of r)if(!n.has(i)){const t=e.get(o);void 0!==t&&n.set(i,t)}}return n.size>0?n:void 0}static detect(e,t){return"function"==typeof t?.groupOn||"boolean"==typeof t?.enableRowGrouping||Array.isArray(t?.groups)}processRows(e){if(this.preDefinedGroups.length>0||Array.isArray(this.config.groups))return this.preDefinedGroups.length>0||Array.isArray(this.config.groups)&&this.config.groups.length>0?this.processPreDefinedGroups():(this.isActive=!1,this.flattenedRows=[],[]);const t=this.config;if("function"!=typeof t.groupOn)return this.isActive=!1,this.flattenedRows=[],[...e];const i=this.resolveGroupSortDirections(e),r=nr({rows:[...e],config:t,expanded:new Set,groupSortDirections:i});if(0===r.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)}(r);n=or(t.defaultExpanded??!1,e),n.size>0&&(this.expandedKeys=new Set(n),this.hasAppliedDefaultExpanded=!0)}const o=nr({rows:[...e],config:t,expanded:this.expandedKeys,initialExpanded:n,groupSortDirections:i});this.isActive=!0,this.flattenedRows=o,this.keysToAnimate.clear();const s=new Set;return o.forEach((e,t)=>{if("data"===e.kind){const e=`data-${t}`;s.add(e),this.previousVisibleKeys.has(e)||this.keysToAnimate.add(e)}}),this.previousVisibleKeys=s,o.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(`.${R.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(!0===e?.__loading&&e?.__groupKey){t.className="data-grid-row",t.__isCustomRow=!0,t.innerHTML="";const e=document.createElement("div");return e.className="cell",e.style.gridColumn="1 / -1",e.setAttribute("role","gridcell"),e.textContent=" ",t.appendChild(e),We(t,!0),!0}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()}processPreDefinedGroups(){const e=this.preDefinedGroups.length>0?this.preDefinedGroups:Array.isArray(this.config.groups)?this.config.groups:[];if(0===e.length)return this.isActive=!1,this.flattenedRows=[],[];if(!this.hasAppliedDefaultExpanded&&0===this.expandedKeys.size&&!1!==this.config.defaultExpanded){const t=this.collectGroupKeys(e),i=or(this.config.defaultExpanded??!1,t);i.size>0&&(this.expandedKeys=new Set(i),this.hasAppliedDefaultExpanded=!0)}const t=sr({groups:e,expanded:this.expandedKeys,groupRows:this.groupRowsMap,loadingGroups:this.loadingGroups});this.isActive=!0,this.flattenedRows=t,this.keysToAnimate.clear();const i=new Set;return t.forEach((e,t)=>{if("data"===e.kind){const e=`data-${t}`;i.add(e),this.previousVisibleKeys.has(e)||this.keysToAnimate.add(e)}}),this.previousVisibleKeys=i,t.map(t=>{if("group"===t.kind){const i=this.findGroupDefinition(e,t.key),r=i?.rowCount??t.rows.length;return{__isGroupRow:!0,__groupKey:t.key,__groupValue:t.value,__groupDepth:t.depth,__groupRows:t.rows,__groupExpanded:t.expanded,__groupRowCount:r,__rowCacheKey:`group:${t.key}`}}return t.row})}collectGroupKeys(e){const t=[];for(const i of e)t.push(i.key),i.children?.length&&t.push(...this.collectGroupKeys(i.children));return t}getActiveGroups(){return this.preDefinedGroups.length>0?this.preDefinedGroups:Array.isArray(this.config.groups)?this.config.groups:[]}findGroupDefinition(e,t){for(const i of e){if(i.key===t)return i;if(i.children?.length){const e=this.findGroupDefinition(i.children,t);if(e)return e}}}createToggleButton(e,t){const i=document.createElement("button");return i.type="button",i.className=`${R.GROUP_TOGGLE}${e?` ${R.EXPANDED}`:""}`,i.setAttribute("aria-label",e?"Collapse group":"Expand group"),this.setIcon(i,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=R.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=R.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=ir.run(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"),$i(o))return a.setAttribute("data-field",o.field),void t.appendChild(a);if(d){const e=n[o.field];if(e){const t=ir.run(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=ir.run(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=R.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("group-toggle",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("group-toggle",{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.broadcast("group-toggle",{key:e,expanded:this.expandedKeys.has(e),value:r?.value,depth:r?.depth??0,expandedKeys:[...this.expandedKeys]});const n=this.getActiveGroups();if(n.length>0){const i=lr(n,e);if(t){if(this.emit("group-expand",{groupKey:e,groupPath:i}),!this.groupRowsMap.has(e)){const t=this.findGroupDefinition(n,e);t&&(this.loadingGroups.add(e),this.grid?.query?.("datasource:fetch-children",{context:{source:"grouping-rows",groupKey:e,group:t,groupPath:i}}))}}else this.emit("group-collapse",{groupKey:e,groupPath:i})}const l=this.expandedKeys.has(e),a=null!=r?.value?String(r.value):e;if(l){const e=r?.rows?.length??0;o(this.gridElement,s(this.gridElement,"groupExpanded",a,e))}else o(this.gridElement,s(this.gridElement,"groupCollapsed",a));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()}setGroups(e){this.preDefinedGroups=e,this.groupRowsMap.clear(),this.loadingGroups.clear(),this.expandedKeys.clear(),this.hasAppliedDefaultExpanded=!1,this.requestRender()}getGroups(){return this.preDefinedGroups.length>0?[...this.preDefinedGroups]:Array.isArray(this.config.groups)?[...this.config.groups]:[]}setGroupRows(e,t){this.groupRowsMap.set(e,t),this.loadingGroups.delete(e),this.requestRender()}setGroupLoading(e,t){t?this.loadingGroups.add(e):this.loadingGroups.delete(e),this.requestRender()}clearGroupRows(e){null!=e?this.groupRowsMap.delete(e):this.groupRowsMap.clear(),this.requestRender()}},e.MasterDetailPlugin=cr,e.MultiSortPlugin=class extends ${static manifest={queries:[{type:"sort:get-model",description:"Returns the current multi-sort model as SortModel[]"},{type:"sort:set-model",description:"Sets the multi-sort model from context (SortModel[])"}]};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;#Ti=!1;#Ii=[];get#At(){return this.grid}clearCoreSortState(){this.#At._sortState=null}#Mi(e){const t=this.grid?.query?.("grouping:get-grouped-fields",null);if(!Array.isArray(t)||0===t.length)return e;const i=t[0];if(!Array.isArray(i)||0===i.length)return e;const r=new Set(i),n=e.filter(e=>!r.has(e.field));return n.length===e.length?e:n}detach(){this.sortModel=[],this.cachedSortResult=null}handleQuery(e){switch(e.type){case"sort:get-model":return[...this.sortModel];case"sort:set-model":{const t=e.context;return!!Array.isArray(t)&&(this.sortModel=[...t],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),!0)}default:return}}processRows(e){if(0===this.sortModel.length)return this.cachedSortResult=null,[...e];const t=this.#At;if(!t._isGridEditMode&&"number"==typeof t._activeEditRows&&-1!==t._activeEditRows&&this.cachedSortResult&&this.cachedSortResult.length===e.length)return[...this.cachedSortResult];const i=this.#Mi(this.sortModel),r=e;return i.length>0&&function(e,t,i){if(!t.length)return;const r=t.map(e=>{const t=i.find(t=>t.field===e.field),r=t?.sortComparator??hr;return{field:e.field,asc:"asc"===e.direction,comparator:r,pinPlaceholders:!t?.sortComparator,column:t}}),n=(e,t)=>t.column?.valueAccessor?W(e,t.column):e[t.field];if(1===r.length){const t=r[0];e.sort((e,i)=>{if(t.pinPlaceholders){const t=ur(e,i);if(0!==t)return t}const r=t.comparator(n(e,t),n(i,t),e,i);return t.asc?r:-r})}else e.sort((e,t)=>{if(r.some(e=>e.pinPlaceholders)){const i=ur(e,t);if(0!==i)return i}for(let i=0;i<r.length;i++){const o=r[i],s=o.comparator(n(e,o),n(t,o),e,t);if(0!==s)return o.asc?s:-s}return 0})}(r,i,this.columns),this.cachedSortResult=r,r}onHeaderClick(e){const t=this.columns.find(t=>t.field===e.field);if(!t?.sortable)return!1;const i=e.originalEvent.shiftKey,r=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,i,r),this.clearCoreSortState(),this.broadcast("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"}`});o(this.gridElement,s(this.gridElement,"sortApplied",e.join(", then "),""))}else o(this.gridElement,s(this.gridElement,"sortCleared"));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=gr(this.sortModel,i),n=pr(this.sortModel,i);if(e.querySelector(".sort-index")?.remove(),n){const i=this.updateSortIndicator(e,n);if(t&&this.sortModel.length>1&&void 0!==r){const t=document.createElement("span");t.className="sort-index",t.textContent=String(r),i.nextSibling?e.insertBefore(t,i.nextSibling):e.appendChild(t)}}else e.classList.contains("sortable")&&this.updateSortIndicator(e,null)})}getSortModel(){return[...this.sortModel]}setSortModel(e){if(this.sortModel=[...e],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...e]}),this.requestRender(),this.grid?.requestStateChange?.(),e.length>0){const t=e.map(e=>{const t=this.columns.find(t=>t.field===e.field);return`${t?.header??e.field} ${"asc"===e.direction?"ascending":"descending"}`});o(this.gridElement,s(this.gridElement,"sortApplied",t.join(", then "),""))}}clearSort(){this.sortModel=[],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[]}),this.requestRender(),this.grid?.requestStateChange?.(),o(this.gridElement,s(this.gridElement,"sortCleared"))}getSortIndex(e){return gr(this.sortModel,e)}getSortDirection(e){return pr(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(this.#Ti||(this.#Ii=[...this.sortModel]),t.sort){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)}else this.sortModel=this.sortModel.filter(t=>t.field!==e);this.clearCoreSortState(),this.#Ti||(this.#Ti=!0,queueMicrotask(()=>{this.#Ti=!1;const e=this.#Ii;this.#Ii=[],function(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i].field!==t[i].field||e[i].direction!==t[i].direction)return!1;return!0}(e,this.sortModel)||(this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender())}))}},e.PinnedColumnsPlugin=class extends ${static manifest={hookPriority:{processColumns:-10},ownedProperties:[{property:"pinned",level:"column",description:'the "pinned" column property',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e}],queries:[{type:Sr,description:"Prevents pinned columns from being moved/reordered"},{type:"getStickyOffsets",description:"Returns the 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;#Li={addGroupEnd:new Set,removeGroupEnd:new Set};#Pi=[];#Di=[];detach(){this.leftOffsets.clear(),this.rightOffsets.clear(),this.isApplied=!1,this.#Li={addGroupEnd:new Set,removeGroupEnd:new Set},this.#Pi=[],this.#Di=[]}static detect(e,t){const i=t?.columns;return!!Array.isArray(i)&&vr(i)}processColumns(e){const t=[...e];if(this.isApplied=vr(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=fr(o);e?"left"===wr(e,t)?i.push(o):n.push(o):r.push(o)}return[...i,...r,...n]}(t,i?me(i):"ltr")}afterRender(){if(!this.isApplied)return;const e=this.gridElement,t=[...this.columns];if(!vr(t))return Er(e),void(this.isApplied=!1);queueMicrotask(()=>{const i=yr(e,t);this.#Li=i.groupEndAdjustments,this.leftOffsets=i.leftOffsets,this.rightOffsets=i.rightOffsets,this.#Pi=i.splitGroups,this.#Fi()})}afterCellRender(e){if(!this.isApplied)return;const t=e.column.field,i=e.cellElement,r=this.leftOffsets.get(t);if(void 0!==r)i.classList.contains(R.STICKY_LEFT)||i.classList.add(R.STICKY_LEFT),i.style.position="sticky",i.style.left=r+"px";else{const e=this.rightOffsets.get(t);void 0!==e&&(i.classList.contains(R.STICKY_RIGHT)||i.classList.add(R.STICKY_RIGHT),i.style.position="sticky",i.style.right=e+"px")}this.#Li.addGroupEnd.has(t)?e.cellElement.classList.add("group-end"):this.#Li.removeGroupEnd.has(t)&&e.cellElement.classList.remove("group-end")}onScroll(e){this.#Fi()}#Fi(){if(!this.isApplied||0===this.#Pi.length)return;const e=this.gridElement;for(const t of this.#Pi){const i=t.pinnedFragment.getBoundingClientRect(),r=t.scrollableFragment.getBoundingClientRect().right<=i.right;if(r&&!t.isTransferred?(t.pinnedFragment.textContent=t.label,t.pinnedFragment.style.overflow="hidden",t.pinnedFragment.style.textOverflow="ellipsis",t.pinnedFragment.style.whiteSpace="nowrap",t.pinnedFragment.style.borderRightStyle="",t.floatLabel.style.visibility="hidden",t.floatLabel.style.transform="",t.floatOffset=0,this.#Li.addGroupEnd.add(t.pinnedField),e.querySelectorAll(`.header-row .cell[data-field="${t.pinnedField}"], .data-grid-row .cell[data-field="${t.pinnedField}"]`).forEach(e=>e.classList.add("group-end")),t.isTransferred=!0):!r&&t.isTransferred&&(t.pinnedFragment.textContent="",t.pinnedFragment.style.overflow="",t.pinnedFragment.style.textOverflow="",t.pinnedFragment.style.whiteSpace="",t.pinnedFragment.style.borderRightStyle="none",t.floatLabel.style.visibility="",t.floatLabel.style.transform="",t.floatOffset=0,this.#Li.addGroupEnd.delete(t.pinnedField),e.querySelectorAll(`.header-row .cell[data-field="${t.pinnedField}"], .data-grid-row .cell[data-field="${t.pinnedField}"]`).forEach(e=>e.classList.remove("group-end")),t.isTransferred=!1),!t.isTransferred){const e=t.floatLabel.getBoundingClientRect().left-t.floatOffset,r=i.left;e<r?(t.floatOffset=r-e,t.floatLabel.style.transform=`translateX(${t.floatOffset}px)`):(t.floatOffset=0,t.floatLabel.style.transform="")}}}handleQuery(e){switch(e.type){case Sr:return null==fr(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.lockPinning||i.meta?.lockPinning)return;const r=[];return null!=fr(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.#Di.length&&(this.#Di=i.map(e=>e.field));const r=i.map(i=>{if(i.field!==e)return i;const r={...i};return r.pinned=t,r});n.columns=r}else{const t={...i[r]};delete t.pinned;const o=[...i];o.splice(r,1);const s=this.#Di.indexOf(e);if(s>=0){let e=o.length;for(let t=0;t<o.length;t++){if(fr(o[t]))continue;if(this.#Di.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!=fr(e))||(this.#Di=[]),n.columns=o}}refreshStickyOffsets(){const e=[...this.columns],t=yr(this.gridElement,e);this.#Li=t.groupEndAdjustments,this.leftOffsets=t.leftOffsets,this.rightOffsets=t.rightOffsets,this.#Pi=t.splitGroups}getLeftPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>mr(e,t))}([...this.columns],me(this.gridElement))}getRightPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>br(e,t))}([...this.columns],me(this.gridElement))}clearStickyPositions(){Er(this.gridElement)}getHorizontalScrollOffsets(e,t){if(!this.isApplied)return;let i=0,r=0;if(e){const t=e.querySelectorAll(`.${R.STICKY_LEFT}`),n=e.querySelectorAll(`.${R.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(R.STICKY_LEFT)?i+=e.offsetWidth:e.classList.contains(R.STICKY_RIGHT)&&(r+=e.offsetWidth)})}const n=t?.classList.contains(R.STICKY_LEFT)||t?.classList.contains(R.STICKY_RIGHT);return{left:i,right:r,skipScroll:n}}},e.PinnedRowsPlugin=class extends ${name="pinnedRows";styles="@layer tbw-plugins{.tbw-scroll-area{container-type:inline-size}.tbw-footer,.tbw-header-pinned{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+.tbw-pinned-rows{border-top:0}.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;headerWrapper=null;lastModeWasSlots=!1;detach(){this.cleanup()}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),this.headerWrapper&&!t.contains(this.headerWrapper)&&(this.headerWrapper=null);const i=this.getSelectionState(),r=this.getFilterState(),n=Pr(this.sourceRows,this.columns,this.gridElement,i,r);this.config.slots?this.renderSlotMode(t,e,n):this.renderLegacyMode(t,e,n)}renderSlotMode(e,t,i){this.lastModeWasSlots||this.detachLegacyOnly(),this.lastModeWasSlots=!0;const r=this.config.slots??[],n=r.filter(e=>"top"===e.position),o=r.filter(e=>"top"!==e.position);n.length>0?(this.headerWrapper||(this.headerWrapper=document.createElement("div"),this.headerWrapper.className="tbw-header-pinned",e.insertBefore(this.headerWrapper,e.firstChild)),this.populateSlotWrapper(this.headerWrapper,n,"top",i)):this.headerWrapper&&(this.headerWrapper.remove(),this.headerWrapper=null),o.length>0?(this.footerWrapper||(this.footerWrapper=document.createElement("div"),this.footerWrapper.className="tbw-footer",e.appendChild(this.footerWrapper)),this.populateSlotWrapper(this.footerWrapper,o,"bottom",i)):this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null)}populateSlotWrapper(e,t,i,r){e.innerHTML="";for(const n of t){const t="render"in n&&null!=n.render?Fr(n,r):Hr(n,i,this.visibleColumns,this.sourceRows,this.config.fullWidth);t&&e.appendChild(t)}}renderLegacyMode(e,t,i){this.lastModeWasSlots&&(this.headerWrapper&&(this.headerWrapper.remove(),this.headerWrapper=null),this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null),this.bottomAggregationContainer=null,this.infoBarElement=null),this.lastModeWasSlots=!1;const r=this.config.aggregationRows||[],n=r.filter(e=>"top"===e.position),o=r.filter(e=>"top"!==e.position);n.length>0?(this.topAggregationContainer||(this.topAggregationContainer=Ar("top"),e.insertBefore(this.topAggregationContainer,e.firstChild)),kr(this.topAggregationContainer,n,this.visibleColumns,this.sourceRows,this.config.fullWidth)):this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null);const s=!1!==this.config.showRowCount||this.config.showSelectedCount&&i.selectedRows>0||this.config.showFilteredCount&&i.filteredRows!==i.totalRows||this.config.customPanels&&this.config.customPanels.length>0,l=s&&"top"!==this.config.position,a=o.length>0||l;if(s&&"top"===this.config.position)if(this.infoBarElement){const e=_r(this.config,i);this.infoBarElement.replaceWith(e),this.infoBarElement=e}else this.infoBarElement=_r(this.config,i),e.insertBefore(this.infoBarElement,e.firstChild);else"top"===this.config.position&&this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null);a?(this.footerWrapper||(this.footerWrapper=document.createElement("div"),this.footerWrapper.className="tbw-footer",e.appendChild(this.footerWrapper)),this.footerWrapper.innerHTML="",o.length>0&&(this.bottomAggregationContainer||(this.bottomAggregationContainer=Ar("bottom")),this.footerWrapper.appendChild(this.bottomAggregationContainer),kr(this.bottomAggregationContainer,o,this.visibleColumns,this.sourceRows,this.config.fullWidth)),l&&(this.infoBarElement=_r(this.config,i),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),this.headerWrapper&&(this.headerWrapper.remove(),this.headerWrapper=null)}detachLegacyOnly(){this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null),this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=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 Pr(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=en,e.PluginEvents={SELECTION_CHANGE:"selection-change",TREE_EXPAND:"tree-expand",TREE_LOAD_START:"tree-load-start",TREE_LOAD_END:"tree-load-end",TREE_LOAD_ERROR:"tree-load-error",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=Bt,e.PrintPlugin=class extends ${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}}}";#Hi=!1;#Gi=null;#Ni=null;#Oi=null;#qi=null;#zi=null;#$i=null;get#At(){return this.grid}isPrinting(){return this.#Hi}async print(e){if(this.#Hi)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={...nn,...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.#Hi=!0;const s=performance.now();this.emit("print-start",{rowCount:n,limitApplied:o,originalRowCount:r});try{const e=this.#At;this.#Ni={bypassThreshold:e._virtualization?.bypassThreshold??24},this.#Bi(),o&&(this.#Oi=this.sourceRows,this.grid.rows=this.sourceRows.slice(0,n),await new Promise(e=>setTimeout(e,50))),(i.includeTitle||i.includeTimestamp)&&this.#Wi(i),await this.#Ki(),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.#Vi(i):await this.#ji(),this.emit("print-complete",{success:!0,rowCount:n,duration:Math.round(performance.now()-s)})}catch(l){w("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.#Ui(),this.#Hi=!1}}#Wi(e){const t=this.gridElement;if(t){if(this.#qi=document.createElement("div"),this.#qi.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.#qi.appendChild(i)}if(e.includeTimestamp){const e=document.createElement("div");e.className="tbw-print-header-timestamp",e.textContent=`Printed: ${(new Date).toLocaleString()}`,this.#qi.appendChild(e)}t.insertBefore(this.#qi,t.firstChild),this.#zi=document.createElement("div"),this.#zi.className="tbw-print-footer",this.#zi.textContent=`Page generated from ${window.location.hostname}`,t.appendChild(this.#zi)}}async#Ki(){const e=this.#At;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#ji(){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#Vi(e){const t=this.gridElement;t&&await rn(t,{orientation:e.orientation})}#Bi(){const e=this.columns;if(e){this.#Gi=new Map;for(const t of e){if(!t.field)continue;(!0===t.printHidden||!0===t.utility&&!1!==t.printHidden)&&(this.#Gi.set(t.field,!t.hidden),this.grid.setColumnVisible(t.field,!1))}}}#Yi(){if(this.#Gi){for(const[e,t]of this.#Gi)this.grid.setColumnVisible(e,t);this.#Gi=null}}#Ui(){const e=this.gridElement;if(!e)return;this.#Yi(),e.classList.remove("print-portrait","print-landscape"),null!==this.#$i&&(e.style.transform="",e.style.transformOrigin="",e.style.width="",this.#$i=null),this.#qi&&(this.#qi.remove(),this.#qi=null),this.#zi&&(this.#zi.remove(),this.#zi=null);const t=this.#At;this.#Ni&&t._virtualization&&(t._virtualization.bypassThreshold=this.#Ni.bypassThreshold,t.refreshVirtualWindow(!0),this.#Ni=null),null!==this.#Oi&&(this.grid.rows=this.#Oi,this.#Oi=null)}afterRender(){this.config?.button&&!this.#Xi&&(this.#Zi(),this.#Xi=!0)}#Xi=!1;#Zi(){const e=this.#At;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",this.setIcon(t,"print"),t.addEventListener("click",()=>{this.print()},{signal:this.disconnectSignal}),e.appendChild(t)}})}},e.ROW_DRAG_HANDLE_FIELD=yn,e.RenderPhase=de,e.ReorderPlugin=class extends ${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}}';static manifest={queries:[{type:ln,description:"Authoritative check for whether a column may be reordered (honors lockPosition)."}]};handleQuery(e){if(e.type===ln){const t=e.context;return t?on(t):void 0}}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#At(){return this.grid}canMoveColumnWithPlugins(e){if(!e||!on(e))return!1;return!this.grid.query(ln,e).includes(!1)}clearDragClasses(){this.gridElement?.querySelectorAll(".header-row > .cell, .header-group-row > .cell").forEach(e=>{e.classList.remove(R.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(R.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(R.DRAGGING);else this.draggedField&&this.gridElement?.querySelector(`.header-row > .cell[data-field="${this.draggedField}"]`)?.classList.add(R.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=sn(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(R.DRAGGING);for(const i of n)e.querySelector(`.header-row > .cell[data-field="${i}"]`)?.classList.add(R.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=sn(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.#At,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,De(this.#At),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=sn(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 ${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-header-pinned,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"}]};#ne;#Qi=!1;#Ji;#er=!1;#tr=0;#ir=new Set;#rr=new Set;#nr=null;#or=[];get#At(){return this.grid}isResponsive(){return this.#Qi}setResponsive(e){e!==this.#Qi&&(this.#Qi=e,this.#sr(),this.emit("responsive-change",{isResponsive:e,width:this.#tr,breakpoint:this.config.breakpoint??0}),this.requestRender())}setBreakpoint(e){this.config.breakpoint=e,this.#lr(this.#tr)}setCardRenderer(e){this.config.cardRenderer=e,this.#Qi&&this.requestRender()}getWidth(){return this.#tr}getActiveBreakpoint(){return this.#nr}attach(e){super.attach(e),this.#ar(),this.#dr(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#or=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#ne=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#tr=t,clearTimeout(this.#Ji),this.#Ji=setTimeout(()=>{this.#lr(t)},this.config.debounceMs??100)}),this.#ne.observe(this.gridElement)}#ar(){const e=this.gridElement;if(!e)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const i=this.#At.__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=F(G(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})}#dr(e){if(this.#ir.clear(),this.#rr.clear(),e)for(const t of e)"string"==typeof t?this.#ir.add(t):t.showValue?this.#rr.add(t.field):this.#ir.add(t.field)}detach(){this.#ne?.disconnect(),this.#ne=void 0,clearTimeout(this.#Ji),this.#Ji=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#Qi}afterRender(){this.#cr();if(!(this.#or.length>0?null!==this.#nr:this.#Qi))return;const e=this.#ir.size>0,t=this.#rr.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.#ir.has(e)?(r.setAttribute("data-responsive-hidden",""),r.removeAttribute("data-responsive-value-only")):this.#rr.has(e)?(r.setAttribute("data-responsive-value-only",""),r.removeAttribute("data-responsive-hidden")):(r.removeAttribute("data-responsive-hidden"),r.removeAttribute("data-responsive-value-only")))}}#lr(e){if(this.#or.length>0)return void this.#ur(e);const t=this.config.breakpoint??0;0!==t||this.#er||(this.#er=!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.#Qi&&(this.#Qi=i,this.#sr(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#ur(e){let t=null;for(const i of this.#or)e<=i.maxWidth&&(t=i);if(t!==this.#nr){this.#nr=t,t?.hiddenColumns?this.#dr(t.hiddenColumns):this.#dr(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#Qi&&(this.#Qi=i,this.#sr()),this.emit("responsive-change",{isResponsive:this.#Qi,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#hr;#sr(){this.gridElement.toggleAttribute("data-responsive",this.#Qi);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.#At;if(this.#Qi){t._virtualization&&(this.#hr=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.#hr&&this.#hr>0&&t._virtualization&&(t._virtualization.rowHeight=this.#hr,this.#hr=void 0),this.#gr=void 0,this.#pr=void 0,this.#fr=void 0}}renderRow(e,t,i){if(!this.#Qi||!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.#wr()}px`,t.appendChild(r),!0}onKeyDown(e){if(!this.#Qi)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(),De(this.#At),!0;if(this.grid._focusRow<t)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),De(this.#At),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),De(this.#At),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=i,e.preventDefault(),De(this.#At),!0;break;case"ArrowRight":if(this.grid._focusRow<t)return this.grid._focusRow+=1,e.preventDefault(),De(this.#At),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),De(this.#At),!0}return!1}#gr;#pr;#fr;#wr(){if(this.#gr&&this.#gr>0)return this.#gr;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#mr(){return this.#pr&&this.#pr>0?this.#pr:this.#hr??28}#br(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}getRowHeight(e,t){if(this.#Qi&&this.config.cardRenderer)return e.__isGroupRow?this.#mr():this.#wr()}#vr(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#yr=!1;#cr(){if(!this.#Qi)return;let e=!1;const t=this.#At,i=this.#br(),r=this.#vr();if(r!==this.#fr&&(this.#fr=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.#pr&&(this.#pr=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.#gr&&(this.#gr=r,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=r))}e&&!this.#yr&&(this.#yr=!0,queueMicrotask(()=>{this.#yr=!1,this.grid&&this.#Qi&&this.#At.refreshVirtualWindow?.(!0,!0)}))}},e.RowDragDropPlugin=En,e.RowReorderPlugin=En,e.SelectionPlugin=class extends ${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:26}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.row-focus>.cell.sticky-left,tbw-grid .data-grid-row.row-focus>.cell.sticky-right{background:linear-gradient(var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0),var(--tbw-color-panel-bg)}tbw-grid .data-grid-row.row-focus[data-selectable=false]>.cell.sticky-left,tbw-grid .data-grid-row.row-focus[data-selectable=false]>.cell.sticky-right{background:var(--tbw-color-row-alt)}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;announceTimer=null;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-change",()=>this.clearSelectionSilent()),this.on("group-toggle",()=>this.clearSelectionSilent()),this.on("tree-expand",()=>this.clearSelectionSilent()),this.on("sort-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(){const e=this.gridElement?.querySelector(".rows-body");e?.removeAttribute("aria-multiselectable"),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&&Bi(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.#Cr()),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?.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.#Cr()),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=In(this.cellAnchor,{row:t,col:i}),r=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(r&&Mn(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&&Mn(this.ranges[0],e))return!1;this.ranges=[e],this.activeRange=e,this.cellAnchor={row:t,col:i}}return this.emit("selection-change",this.#Cr()),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.#Cr()),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.#Cr()),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&&Bi(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&&Mn(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.#Cr()),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&&Bi(i)){const e=this.visibleColumns.findIndex(e=>!Bi(e));e>=0&&(t=e)}const r=In(this.cellAnchor,{row:e.rowIndex,col:t}),n=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return n&&Mn(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.#Cr()),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===Ln))return e;const t=this.#xr(),i=e.findIndex($i),r=i>=0?i+1:0;return[...e.slice(0,r),t,...e.slice(r)]}return e}#xr(){return{field:Ln,header:"",width:32,resizable:!1,sortable:!1,lockPosition:!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}}}#Rr(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const t=e.closest(".cell"),i=t?fe(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}}#Er(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.#Cr()))))}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.#Cr()))}}}#Sr(){const e=this.gridElement;if(!e)return;const{mode:t}=this.config,i=!!this.config.isSelectable,r=e.querySelector(".rows-body");if(r){const e=!1!==this.config.multiSelect;r.setAttribute("aria-multiselectable",e?"true":"false")}e.querySelectorAll(".cell").forEach(e=>{e.classList.remove(R.SELECTED,"top","bottom","first","last"),i&&e.removeAttribute("data-selectable")});const n=e.querySelectorAll(".data-grid-row");if(n.forEach(e=>{e.classList.remove(R.SELECTED,"row-focus"),e.setAttribute("aria-selected","false"),i&&e.removeAttribute("data-selectable")}),"row"===t&&(we(e),n.forEach(e=>{const t=fe(e.querySelector(".cell[data-row]"));t>=0&&(i&&!this.isRowSelectable(t)&&e.setAttribute("data-selectable","false"),this.selected.has(t)&&(e.classList.add(R.SELECTED,"row-focus"),e.setAttribute("aria-selected","true")))}),this.config.checkbox&&this.#Rr(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){we(e);const t=this.ranges.map(Sn),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&&Bi(n))return;i(t,r)&&(e.classList.add(R.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.#Cr())}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=In(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.#Cr())}this.#Er(i),this.gridElement.setAttribute("data-selection-mode",i),t&&t.classList.toggle("selecting",this.isDragging),this.#Sr()}onScrollRender(){this.isSelectionEnabled()&&this.#Sr()}getSelection(){return{mode:this.config.mode,ranges:this.#Cr().ranges,anchor:this.cellAnchor}}getSelectedCells(){return function(e){const t=new Map;for(const i of e)for(const e of Tn(i))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return kn(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.#Cr()),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.#Cr()),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.#Cr()),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:An(this.ranges)}),this.requestAfterRender()}#Cr(){const e=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:An(t.ranges)}:{mode:e,ranges:[]}}(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length);return this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=setTimeout(()=>{const t="row"===e.mode?this.selected.size:e.ranges.length;t>0&&o(this.gridElement,s(this.gridElement,"selectionChanged",t))},150),e}},e.ServerSidePlugin=class extends ${static manifest={modifiesRowStructure:!0,hookPriority:{processRows:-10},incompatibleWith:[{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."}],events:[{type:"datasource:data",description:"Root data page/block loaded"},{type:"datasource:children",description:"Child data loaded for a parent context"},{type:"datasource:loading",description:"Loading state changed"},{type:"datasource:error",description:"Fetch operation failed"}],queries:[{type:"datasource:fetch-children",description:"Request child rows for a parent context"},{type:"datasource:is-active",description:"Check if ServerSide plugin has an active data source"}]};name="serverSide";get defaultConfig(){return{pageSize:100,cacheBlockSize:100,maxConcurrentRequests:2}}dataSource=null;totalNodeCount=0;infiniteScrollMode=!1;loadedBlocks=new Map;loadingBlocks=new Set;blockControllers=new Map;lastRequestId=0;scrollDebounceTimer;managedNodes=[];attach(e){super.attach(e),this.on("sort-change",()=>{"local"===this.config.sortMode?this.requestRender():this.onModelChange()}),this.on("filter-change",()=>{"local"===this.config.filterMode?this.requestRender():this.onModelChange()}),this.config.dataSource&&this.setDataSource(this.config.dataSource)}detach(){this.dataSource=null,this.totalNodeCount=0,this.infiniteScrollMode=!1,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.abortAllBlocks(),this.managedNodes=[],this.lastRequestId=0,this.scrollDebounceTimer&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=void 0)}abortAllBlocks(){for(const e of this.blockControllers.values())e.abort();this.blockControllers.clear()}getEnrichmentParams(){const e="local"===this.config.sortMode,t="local"===this.config.filterMode,i=e?void 0:this.grid?.query?.("sort:get-model",null),r=t?void 0:this.grid?.query?.("filter:get-model",null);let n=i?.[0];const o=this.grid;if(!e&&!n&&o?._sortState){const{field:e,direction:t}=o._sortState;n=[{field:e,direction:1===t?"asc":"desc"}]}return{sortModel:n,filterModel:r?.[0]}}getViewportMapping(e,t){const i={viewportStart:e,viewportEnd:t},r=this.grid?.query?.("datasource:viewport-mapping",i);return r?.[0]?r[0]:{startNode:e,endNode:t,totalLoadedNodes:this.totalNodeCount}}onModelChange(){this.dataSource&&(this.abortAllBlocks(),this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1,this.requestRender(),this.loadRequiredBlocks())}applyServerResult(e,t,i){void 0!==e.lastNode?(this.totalNodeCount=e.lastNode+1,this.infiniteScrollMode=!1):-1===e.totalNodeCount?this.infiniteScrollMode=!0:(this.totalNodeCount=e.totalNodeCount,this.infiniteScrollMode=!1),this.infiniteScrollMode&&e.rows.length<i&&(this.totalNodeCount=t*i+e.rows.length,this.infiniteScrollMode=!1)}getInfiniteScrollEstimate(e){let t=0;for(const[i,r]of this.loadedBlocks){const n=i*e+r.length;n>t&&(t=n)}return t+e}loadRequiredBlocks(){if(!this.dataSource)return;const e=this.grid,t=this.config.cacheBlockSize??100,i=this.getViewportMapping(e._virtualization.start,e._virtualization.end),r=Math.max(0,this.config.loadThreshold??0),n=Math.max(0,i.startNode-r),o=this.totalNodeCount>0?this.totalNodeCount:1/0,s=Math.min(o,i.endNode+r);if(s<=n)return;const l=function(e,t,i){const r=Pn(e,i),n=Pn(t-1,i),o=[];for(let s=r;s<=n;s++)o.push(s);return o}(n,s,t),a=this.getEnrichmentParams(),d=this.grid?.getAttribute?.("id")??void 0;for(const c of l){if(this.loadedBlocks.has(c)||this.loadingBlocks.has(c))continue;if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2)){f("TBW143","Concurrent request limit reached, deferring block load",d);break}this.loadingBlocks.add(c);const e=new AbortController;this.blockControllers.set(c,e),this.broadcast("datasource:loading",{loading:!0}),Fn(this.dataSource,c,t,a,e.signal).then(i=>{if(this.blockControllers.delete(c),e.signal.aborted)return this.loadingBlocks.delete(c),void(0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}));this.loadedBlocks.set(c,i.rows);const r=this.managedNodes.length;this.applyServerResult(i,c,t),this.loadingBlocks.delete(c);const n=c*t;for(let e=0;e<i.rows.length;e++)n+e<this.managedNodes.length&&(this.managedNodes[n+e]=i.rows[e]);const o={rows:i.rows,totalNodeCount:i.totalNodeCount,startNode:n,endNode:n+i.rows.length,claimed:!1};this.broadcast("datasource:data",o),0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1});0===r||this.managedNodes.length<(Number.isFinite(this.totalNodeCount)?this.totalNodeCount:0)?this.requestRender():this.requestVirtualRefresh(),this.loadRequiredBlocks()}).catch(t=>{if(this.blockControllers.delete(c),this.loadingBlocks.delete(c),e.signal.aborted)return void(0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}));const i=t instanceof Error?t:new Error(String(t));w(u,`getRows() failed: ${i.message}`,d),this.broadcast("datasource:error",{error:i}),0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1})})}}processRows(e){if(!this.dataSource)return[...e];const t=this.config.cacheBlockSize??100,i=this.infiniteScrollMode?this.getInfiniteScrollEstimate(t):Number.isFinite(this.totalNodeCount)&&this.totalNodeCount>=0?this.totalNodeCount:0;for(;this.managedNodes.length<i;){const e=this.managedNodes.length;this.managedNodes.push({__loading:!0,__index:e})}this.managedNodes.length=i;for(let n=0;n<i;n++){const e=Hn(n,t,this.loadedBlocks);e&&(this.managedNodes[n]=e)}const r=this.grid;if("local"===this.config.sortMode&&r?._sortState){const e=r._columns??[],t=(r.effectiveConfig?.sortHandler??V)(this.managedNodes,r._sortState,e);return t&&"function"==typeof t.then?(t.catch(()=>{}),this.managedNodes):t}return this.managedNodes}onScroll(e){this.dataSource&&(this.loadRequiredBlocks(),this.scrollDebounceTimer&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.loadRequiredBlocks()},100))}handleQuery(e){switch(e.type){case"datasource:is-active":return null!=this.dataSource;case"datasource:fetch-children":{const{context:t}=e.context;return void this.fetchChildren(t)}}}fetchChildren(e){if(!this.dataSource)return;const t=this.grid?.getAttribute?.("id")??void 0;if(!this.dataSource.getChildRows)return void p("TBW142",`Plugin "${e.source}" requested child rows but getChildRows() is not implemented on the dataSource`,t);const i=this.getEnrichmentParams();this.broadcast("datasource:loading",{loading:!0,context:e}),this.dataSource.getChildRows({context:e,sortModel:i.sortModel,filterModel:i.filterModel}).then(t=>{const i={rows:t.rows,context:e,claimed:!1};this.broadcast("datasource:children",i),this.broadcast("datasource:loading",{loading:!1,context:e})}).catch(i=>{const r=i instanceof Error?i:new Error(String(i));w("TBW141",`getChildRows() failed: ${r.message}`,t),this.broadcast("datasource:error",{error:r,context:e}),this.broadcast("datasource:loading",{loading:!1,context:e})})}setDataSource(e){this.abortAllBlocks(),this.dataSource=e,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1;const t=this.config.cacheBlockSize??100,i=this.getEnrichmentParams(),r=this.grid?.getAttribute?.("id")??void 0,n=new AbortController;this.blockControllers.set(0,n),this.loadingBlocks.add(0),this.broadcast("datasource:loading",{loading:!0}),Fn(e,0,t,i,n.signal).then(e=>{if(this.blockControllers.delete(0),this.loadingBlocks.delete(0),n.signal.aborted)return void this.broadcast("datasource:loading",{loading:!1});this.loadedBlocks.set(0,e.rows),this.applyServerResult(e,0,t);const i={rows:e.rows,totalNodeCount:e.totalNodeCount,startNode:0,endNode:e.rows.length,claimed:!1};this.broadcast("datasource:data",i),this.broadcast("datasource:loading",{loading:!1}),this.requestRender(),(this.config.loadThreshold??0)>0&&this.loadRequiredBlocks()}).catch(e=>{if(this.blockControllers.delete(0),this.loadingBlocks.delete(0),n.signal.aborted)return void this.broadcast("datasource:loading",{loading:!1});const t=e instanceof Error?e:new Error(String(e));w(u,`getRows() failed: ${t.message}`,r),this.broadcast("datasource:error",{error:t}),this.broadcast("datasource:loading",{loading:!1})})}refresh(){if(!this.dataSource)return;const e=this.dataSource;this.abortAllBlocks(),this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1,this.setDataSource(e)}purgeCache(){this.abortAllBlocks(),this.loadedBlocks.clear(),this.managedNodes=[]}getTotalNodeCount(){return this.totalNodeCount}getTotalRowCount(){return this.totalNodeCount}isNodeLoaded(e){const t=Pn(e,this.config.cacheBlockSize??100);return this.loadedBlocks.has(t)}isRowLoaded(e){return this.isNodeLoaded(e)}getLoadedBlockCount(){return this.loadedBlocks.size}},e.TooltipPlugin=class extends ${name="tooltip";styles='@layer tbw-plugins{.tbw-tooltip-popover{margin:0;padding:var(--tbw-tooltip-padding, var(--tbw-spacing-sm, .375rem) var(--tbw-spacing-md, .5rem));background:var(--tbw-tooltip-bg, light-dark(#333338, #484850));color:var(--tbw-tooltip-fg, light-dark(#f5f5f5, #f0f0f0));border:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72));border-radius:var(--tbw-tooltip-radius, var(--tbw-border-radius, .25rem));box-shadow:none;filter:var(--tbw-tooltip-shadow, drop-shadow(0 4px 4px rgba(0, 0, 0, .45)));font-family:var(--tbw-font-family, system-ui, sans-serif);font-size:var(--tbw-tooltip-font-size, var(--tbw-font-size-sm, .9285em));max-width:var(--tbw-tooltip-max-width, 300px);white-space:pre-line;word-wrap:break-word;overflow-wrap:break-word;pointer-events:none;z-index:10001}.tbw-tooltip-popover:after{content:"";position:absolute;width:var(--tbw-tooltip-arrow-size, 14px);height:var(--tbw-tooltip-arrow-size, 14px);left:var(--tbw-tooltip-arrow-offset, 16px);background:inherit;pointer-events:none}.tbw-tooltip-popover:not(.tbw-tooltip-above):after{top:calc(var(--tbw-tooltip-arrow-size, 14px) / -2);transform:rotate(45deg);border-top:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72));border-left:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72))}.tbw-tooltip-popover.tbw-tooltip-above:after{bottom:calc(var(--tbw-tooltip-arrow-size, 14px) / -2);transform:rotate(45deg);border-bottom:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72));border-right:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72))}@supports (anchor-name: --test){.tbw-tooltip-popover{position-anchor:--tbw-tooltip-anchor;top:calc(anchor(bottom) + 11px);left:anchor(left);position-try-fallbacks:--tbw-tooltip-flip-above}@position-try --tbw-tooltip-flip-above{top:auto;bottom:calc(anchor(top) + 11px)}}}';static manifest={ownedProperties:[{property:"cellTooltip",level:"column",description:'the "cellTooltip" column property'},{property:"headerTooltip",level:"column",description:'the "headerTooltip" column property'}],configRules:[]};#_r=null;#Ar=null;#kr=!1;get#Tr(){return!1!==this.config.header}get#Ir(){return!1!==this.config.cell}attach(e){super.attach(e)}detach(){this.#Mr(),this.#_r?.remove(),this.#_r=null,this.#kr=!1,super.detach()}afterRender(){this.#Lr(),this.#Pr()}#Lr(){if(this.#_r)return;const e=document.createElement("div");e.className="tbw-tooltip-popover",e.setAttribute("popover","hint"),e.style.overflow="visible",e.style.margin="0",document.body.appendChild(e),this.#_r=e}#Dr(e,t){if(this.#_r){if(this.#Fr(),e.style.setProperty("anchor-name","--tbw-tooltip-anchor"),this.#Ar=e,this.#_r.textContent=t,Nn())try{this.#_r.showPopover()}catch{}"undefined"!=typeof CSS&&!0===CSS.supports?.("anchor-name","--test")?requestAnimationFrame(()=>this.#Hr(e)):this.#Gr(e)}}#Mr(){if(this.#_r){if(Nn())try{this.#_r.hidePopover()}catch{}this.#_r.classList.remove("tbw-tooltip-above")}this.#Fr()}#Fr(){this.#Ar&&("--tbw-tooltip-anchor"===this.#Ar.style.getPropertyValue("anchor-name")&&this.#Ar.style.removeProperty("anchor-name"),this.#Ar=null)}#Gr(e){if(!this.#_r)return;const t=e.getBoundingClientRect();this.#_r.style.position="fixed",this.#_r.style.left=`${t.left}px`;window.innerHeight-t.bottom<80?(this.#_r.style.top="",this.#_r.style.bottom=window.innerHeight-t.top+11+"px",this.#_r.classList.add("tbw-tooltip-above")):(this.#_r.style.top=`${t.bottom+11}px`,this.#_r.style.bottom="",this.#_r.classList.remove("tbw-tooltip-above"))}#Hr(e){if(!this.#_r)return;const t=e.getBoundingClientRect(),i=this.#_r.getBoundingClientRect();this.#_r.classList.toggle("tbw-tooltip-above",i.bottom<=t.top)}#Pr(){if(this.#kr)return;const e=this.gridElement?.querySelector(".tbw-grid-root");e&&(this.#kr=!0,e.addEventListener("mouseover",e=>this.#Nr(e),{signal:this.disconnectSignal}),e.addEventListener("mouseout",e=>this.#Or(e),{signal:this.disconnectSignal}))}#Nr(e){const t=e.target;if(!t?.closest)return;const i=t.closest('[part~="header-cell"]');if(i&&this.#Tr)return void this.#qr(i);const r=t.closest("[data-row][data-col]");r&&this.#Ir&&!r.style.getPropertyValue("anchor-name")&&this.#zr(r)}#Or(e){const t=e.target;if(!t?.closest)return;const i=t.closest('[part~="header-cell"], [data-row][data-col]');if(!i)return;const r=e.relatedTarget;r&&i.contains(r)||this.#Mr()}#qr(e){const t=parseInt(e.getAttribute("data-col")??"-1",10);if(t<0)return;const i=this.visibleColumns[t];if(!i)return;const r=function(e,t){const i=e.headerTooltip;if(!1===i)return null;if("string"==typeof i)return i;if("function"==typeof i)return i({column:e,value:e.header??e.field});const r=t.querySelector("span:first-child")??t;return Gn(r)&&r.textContent?.trim()||null}(i,e);r&&this.#Dr(e,r)}#zr(e){const t=parseInt(e.getAttribute("data-row")??"-1",10),i=parseInt(e.getAttribute("data-col")??"-1",10);if(t<0||i<0)return;const r=this.visibleColumns[i];if(!r)return;const n=this.rows[t],o=n?.[r.field],s=function(e,t,i,r,n){const o=e.cellTooltip;if(!1===o)return null;if("string"==typeof o)return o;if("function"==typeof o)return o({value:r,row:i,column:e,field:e.field,grid:n});return Gn(t)&&t.textContent?.trim()||null}(r,e,n,o,this.grid);s&&this.#Dr(e,s)}},e.TreePlugin=class extends ${static manifest={modifiesRowStructure:!0,hookPriority:{processRows:10},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."}],events:[{type:"tree-expand",description:"Emitted when tree expansion state changes (toggle, expand all, collapse all). Broadcast to both DOM consumers and plugin bus."}],queries:[{type:"canMoveRow",description:"Returns false for rows with children (parent nodes cannot be reordered)"},{type:"datasource:viewport-mapping",description:"Translates flat viewport row indices to top-level node indices for ServerSide pagination."}]};static dependencies=[{name:"multiSort",required:!1,reason:"Queries sort model for coordinated tree sorting"},{name:"serverSide",required:!1,reason:"Consumes datasource events for lazy-loaded tree data"}];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;vertical-align:middle;overflow:visible;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);height: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}}tbw-grid.tbw-tree-loading .rows-viewport:after{content:"";display:block;height:2px;background:linear-gradient(90deg,transparent,var(--tbw-color-accent, #2563eb),transparent);animation:tbw-tree-loading-bar 1s ease-in-out infinite;position:sticky;bottom:0;left:0;right:0}@keyframes tbw-tree-loading-bar{0%{transform:translate(-100%)}to{transform:translate(100%)}}}';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;loadingKeys=new Set;#$r=new WeakMap;#Br=new WeakMap;originalTreeColumnRenderer;wrappedTreeColumnField;detach(){this.expandedKeys.clear(),this.initialExpansionDone=!1,this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.sortState=null,this.loadingKeys.clear(),this.originalTreeColumnRenderer=void 0,this.wrappedTreeColumnField=void 0}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}if("datasource:viewport-mapping"===e.type){const{viewportStart:t,viewportEnd:i}=e.context;if(0===this.flattenedRows.length)return;return{startNode:Wn(this.flattenedRows,t),endNode:Wn(this.flattenedRows,i)+1,totalLoadedNodes:function(e){let t=0;for(const i of e)0===i.depth&&t++;return t}(this.flattenedRows)}}}attach(e){super.attach(e),this.on("datasource:data",e=>{const t=e;t.claimed||(t.claimed=!0)}),this.on("datasource:children",e=>{const t=e;if("tree"!==t.context?.source)return;t.claimed=!0;const i=t.context.parentNode;if(i){i[this.config.childrenField??"children"]=t.rows;const e=this.#$r.get(i)??String(i.id??"?");this.loadingKeys.delete(e),this.requestRender()}})}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 Kn(t,i)}processRows(e){const t=this.config.childrenField??"children",i=e;if(0===i.length||!Kn(i,t))return this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),[...e];const r=this.resolveEffectiveSortState();this.config.defaultExpanded&&!this.initialExpansionDone&&(this.expandedKeys=zn(i,this.config),this.initialExpansionDone=!0),this.flattenedRows=this.#Wr(i,this.expandedKeys,r,null,0),this.#Br=new WeakMap,this.rowKeyMap.clear(),this.keysToAnimate.clear();const n=new Set;for(const o of this.flattenedRows)this.rowKeyMap.set(o.key,o),this.#Br.set(o.data,o),n.add(o.key),!this.previousVisibleKeys.has(o.key)&&o.depth>0&&this.keysToAnimate.add(o.key);return this.previousVisibleKeys=n,this.flattenedRows.map(e=>e.data)}#Kr(e,t,i){if(void 0!==e.id){const t=String(e.id);return this.#$r.set(e,t),t}const r=this.#$r.get(e);if(void 0!==r)return r;const n=i?`${i}-${t}`:String(t);return this.#$r.set(e,n),n}#Wr(e,t,i,r,n){const o=this.config.childrenField??"children";for(let a=0;a<e.length;a++)this.#Kr(e[a],a,r);const s=i?this.#Vr(e,i.field,i.direction):e,l=[];for(let a=0;a<s.length;a++){const e=s[a],d=this.#Kr(e,a,r),c=e[o],u=Array.isArray(c)&&c.length>0,h=null!=c&&!Array.isArray(c)&&!!c,g=u||h,p=t.has(d);l.push({key:d,data:e,depth:n,hasChildren:g,isExpanded:p,parentKey:r}),u&&p&&l.push(...this.#Wr(c,t,i,d,n+1))}return l}#Vr(e,t,i){const r=this.grid,n=r?._columns??[],o={field:t,direction:i},s=[...e],l=(r?.effectiveConfig?.sortHandler??V)(s,o,n);return l&&"function"==typeof l.then?(l.catch(()=>{}),V(s,o,n)):l}requestLazyChildren(e){if(this.loadingKeys.has(e.key))return;const t=this.config.childrenField??"children",i=e.data[t];if(Array.isArray(i)&&i.length>0)return;const r=this.grid?.query?.("datasource:is-active",null);r&&(this.loadingKeys.add(e.key),this.grid.query("datasource:fetch-children",{context:{source:"tree",parentNode:e.data,nodePath:[e.key]}}))}resolveEffectiveSortState(){const e=this.grid?.query?.("sort:get-model",null);if(Array.isArray(e)&&e.length>0){const t=e[0];if(Array.isArray(t)&&t.length>0)return{field:t[0].field,direction:"desc"===t[0].direction?-1:1}}return this.sortState}processColumns(e){if(0===this.flattenedRows.length)return[...e];const t=[...e];if(0===t.length)return t;const{treeColumn:i}=this.config;let r=0;if(i){const e=t.findIndex(e=>e.field===i);e>=0&&(r=e)}const n=t[r],o=n.field;this.wrappedTreeColumnField!==o&&(this.originalTreeColumnRenderer=n.viewRenderer,this.wrappedTreeColumnField=o);const s=this.originalTreeColumnRenderer,l=()=>this.config,a=this.setIcon.bind(this);return t[r]={...n,viewRenderer:e=>{const{row:t,value:i}=e,{showExpandIcons:r=!0,indentWidth:n}=l(),o=this.#Br.get(t),d=o?.depth??0,c=document.createElement("span");if(c.className="tree-cell-wrapper",c.style.setProperty("--tbw-tree-depth",String(d)),void 0!==n&&c.style.setProperty("--tbw-tree-indent-width",`${n}px`),r)if(o&&o.hasChildren){const e=document.createElement("span");e.className=`${R.TREE_TOGGLE}${o.isExpanded?` ${R.EXPANDED}`:""}`,a(e,o.isExpanded?"collapse":"expand"),e.setAttribute("data-tree-key",o.key),c.appendChild(e)}else{const e=document.createElement("span");e.className="tree-spacer",c.appendChild(e)}const u=document.createElement("span");if(u.className="tree-content",s){const t=s(e);t instanceof Node?u.appendChild(t):"string"==typeof t&&(u.innerHTML=t)}else u.textContent=null!=i?String(i):"";return c.appendChild(u),c}},t}onCellClick(e){const t=e.originalEvent?.target;if(!t?.classList.contains(R.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=qn(this.expandedKeys,i),this.expandedKeys.has(i)&&this.requestLazyChildren(r),this.broadcast("tree-expand",{key:i,row:r.data,expanded:this.expandedKeys.has(i),depth:r.depth,expandedKeys:[...this.expandedKeys]}),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=qn(this.expandedKeys,i.key),this.expandedKeys.has(i.key)&&this.requestLazyChildren(i),this.broadcast("tree-expand",{key:i.key,row:i.data,expanded:this.expandedKeys.has(i.key),depth:i.depth,expandedKeys:[...this.expandedKeys]}),this.requestRenderWithFocus(),!0):void 0}onHeaderClick(e){if(0===this.flattenedRows.length||!e.column.sortable)return!1;const t=this.grid?.query?.("sort:get-model",null);if(Array.isArray(t)&&t.length>0)return!1;const{field:i}=e.column;this.sortState&&this.sortState.field===i?1===this.sortState.direction?this.sortState={field:i,direction:-1}:this.sortState=null:this.sortState={field:i,direction:1};const r=this.grid;return void 0!==r._sortState&&(r._sortState=this.sortState?{...this.sortState}:null),this.broadcast("sort-change",{field:i,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);const t=this.rowKeyMap.get(e);t&&this.requestLazyChildren(t),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}toggle(e){this.expandedKeys=qn(this.expandedKeys,e);const t=this.rowKeyMap.get(e);t?(this.expandedKeys.has(e)&&this.requestLazyChildren(t),this.broadcast("tree-expand",{key:e,row:t.data,expanded:this.expandedKeys.has(e),depth:t.depth,expandedKeys:[...this.expandedKeys]})):this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}expandAll(){this.expandedKeys=zn(this.rows,this.config),this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}getExpandedKeys(){return[...this.expandedKeys]}getFlattenedRows(){return[...this.flattenedRows]}getRowMeta(e){return this.#Br.get(e)}getRowByKey(e){return this.rowKeyMap.get(e)?.data}expandToKey(e){this.expandedKeys=Bn(this.rows,e,this.config,this.expandedKeys),this.requestRender()}},e.UndoRedoPlugin=class extends ${static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];#jr=!1;#Ur=null;#Yr(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}}#Xr(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(R.EDITING)){const e=n.querySelector(Ce);e?.focus({preventScroll:!0})}}#Zr(e,t){if(this.#jr=!0,"compound"===e.type){const i="undo"===t?[...e.actions].reverse():e.actions;for(const e of i)this.#Yr(e,"undo"===t?e.oldValue:e.newValue)}else this.#Yr(e,"undo"===t?e.oldValue:e.newValue);this.#jr=!1}#Qr(e){const t="compound"===e.type?e.actions[e.actions.length-1]:e;t&&this.#Xr(t)}attach(e){super.attach(e),this.on("cell-edit-committed",e=>{this.#jr||this.recordEdit(e.rowIndex,e.field,e.oldValue,e.newValue)})}detach(){this.undoStack=[],this.redoStack=[],this.#Ur=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=jn({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#Zr(t.action,"undo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.emit("undo",{action:t.action,type:"undo"}),this.#Qr(t.action),this.requestRenderWithFocus()),!0}if(i){e.preventDefault();const t=Un({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#Zr(t.action,"redo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.emit("redo",{action:t.action,type:"redo"}),this.#Qr(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.#Ur)return void this.#Ur.push(n);const o=Vn({undoStack:this.undoStack,redoStack:this.redoStack},n,this.config.maxHistorySize??100);this.undoStack=o.undoStack,this.redoStack=o.redoStack}beginTransaction(){this.#Ur&&g("TBW111","Transaction already in progress. Call endTransaction() first."),this.#Ur=[]}endTransaction(){const e=this.#Ur;if(e||g("TBW112","No transaction in progress. Call beginTransaction() first."),this.#Ur=null,0===e.length)return;const t=1===e.length?e[0]:{type:"compound",actions:e,timestamp:Date.now()};const i=Vn({undoStack:this.undoStack,redoStack:this.redoStack},t,this.config.maxHistorySize??100);this.undoStack=i.undoStack,this.redoStack=i.redoStack}undo(){const e=jn({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#Zr(e.action,"undo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.#Qr(e.action),this.requestRenderWithFocus()),e.action}redo(){const e=Un({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#Zr(e.action,"redo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.#Qr(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.#Ur=null}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}},e.VisibilityPlugin=Yn,e.builtInSort=V,e.createGrid=function(e){const t=document.createElement("tbw-grid");return e&&(t.gridConfig=e),t},e.defaultComparator=function(e,t){return null==e&&null==t?0:null==e?-1:null==t||e>t?1:e<t?-1:0},e.defaultEditorFor=hi,e.defaultPasteHandler=Ut,e.filteredCountPanel=function(){return e=>{if(e.filteredRows===e.totalRows)return null;const t=document.createElement("span");return t.className="tbw-status-panel tbw-status-panel-filtered-count",t.textContent=`Filtered: ${e.filteredRows}`,t}},e.invalidateAccessorCache=K,e.printGridIsolated=rn,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(Wt.tagName).then(()=>r.querySelector(e)):r.querySelector(e)},e.resolveCellValue=W,e.rowCountPanel=function(){return e=>{const t=document.createElement("span");return t.className="tbw-status-panel tbw-status-panel-row-count",t.textContent=`Total: ${e.totalRows} rows`,t}},e.selectedCountPanel=function(){return e=>{if(e.selectedRows<=0)return null;const t=document.createElement("span");return t.className="tbw-status-panel tbw-status-panel-selected-count",t.textContent=`Selected: ${e.selectedRows}`,t}},e.setFeatureResolver=function(e){Oe=e},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=grid.all.umd.js.map
|