@toolbox-web/grid 1.22.0 → 1.23.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.
Files changed (66) hide show
  1. package/README.md +20 -10
  2. package/all.js +2 -2
  3. package/all.js.map +1 -1
  4. package/index.js +1 -1
  5. package/index.js.map +1 -1
  6. package/lib/core/grid.d.ts +88 -1
  7. package/lib/core/grid.d.ts.map +1 -1
  8. package/lib/core/types.d.ts +61 -0
  9. package/lib/core/types.d.ts.map +1 -1
  10. package/lib/plugins/clipboard/index.js.map +1 -1
  11. package/lib/plugins/column-virtualization/index.js.map +1 -1
  12. package/lib/plugins/context-menu/index.js.map +1 -1
  13. package/lib/plugins/editing/EditingPlugin.d.ts +132 -1
  14. package/lib/plugins/editing/EditingPlugin.d.ts.map +1 -1
  15. package/lib/plugins/editing/editors.d.ts.map +1 -1
  16. package/lib/plugins/editing/index.d.ts +1 -0
  17. package/lib/plugins/editing/index.d.ts.map +1 -1
  18. package/lib/plugins/editing/index.js +1 -1
  19. package/lib/plugins/editing/index.js.map +1 -1
  20. package/lib/plugins/editing/internal/dirty-tracking.d.ts +90 -0
  21. package/lib/plugins/editing/internal/dirty-tracking.d.ts.map +1 -0
  22. package/lib/plugins/editing/types.d.ts +82 -0
  23. package/lib/plugins/editing/types.d.ts.map +1 -1
  24. package/lib/plugins/export/index.js.map +1 -1
  25. package/lib/plugins/filtering/FilteringPlugin.d.ts +17 -4
  26. package/lib/plugins/filtering/FilteringPlugin.d.ts.map +1 -1
  27. package/lib/plugins/filtering/index.js +1 -1
  28. package/lib/plugins/filtering/index.js.map +1 -1
  29. package/lib/plugins/grouping-columns/index.js.map +1 -1
  30. package/lib/plugins/grouping-rows/index.js.map +1 -1
  31. package/lib/plugins/master-detail/index.js.map +1 -1
  32. package/lib/plugins/multi-sort/index.js.map +1 -1
  33. package/lib/plugins/pinned-columns/index.js.map +1 -1
  34. package/lib/plugins/pinned-rows/index.js.map +1 -1
  35. package/lib/plugins/pivot/index.js.map +1 -1
  36. package/lib/plugins/print/index.js.map +1 -1
  37. package/lib/plugins/reorder/index.js.map +1 -1
  38. package/lib/plugins/responsive/index.js.map +1 -1
  39. package/lib/plugins/row-reorder/index.js.map +1 -1
  40. package/lib/plugins/selection/index.js.map +1 -1
  41. package/lib/plugins/server-side/index.js.map +1 -1
  42. package/lib/plugins/tree/index.js.map +1 -1
  43. package/lib/plugins/undo-redo/UndoRedoPlugin.d.ts +52 -7
  44. package/lib/plugins/undo-redo/UndoRedoPlugin.d.ts.map +1 -1
  45. package/lib/plugins/undo-redo/history.d.ts +11 -4
  46. package/lib/plugins/undo-redo/history.d.ts.map +1 -1
  47. package/lib/plugins/undo-redo/index.d.ts +1 -1
  48. package/lib/plugins/undo-redo/index.d.ts.map +1 -1
  49. package/lib/plugins/undo-redo/index.js +1 -1
  50. package/lib/plugins/undo-redo/index.js.map +1 -1
  51. package/lib/plugins/undo-redo/types.d.ts +20 -3
  52. package/lib/plugins/undo-redo/types.d.ts.map +1 -1
  53. package/lib/plugins/visibility/index.js.map +1 -1
  54. package/package.json +1 -1
  55. package/public.d.ts +1 -1
  56. package/public.d.ts.map +1 -1
  57. package/umd/grid.all.umd.js +1 -1
  58. package/umd/grid.all.umd.js.map +1 -1
  59. package/umd/grid.umd.js +1 -1
  60. package/umd/grid.umd.js.map +1 -1
  61. package/umd/plugins/editing.umd.js +1 -1
  62. package/umd/plugins/editing.umd.js.map +1 -1
  63. package/umd/plugins/filtering.umd.js +1 -1
  64. package/umd/plugins/filtering.umd.js.map +1 -1
  65. package/umd/plugins/undo-redo.umd.js +1 -1
  66. package/umd/plugins/undo-redo.umd.js.map +1 -1
@@ -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={mode:"reduced-motion",duration:200,easing:"ease-out"},n='<svg viewBox="0 0 16 16" width="12" height="12"><path fill="currentColor" d="M6 10.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/></svg>',r={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:n,filterActive:n,print:"🖨️"};function o(e,t){if(!(e&&e.length||t&&t.length))return[];if(!e||!e.length)return t||[];if(!t||!t.length)return e;const i={};t.forEach(e=>{const t=i[e.field];if(t){e.header&&!t.header&&(t.header=e.header),e.type&&!t.type&&(t.type=e.type),e.sortable&&(t.sortable=!0),e.editable&&(t.editable=!0),e.resizable&&(t.resizable=!0),null!=e.width&&null==t.width&&(t.width=e.width),null!=e.minWidth&&null==t.minWidth&&(t.minWidth=e.minWidth),e.__viewTemplate&&(t.__viewTemplate=e.__viewTemplate),e.__editorTemplate&&(t.__editorTemplate=e.__editorTemplate),e.__headerTemplate&&(t.__headerTemplate=e.__headerTemplate);const i=e.renderer||e.viewRenderer,n=t.renderer||t.viewRenderer;i&&!n&&(t.viewRenderer=i,e.renderer&&(t.renderer=i)),e.editor&&!t.editor&&(t.editor=e.editor)}else i[e.field]={...e}});const n=e.map(e=>{const t=i[e.field];if(!t)return e;const n={...e};t.header&&!n.header&&(n.header=t.header),t.type&&!n.type&&(n.type=t.type),n.sortable=e.sortable||t.sortable,!0!==e.resizable&&!0!==t.resizable||(n.resizable=!0),n.editable=e.editable||t.editable,null!=t.width&&null==n.width&&(n.width=t.width),null!=t.minWidth&&null==n.minWidth&&(n.minWidth=t.minWidth),t.__viewTemplate&&(n.__viewTemplate=t.__viewTemplate),t.__editorTemplate&&(n.__editorTemplate=t.__editorTemplate),t.__headerTemplate&&(n.__headerTemplate=t.__headerTemplate);const r=t.renderer||t.viewRenderer,o=n.renderer||n.viewRenderer;return r&&!o&&(n.viewRenderer=r,t.renderer&&(n.renderer=r)),t.editor&&!n.editor&&(n.editor=t.editor),delete i[e.field],n});return Object.keys(i).forEach(e=>n.push(i[e])),n}function s(e,t){try{e.part?.add?.(t)}catch{}const i=e.getAttribute("part");i?i.split(/\s+/).includes(t)||e.setAttribute("part",i+" "+t):e.setAttribute("part",t)}function l(e){const i=e.effectiveConfig?.fitMode||e.fitMode||t.STRETCH;if(i!==t.STRETCH&&i!==t.FIXED)return;if(e.__didInitialAutoSize)return;if(!e.isConnected)return;const n=Array.from(e._headerRowEl?.children||[]);if(!n.length)return;let r=!1;e._visibleColumns.forEach((t,i)=>{if(t.width)return;const o=n[i];let s=o?o.scrollWidth:0;for(const n of e._rowPool){const e=n.children[i];if(e){const t=e.scrollWidth;t>s&&(s=t)}}s>0&&(t.width=s+2,t.__autoSized=!0,r=!0)}),r&&c(e),e.__didInitialAutoSize=!0}const a=/^(?:\d+(?:\.\d+)?(?:px|%|fr|em|rem|ch|vw|vh|vmin|vmax)|calc\(.+\)|min-content|max-content|minmax\(.+\)|fit-content\(.+\)|auto)$/i;function d(e,t){return"number"==typeof e?`${e}px`:(a.test(e)||console.warn(`[tbw-grid] Column '${t??"?"}' has an invalid CSS width value: '${e}'. Expected a number (px) or a valid CSS unit string (e.g. '30%', '2fr', 'calc(...)').`),e)}function c(e){const i=e.effectiveConfig?.fitMode||e.fitMode||t.STRETCH;e._gridTemplate=i===t.STRETCH?e._visibleColumns.map(e=>{if(null!=e.width)return d(e.width,e.field);const t=e.minWidth;return null!=t?`minmax(${t}px, 1fr)`:"1fr"}).join(" ").trim():e._visibleColumns.map(e=>null!=e.width?d(e.width,e.field):"max-content").join(" "),e.style.setProperty("--tbw-column-template",e._gridTemplate)}function h(e,t){const i=e[0]||{},n=Object.keys(i).map(e=>{const t=i[e],n=null==(r=t)?"string":"number"==typeof r?"number":"boolean"==typeof r?"boolean":r instanceof Date||"string"==typeof r&&/\d{4}-\d{2}-\d{2}/.test(r)&&!isNaN(Date.parse(r))?"date":"string";var r;return{field:e,header:e.charAt(0).toUpperCase()+e.slice(1),type:n}}),r={};return n.forEach(e=>{r[e.field]=e.type||"string"}),{columns:n,typeMap:r}}const u=/{{\s*([^}]+)\s*}}/g,g="__DG_EMPTY__",p=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,f=/__(proto|defineGetter|defineSetter)|constructor|window|globalThis|global|process|Function|import|eval|Reflect|Proxy|Error|arguments|document|location|cookie|localStorage|sessionStorage|indexedDB|fetch|XMLHttpRequest|WebSocket|Worker|SharedWorker|ServiceWorker|opener|parent|top|frames|self|this\b/;const w=new Set(["script","iframe","object","embed","form","input","button","textarea","select","link","meta","base","style","template","slot","portal","frame","frameset","applet","noscript","noembed","plaintext","xmp","listing"]),m=/^on\w+$/i,b=new Set(["href","src","action","formaction","data","srcdoc","xlink:href","poster","srcset"]),v=/^\s*(javascript|vbscript|data|blob):/i;function y(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],i=e.querySelectorAll("*");for(const n of i){const e=n.tagName.toLowerCase();if(w.has(e)){t.push(n);continue}if("svg"===e||"http://www.w3.org/2000/svg"===n.namespaceURI){if(Array.from(n.attributes).some(e=>m.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(n);continue}}const i=[];for(const t of n.attributes){const e=t.name.toLowerCase();m.test(e)?i.push(t.name):(b.has(e)&&v.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&i.push(t.name)}i.forEach(e=>n.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}function C(e,t){if(!e||-1===e.indexOf("{{"))return e;const i=[],n=e.replace(u,(e,n)=>{const r=function(e,t){if(e=(e||"").trim(),!e)return g;if(x.test(e))return g;if("value"===e)return null==t.value?g:String(t.value);if(e.startsWith("row.")&&!/[()?]/.test(e)&&!e.includes(":")){const i=e.slice(4),n=t.row?t.row[i]:void 0;return null==n?g:String(n)}if(e.length>80)return g;if(!p.test(e)||f.test(e))return g;const i=e.match(/\./g);if(i&&i.length>1)return g;try{const i=new Function("value","row",`return (${e});`)(t.value,t.row),n=null==i?"":String(i);return x.test(n)?g:n||g}catch{return g}}(n,t);return i.push({expr:n.trim(),result:r}),r}),r=(o=n)?o.replace(new RegExp(g,"g"),"").replace(/Reflect\.[^<>{}\s]+|\bProxy\b|ownKeys\([^)]*\)/g,""):o;var o;const s=i.length&&i.every(e=>""===e.result||e.result===g);return x.test(e)||s?"":r}const x=/Reflect|Proxy|ownKeys/;function E(e){if(x.test(e.textContent||"")){for(const t of e.childNodes)t.nodeType===Node.TEXT_NODE&&x.test(t.textContent||"")&&(t.textContent="");x.test(e.textContent||"")&&(e.textContent="")}}function R(e){const t=x.test(e),i=i=>{if(t)return"";return C(e,i)};return i.__blocked=t,i}class S{#e;#t;#i;#n;#r;#o={};#s={};#l=!0;#a=[];#d;#c;#h;#u;#g;constructor(e){this.#u=e}get original(){return this.#o}get effective(){return this.#s}get columns(){return this.#s.columns??[]}set columns(e){this.#s.columns=e}get lightDomColumnsCache(){return this.#n}set lightDomColumnsCache(e){this.#n=e}get originalColumnNodes(){return this.#r}set originalColumnNodes(e){this.#r=e}get lightDomTitle(){return this.#g}set lightDomTitle(e){this.#g=e}get initialColumnState(){return this.#h}set initialColumnState(e){this.#h=e}get sourcesChanged(){return this.#l}markSourcesChanged(){this.#l=!0}setGridConfig(e){this.#e=e,this.#l=!0,this.#n=void 0}getGridConfig(){return this.#e}setColumns(e){this.#t=e,this.#l=!0}getColumns(){return this.#t}setFitMode(e){this.#i=e,this.#l=!0}getFitMode(){return this.#i}merge(){const e=(this.#s.columns?.length??0)>0;if(!this.#l&&e)return;const t=this.#p();this.#l=!1,this.#o=t,Object.freeze(this.#o),this.#o.columns&&Object.freeze(this.#o.columns),this.#s=this.#f(this.#o),this.#w()}#f(e){const t={...e};return e.columns&&(t.columns=e.columns.map(e=>({...e}))),e.shell&&(t.shell={...e.shell,header:e.shell.header?{...e.shell.header}:void 0,toolPanel:e.shell.toolPanel?{...e.shell.toolPanel}:void 0,toolPanels:e.shell.toolPanels?.map(e=>({...e})),headerContents:e.shell.headerContents?.map(e=>({...e}))}),t}#w(){const e=this.#s;if(this.#m(),"number"==typeof e.rowHeight&&e.rowHeight>0&&this.#u.setRowHeight(e.rowHeight),"fixed"===e.fitMode){this.columns.forEach(e=>{null==e.width&&(e.width=80)})}this.#u.applyAnimationConfig(e)}#m(){const e=this.#s.typeDefaults;if(!e)return;const t=this.columns;for(const i of t){if(!i.type)continue;const t=e[i.type];t&&(i.renderer||i.viewRenderer||!t.renderer||(i.renderer=t.renderer),!i.format&&t.format&&(i.format=t.format),!i.editor&&t.editor&&(i.editor=t.editor),!i.editorParams&&t.editorParams&&(i.editorParams=t.editorParams))}}#p(){const e=this.#e?{...this.#e}:{},t=Array.isArray(e.columns)?[...e.columns]:[],i=(this.#n??[]).map(e=>({...e}));let n=o(t,i);this.#t&&this.#t.length&&(n=o(this.#t,i));const r=this.#u.getRows();if(0===n.length&&r.length){n=h(r).columns}return n.length&&(n.forEach(e=>{void 0===e.sortable&&(e.sortable=!0),void 0===e.resizable&&(e.resizable=!0),void 0===e.__originalWidth&&"number"==typeof e.width&&(e.__originalWidth=e.width)}),n.forEach(e=>{e.__viewTemplate&&!e.__compiledView&&(e.__compiledView=R(e.__viewTemplate.innerHTML)),e.__editorTemplate&&!e.__compiledEditor&&(e.__compiledEditor=R(e.__editorTemplate.innerHTML))}),e.columns=n),this.#i&&(e.fitMode=this.#i),e.fitMode||(e.fitMode="stretch"),this.#b(e),e.columnState&&!this.#h&&(this.#h=e.columnState),e}#b(e){e.shell=e.shell?{...e.shell}:{},e.shell.header=e.shell.header?{...e.shell.header}:{};const t=this.#u.getShellLightDomTitle();t&&(this.#g=t),this.#g&&!e.shell.header.title&&(e.shell.header.title=this.#g);const i=this.#u.getShellLightDomHeaderContent();i?.length>0&&(e.shell.header.lightDomContent=i),this.#u.getShellHasToolButtonsContainer()&&(e.shell.header.hasToolButtonsContainer=!0);const n=this.#u.getShellToolPanels();if(n.size>0){const t=Array.from(n.values());t.sort((e,t)=>(e.order??100)-(t.order??100)),e.shell.toolPanels=t}const r=this.#u.getShellHeaderContents();if(r.size>0){const t=Array.from(r.values());t.sort((e,t)=>(e.order??100)-(t.order??100)),e.shell.headerContents=t}const o=this.#u.getShellToolbarContents(),s=Array.from(o.values()),l=this.#e?.shell?.header?.toolbarContents??[],a=new Set(l.map(e=>e.id)),d=[...l];for(const c of s)a.has(c.id)||d.push(c);d.sort((e,t)=>(e.order??0)-(t.order??0)),e.shell.header.toolbarContents=d}collectState(e){const t=this.columns,i=this.#v();return{columns:t.map((t,n)=>{const r={field:t.field,order:n,visible:!t.hidden},o=t;void 0!==o.__renderedWidth?r.width=o.__renderedWidth:void 0!==t.width&&(r.width="string"==typeof t.width?parseFloat(t.width):t.width);const s=i.get(t.field);s&&(r.sort=s);for(const i of e)if(i.getColumnState){const e=i.getColumnState(t.field);e&&Object.assign(r,e)}return r})}}applyState(e,t){if(!e.columns||0===e.columns.length)return;const i=this.columns,n=new Map(e.columns.map(e=>[e.field,e])),r=i.map(e=>{const t=n.get(e.field);if(!t)return e;const i={...e};return void 0!==t.width&&(i.width=t.width,i.__renderedWidth=t.width),void 0!==t.visible&&(i.hidden=!t.visible),i});r.sort((e,t)=>(n.get(e.field)?.order??1/0)-(n.get(t.field)?.order??1/0)),this.columns=r;const o=e.columns.filter(e=>void 0!==e.sort).sort((e,t)=>(e.sort?.priority??0)-(t.sort?.priority??0));if(o.length>0){const e=o[0];e.sort&&this.#u.setSortState({field:e.field,direction:"asc"===e.sort.direction?1:-1})}else this.#u.setSortState(null);for(const s of t)if(s.applyColumnState)for(const t of e.columns)s.applyColumnState(t.field,t)}resetState(e){this.#h=void 0,this.#u.setSortState(null),this.#s=this.#f(this.#o),this.#w();for(const t of e)if(t.applyColumnState)for(const e of this.columns)t.applyColumnState(e.field,{field:e.field,order:0,visible:!0});this.requestStateChange(e)}#v(){const e=new Map,t=this.#u.getSortState();return t&&e.set(t.field,{direction:1===t.direction?"asc":"desc",priority:0}),e}requestStateChange(e){this.#c&&clearTimeout(this.#c),this.#c=setTimeout(()=>{this.#c=void 0;const t=this.collectState(e);this.#u.emit("column-state-change",t)},100)}setColumnVisible(e,t){const i=this.columns,n=i.find(t=>t.field===e);if(!n)return!1;if(!t&&n.lockVisible)return!1;if(!t){if(0===i.filter(t=>!t.hidden&&t.field!==e).length)return!1}return!!n.hidden!=!t&&(n.hidden=!t,this.#u.emit("column-visibility",{field:e,visible:t,visibleColumns:i.filter(e=>!e.hidden).map(e=>e.field)}),this.#u.clearRowPool(),this.#u.setup(),!0)}toggleColumnVisibility(e){const t=this.columns.find(t=>t.field===e);return!!t&&this.setColumnVisible(e,!!t.hidden)}isColumnVisible(e){const t=this.columns.find(t=>t.field===e);return!!t&&!t.hidden}showAllColumns(){const e=this.columns;e.some(e=>e.hidden)&&(e.forEach(e=>e.hidden=!1),this.#u.emit("column-visibility",{visibleColumns:e.map(e=>e.field)}),this.#u.clearRowPool(),this.#u.setup())}getAllColumns(){return this.columns.map(e=>({field:e.field,header:e.header||e.field,visible:!e.hidden,lockVisible:e.lockVisible,utility:!0===e.meta?.utility}))}getColumnOrder(){return this.columns.map(e=>e.field)}setColumnOrder(e){if(!e.length)return;const t=new Map(this.columns.map(e=>[e.field,e])),i=[];for(const n of e){const e=t.get(n);e&&(i.push(e),t.delete(n))}for(const n of t.values())i.push(n);this.columns=i,this.#u.renderHeader(),this.#u.updateTemplate(),this.#u.refreshVirtualWindow()}parseLightDomColumns(e){this.#n||(this.#r=Array.from(e.querySelectorAll("tbw-grid-column")),this.#n=this.#r.length?function(e){return Array.from(e.querySelectorAll("tbw-grid-column")).map(e=>{const t=e.getAttribute("field")||"";if(!t)return null;const i=e.getAttribute("type")||void 0,n={field:t,type:i&&new Set(["number","string","date","boolean","select"]).has(i)?i:void 0,header:e.getAttribute("header")||void 0,sortable:e.hasAttribute("sortable"),editable:e.hasAttribute("editable")},r=e.getAttribute("width");if(r){const e=parseFloat(r);!isNaN(e)&&/^\d+(\.\d+)?$/.test(r.trim())?n.width=e:n.width=r}const o=e.getAttribute("minWidth")||e.getAttribute("min-width");if(o){const e=parseFloat(o);isNaN(e)||(n.minWidth=e)}e.hasAttribute("resizable")&&(n.resizable=!0),e.hasAttribute("sizable")&&(n.resizable=!0);const s=e.getAttribute("editor"),l=e.getAttribute("renderer");s&&(n.__editorName=s),l&&(n.__rendererName=l);const a=e.getAttribute("options");a&&(n.options=a.split(",").map(e=>{const[t,i]=e.includes(":")?e.split(":"):[e.trim(),e.trim()];return{value:t.trim(),label:i?.trim()||t.trim()}}));const d=e.querySelector("tbw-grid-column-view"),c=e.querySelector("tbw-grid-column-editor"),h=e.querySelector("tbw-grid-column-header");d&&(n.__viewTemplate=d),c&&(n.__editorTemplate=c),h&&(n.__headerTemplate=h);const u=globalThis.DataGridElement,g=u?.getAdapters?.()??[],p=d??e,f=g.find(e=>e.canHandle(p));if(f){const e=f.createRenderer(p);e&&(n.viewRenderer=e)}const w=c??e,m=g.find(e=>e.canHandle(w));if(m){const e=m.createEditor(w);e&&(n.editor=e)}return n}).filter(e=>!!e)}(e):[])}clearLightDomCache(){this.#n=void 0}#y=new Map;registerLightDomHandler(e,t){this.#y.set(e.toLowerCase(),t)}unregisterLightDomHandler(e){this.#y.delete(e.toLowerCase())}observeLightDOM(e){this.#d&&this.#d.disconnect();const t=new Set;let i=null;const n=()=>{i=null;for(const e of t){const t=this.#y.get(e);t?.()}t.clear()};this.#d=new MutationObserver(e=>{for(const i of e){for(const e of i.addedNodes){if(e.nodeType!==Node.ELEMENT_NODE)continue;const i=e.tagName.toLowerCase();this.#y.has(i)&&t.add(i)}if("attributes"===i.type&&i.target.nodeType===Node.ELEMENT_NODE){const e=i.target.tagName.toLowerCase();this.#y.has(e)&&t.add(e)}}t.size>0&&!i&&(i=setTimeout(n,0))}),this.#d.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["title","field","header","width","hidden","id","icon","tooltip","order"]})}onChange(e){this.#a.push(e)}notifyChange(){for(const e of this.#a)e()}dispose(){this.#d?.disconnect(),this.#a=[],this.#c&&clearTimeout(this.#c)}}function _(){if("undefined"!=typeof window&&window.location){const e=window.location.hostname;if("localhost"===e||"127.0.0.1"===e||"::1"===e)return!0}return"undefined"!=typeof process&&"production"!==process.env?.NODE_ENV}function A(e){return`<span role="checkbox" aria-checked="${e}" aria-label="${e}">${e?"&#x1F5F9;":"&#9744;"}</span>`}function k(e){if(null==e||""===e)return"";if(e instanceof Date)return isNaN(e.getTime())?"":e.toLocaleDateString();if("number"==typeof e||"string"==typeof e){const t=new Date(e);return isNaN(t.getTime())?"":t.toLocaleDateString()}return""}function T(e){if(!e)return-1;const t=e.getAttribute("data-row");if(t)return parseInt(t,10);const i=e.closest(".data-grid-row");if(!i)return-1;const n=i.parentElement;if(!n)return-1;const r=n.querySelectorAll(":scope > .data-grid-row");for(let o=0;o<r.length;o++)if(r[o]===i)return o;return-1}function L(e){e&&e.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function M(e){try{if("rtl"===getComputedStyle(e).direction)return"rtl"}catch{}try{const t=e.closest?.("[dir]")?.getAttribute("dir");if("rtl"===t)return"rtl"}catch{}return"ltr"}function P(e){return"rtl"===M(e)}function H(e,t){const i=t.renderer||t.viewRenderer;if(i)return i;if(!t.type)return;const n=e.__frameworkAdapter;if(n?.getTypeDefault){const e=n.getTypeDefault(t.type);if(e?.renderer)return e.renderer}}function I(e,t){if(t.format)return t.format;if(!t.type)return;const i=e.__frameworkAdapter;if(i?.getTypeDefault){const e=i.getTypeDefault(t.type);if(e?.format)return e.format}}const D='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function z(e){return(e.__editingCellCount??0)>0}function O(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing");e.querySelectorAll(".cell.editing").forEach(e=>e.classList.remove("editing"))}const F=document.createElement("template");F.innerHTML='<div class="cell" role="gridcell" part="cell"></div>';const q=document.createElement("template");function N(){return F.content.firstElementChild.cloneNode(!0)}function G(){return q.content.firstElementChild.cloneNode(!0)}function V(e){e.__cellDisplayCache=void 0,e.__cellCacheEpoch=void 0,e.__hasSpecialColumns=void 0}function $(e,t,i,n){const r=t.children,o=e._visibleColumns,s=o.length,l=r.length,a=s<l?s:l,d=e._focusRow,c=e._focusCol,h=e._hasAfterCellRenderHook?.()??!1;let u=e.__hasSpecialColumns;if(void 0===u){u=!1;const t=e.__frameworkAdapter;for(let e=0;e<s;e++){const i=o[e];if(i.__viewTemplate||i.__compiledView||i.renderer||i.viewRenderer||i.externalView||i.format||"date"===i.type||"boolean"===i.type||i.type&&t?.getTypeDefault?.(i.type)?.renderer||i.type&&t?.getTypeDefault?.(i.type)?.format){u=!0;break}}e.__hasSpecialColumns=u}const g=String(n);if(u){for(let s=0;s<a;s++){if(o[s].externalView){if(!r[s].querySelector("[data-external-view]"))return void B(e,t,i,n)}}for(let s=0;s<a;s++){const l=o[s],a=r[s];a.getAttribute("data-row")!==g&&a.setAttribute("data-row",g);const u=a.classList.contains("editing");if(!u){const e=d===n&&c===s;e!==a.classList.contains("cell-focus")&&(a.classList.toggle("cell-focus",e),a.setAttribute("aria-selected",String(e)))}const f=l.cellClass;if(f){const e=a.getAttribute("data-dynamic-classes");e&&e.split(" ").forEach(e=>e&&a.classList.remove(e));try{const e=f(i[l.field],i,l);if(e&&e.length>0){const t=e.filter(e=>e&&"string"==typeof e);t.forEach(e=>a.classList.add(e)),a.setAttribute("data-dynamic-classes",t.join(" "))}else a.removeAttribute("data-dynamic-classes")}catch(p){console.warn(`[tbw-grid] cellClass callback error for column '${l.field}':`,p),a.removeAttribute("data-dynamic-classes")}}if(u)continue;const w=H(e,l);if(w){const r=i[l.field],o=w({row:i,value:r,field:l.field,column:l,cellEl:a});"string"==typeof o?(e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=y(o)):o instanceof Node?o.parentElement!==a&&(e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML="",a.appendChild(o)):null==o&&(e.__frameworkAdapter?.releaseCell?.(a),a.textContent=null==r?"":String(r)),h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:r,cellElement:a,rowElement:t});continue}if(l.__compiledView){const r=i[l.field],o=l.__compiledView({row:i,value:r,field:l.field,column:l});l.__compiledView.__blocked?a.textContent="":(a.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=y(o),E(a)),h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:r,cellElement:a,rowElement:t});continue}if(l.__viewTemplate){const r=i[l.field],o=l.__viewTemplate.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(o)?a.textContent="":(a.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=y(C(o,{row:i,value:r})),E(a)),h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:r,cellElement:a,rowElement:t});continue}if(l.externalView)continue;const m=i[l.field];let b;const v=I(e,l);if(v){try{const e=v(m,i);b=null==e?"":String(e)}catch(p){console.warn(`[tbw-grid] Format error in column '${l.field}':`,p),b=null==m?"":String(m)}a.textContent=b}else"date"===l.type?(b=k(m),a.textContent=b):"boolean"===l.type?a.innerHTML=A(!!m):(b=null==m?"":String(m),a.textContent=b);h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:m,cellElement:a,rowElement:t})}}else for(let f=0;f<a;f++){const s=r[f];if(s.classList.contains("editing"))continue;s.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(s);const l=o[f],a=i[l.field];s.textContent=null==a?"":String(a),s.getAttribute("data-row")!==g&&s.setAttribute("data-row",g);const u=d===n&&c===f;u!==s.classList.contains("cell-focus")&&(s.classList.toggle("cell-focus",u),s.setAttribute("aria-selected",String(u))),h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:f,value:a,cellElement:s,rowElement:t})}}function B(e,t,i,n){t.classList.remove("tbw-row-loading"),t.removeAttribute("aria-busy");const r=e.__frameworkAdapter;if(r?.releaseCell){const e=t.children;for(let t=e.length-1;t>=0;t--)r.releaseCell(e[t])}t.innerHTML="";const o=e._visibleColumns,s=o.length,l=e._focusRow,a=e._focusCol,d=e,c=e._hasAfterCellRenderHook?.()??!1,h=document.createDocumentFragment();for(let g=0;g<s;g++){const r=o[g],s=N();s.setAttribute("aria-colindex",String(g+1)),s.setAttribute("data-col",String(g)),s.setAttribute("data-row",String(n)),s.setAttribute("data-field",r.field),s.setAttribute("data-header",r.header??r.field),r.type&&s.setAttribute("data-type",r.type);let p=i[r.field];const f=I(e,r);if(f)try{p=f(p,i)}catch(u){console.warn(`[tbw-grid] Format error in column '${r.field}':`,u)}const w=r.__compiledView,m=r.__viewTemplate,b=H(e,r),v=r.externalView;let x=!1;if(b){const e=b({row:i,value:p,field:r.field,column:r,cellEl:s});"string"==typeof e?(s.innerHTML=y(e),x=!0):e instanceof Node?e.parentElement!==s&&(s.textContent="",s.appendChild(e)):null==e&&(s.textContent=null==p?"":String(p))}else if(v){const e=v,t=document.createElement("div");t.setAttribute("data-external-view",""),t.setAttribute("data-field",r.field),s.appendChild(t);const n={row:i,value:p,field:r.field,column:r};if(e.mount)try{e.mount({placeholder:t,context:n,spec:e})}catch(u){console.warn(`[tbw-grid] External view mount error for column '${r.field}':`,u)}else queueMicrotask(()=>{try{d.dispatchEvent(new CustomEvent("mount-external-view",{bubbles:!0,composed:!0,detail:{placeholder:t,spec:e,context:n}}))}catch(u){console.warn(`[tbw-grid] External view event dispatch error for column '${r.field}':`,u)}});t.setAttribute("data-mounted","")}else if(w){const e=w({row:i,value:p,field:r.field,column:r}),t=w.__blocked;s.innerHTML=t?"":y(e),x=!0,t&&(s.textContent="",s.setAttribute("data-blocked-template",""))}else if(m){const e=m.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(e)?(s.textContent="",s.setAttribute("data-blocked-template","")):(s.innerHTML=y(C(e,{row:i,value:p})),x=!0)}else f?s.textContent=null==p?"":String(p):"date"===r.type?s.textContent=k(p):"boolean"===r.type?s.innerHTML=A(!!p):s.textContent=null==p?"":String(p);if(x){E(s);const e=s.textContent||"";/Proxy|Reflect\.ownKeys/.test(e)&&(s.textContent=e.replace(/Proxy|Reflect\.ownKeys/g,"").trim(),/Proxy|Reflect\.ownKeys/.test(s.textContent||"")&&(s.textContent=""))}s.hasAttribute("data-blocked-template")&&(s.textContent||"").trim().length&&(s.textContent=""),r.editable?s.tabIndex=0:"boolean"===r.type&&(s.hasAttribute("tabindex")||(s.tabIndex=0)),l===n&&a===g?(s.classList.add("cell-focus"),s.setAttribute("aria-selected","true")):s.setAttribute("aria-selected","false");const R=r.cellClass;if(R)try{const e=R(i[r.field],i,r);if(e&&e.length>0){const t=e.filter(e=>e&&"string"==typeof e);t.forEach(e=>s.classList.add(e)),s.setAttribute("data-dynamic-classes",t.join(" "))}}catch(u){console.warn(`[tbw-grid] cellClass callback error for column '${r.field}':`,u)}c&&e._afterCellRender?.({row:i,rowIndex:n,column:r,colIndex:g,value:p,cellElement:s,rowElement:t}),h.appendChild(s)}t.appendChild(h)}function W(e,t,i){if(t.target?.closest(".resize-handle"))return;const n=T(i.querySelector(".cell[data-row]"));if(n<0)return;const r=e._rows[n];if(!r)return;if(e._dispatchRowClick?.(t,n,r,i))return;const o=t.target?.closest(".cell[data-col]");if(o){const i=Number(o.getAttribute("data-col"));if(!isNaN(i)){if(e._dispatchCellClick?.(t,n,i,o))return;const r=e._focusRow!==n||e._focusCol!==i;if(e._focusRow=n,e._focusCol=i,o.classList.contains("editing")){r&&(L(e._bodyEl??e),o.classList.add("cell-focus"));const t=o.querySelector(D);try{t?.focus({preventScroll:!0})}catch{}return}K(e)}}}function K(e,t){if(e._virtualization?.enabled){const{rowHeight:t,container:i,viewportEl:n}=e._virtualization,r=i,o=n?.clientHeight??r?.clientHeight??0;if(r&&o>0){const i=e._focusRow*t;i<r.scrollTop?r.scrollTop=i:i+t>r.scrollTop+o&&(r.scrollTop=i-o+t)}}const i=void 0!==e._activeEditRows&&-1!==e._activeEditRows;i||e.refreshVirtualWindow(!1),L(e._bodyEl),Array.from(e._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(e=>{e.setAttribute("aria-selected","false")});const n=e._focusRow,r=e._virtualization.start??0,o=e._virtualization.end??e._rows.length;if(n>=r&&n<o){const o=e._bodyEl.querySelectorAll(".data-grid-row")[n-r];let s=o?.children[e._focusCol];if(s&&s.classList?.contains("cell")||(s=o?.querySelector(`.cell[data-col="${e._focusCol}"]`)??o?.querySelector(".cell[data-col]")),s){s.classList.add("cell-focus"),s.setAttribute("aria-selected","true");const n=e.querySelector(".tbw-scroll-area");if(n&&s&&(!i||t?.forceHorizontalScroll))if(t?.forceScrollLeft)n.scrollLeft=0;else if(t?.forceScrollRight)n.scrollLeft=n.scrollWidth-n.clientWidth;else{const t=e._getHorizontalScrollOffsets?.(o??void 0,s)??{left:0,right:0};if(!t.skipScroll){const e=s.getBoundingClientRect(),i=n.getBoundingClientRect(),r=e.left-i.left+n.scrollLeft,o=r+e.width,l=n.scrollLeft+t.left,a=n.scrollLeft+n.clientWidth-t.right;r<l?n.scrollLeft=r-t.left:o>a&&(n.scrollLeft=o-n.clientWidth+t.right)}}if(i&&s.classList.contains("editing")){const e=s.querySelector(D);if(e&&document.activeElement!==e)try{e.focus({preventScroll:!0})}catch{}}else if(i&&!s.contains(document.activeElement)){s.hasAttribute("tabindex")||s.setAttribute("tabindex","-1");try{s.focus({preventScroll:!0})}catch{}}else if(!i){const t=e;document.activeElement!==t&&t.focus({preventScroll:!0})}}}}q.innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const U=new WeakMap;function j(e,t){const i=T(t),n=function(e){if(!e)return-1;const t=e.getAttribute("data-col");return t?parseInt(t,10):-1}(t);if(i<0||n<0)return;e._focusRow=i,e._focusCol=n,L(e._bodyEl),t.classList.add("cell-focus"),t.setAttribute("aria-selected","true");const r=t.closest("tbw-grid");r&&document.activeElement!==r&&r.focus({preventScroll:!0})}function Y(e,t,i,n){let r=null;const o=i.composedPath?.();if(r=o&&o.length>0?o[0]:i.target,r&&!t.contains(r)){const e=document.elementFromPoint(i.clientX,i.clientY);e&&(r=e)}const s=r?.closest?.("[data-col]"),l=r?.closest?.(".data-grid-row"),a=r?.closest?.(".header-row");let d,c,h,u,g,p;return s&&(d=parseInt(s.getAttribute("data-row")??"-1",10),c=parseInt(s.getAttribute("data-col")??"-1",10),d>=0&&c>=0&&(h=e._rows[d],p=e._visibleColumns[c],u=p?.field,g=h&&u?h[u]:void 0)),{type:n,row:h,rowIndex:void 0!==d&&d>=0?d:void 0,colIndex:void 0!==c&&c>=0?c:void 0,field:u,value:g,column:p,originalEvent:i,cellElement:s??void 0,rowElement:l??void 0,isHeader:!!a,cell:void 0!==d&&void 0!==c&&d>=0&&c>=0?{row:d,col:c}:void 0}}function X(e,t,i,n){t.addEventListener("keydown",t=>function(e,t){if(e._dispatchKeyDown?.(t))return;const i=e._rows.length-1,n=e._visibleColumns.length-1,r=void 0!==e._activeEditRows&&-1!==e._activeEditRows,o=e._visibleColumns[e._focusCol],s=o?.type,l=t.composedPath?.()??[],a=l.length?l[0]:t.target,d=e=>{if(!e)return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t||!!e.isContentEditable};if((!d(a)||"Home"!==t.key&&"End"!==t.key)&&!(d(a)&&("ArrowUp"===t.key||"ArrowDown"===t.key)&&"INPUT"===a.tagName&&"number"===a.type||d(a)&&("ArrowLeft"===t.key||"ArrowRight"===t.key)||d(a)&&("Enter"===t.key||"Escape"===t.key)||r&&"select"===s&&("ArrowDown"===t.key||"ArrowUp"===t.key))){switch(t.key){case"Tab":return t.preventDefault(),t.shiftKey?e._focusCol>0?e._focusCol-=1:e._focusRow>0&&("function"==typeof e.commitActiveRowEdit&&e._activeEditRows===e._focusRow&&e.commitActiveRowEdit(),e._focusRow-=1,e._focusCol=n):e._focusCol<n?e._focusCol+=1:("function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow<i&&(e._focusRow+=1,e._focusCol=0)),void K(e);case"ArrowDown":r&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=Math.min(i,e._focusRow+1),t.preventDefault();break;case"ArrowUp":r&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=Math.max(0,e._focusRow-1),t.preventDefault();break;case"ArrowRight":{const i=P(e);e._focusCol=i?Math.max(0,e._focusCol-1):Math.min(n,e._focusCol+1),t.preventDefault();break}case"ArrowLeft":{const i=P(e);e._focusCol=i?Math.min(n,e._focusCol+1):Math.max(0,e._focusCol-1),t.preventDefault();break}case"Home":return t.ctrlKey||t.metaKey?(r&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=0,e._focusCol=0):e._focusCol=0,t.preventDefault(),void K(e,{forceScrollLeft:!0});case"End":return t.ctrlKey||t.metaKey?(r&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=i,e._focusCol=n):e._focusCol=n,t.preventDefault(),void K(e,{forceScrollRight:!0});case"PageDown":e._focusRow=Math.min(i,e._focusRow+20),t.preventDefault();break;case"PageUp":e._focusRow=Math.max(0,e._focusRow-20),t.preventDefault();break;case"Enter":{const i=e._focusRow,n=e._focusCol,r=e._visibleColumns[n],o=e._rows[i],s=r?.field??"",l=s&&o?o[s]:void 0,a=e.querySelector(`[data-row="${i}"][data-col="${n}"]`),d=new CustomEvent("cell-activate",{cancelable:!0,detail:{rowIndex:i,colIndex:n,column:r,field:s,value:l,row:o,cellEl:a,trigger:"keyboard",originalEvent:t}});e.dispatchEvent(d);const c=new CustomEvent("activate-cell",{cancelable:!0,detail:{row:i,col:n}});if(e.dispatchEvent(c),d.defaultPrevented||c.defaultPrevented)return void t.preventDefault();break}default:return}K(e)}}(e,t),{signal:n}),i.addEventListener("mousedown",t=>function(e,t,i){const n=Y(e,t,i,"mousedown");e._dispatchCellMouseDown?.(n)&&U.set(e,!0)}(e,i,t),{signal:n}),document.addEventListener("mousemove",t=>function(e,t,i){if(!U.get(e))return;const n=Y(e,t,i,"mousemove");e._dispatchCellMouseMove?.(n)}(e,i,t),{signal:n}),document.addEventListener("mouseup",t=>function(e,t,i){if(!U.get(e))return;const n=Y(e,t,i,"mouseup");e._dispatchCellMouseUp?.(n),U.set(e,!1)}(e,i,t),{signal:n})}function Z(e,t){return null==e&&null==t?0:null==e?-1:null==t||e>t?1:e<t?-1:0}function Q(e,t,i){const n=i.find(e=>e.field===t.field),r=n?.sortComparator??Z,{field:o,direction:s}=t;return[...e].sort((e,t)=>r(e[o],t[o],e,t)*s)}function J(e,t,i,n){e._rows=t,e.__rowRenderEpoch++,e._rowPool.forEach(e=>e.__epoch=-1),le(e),e.refreshVirtualWindow(!0),e.dispatchEvent(new CustomEvent("sort-change",{detail:{field:i.field,direction:n}})),e.requestStateChange?.()}function ee(e,t){if(e._sortState&&e._sortState.field===t.field)if(1===e._sortState.direction)te(e,t,-1);else{e._sortState=null,e.__rowRenderEpoch++,e._rowPool.forEach(e=>e.__epoch=-1),e._rows=e.__originalOrder.slice(),le(e);const i=e._headerRowEl?.querySelectorAll('[role="columnheader"].sortable');i?.forEach(t=>{t.getAttribute("aria-sort")&&("ascending"!==t.getAttribute("aria-sort")&&"descending"!==t.getAttribute("aria-sort")||e._sortState)||t.setAttribute("aria-sort","none")}),e.refreshVirtualWindow(!0),e.dispatchEvent(new CustomEvent("sort-change",{detail:{field:t.field,direction:0}})),e.requestStateChange?.()}else e._sortState||(e.__originalOrder=e._rows.slice()),te(e,t,1)}function te(e,t,i){e._sortState={field:t.field,direction:i};const n={field:t.field,direction:i},r=e._columns,o=(e.effectiveConfig?.sortHandler??Q)(e._rows,n,r);o&&"function"==typeof o.then?o.then(n=>{J(e,n,t,i)}):J(e,o,t,i)}function ie(e,t){return!1!==e.effectiveConfig?.sortable&&!0===t.sortable}function ne(e,t){return!1!==e.effectiveConfig?.resizable&&!1!==t.resizable}function re(e,t){const i=document.createElement("span");s(i,"sort-indicator");const n=e._sortState?.field===t.field?e._sortState.direction:0,o={...r,...e.icons};return function(e,t){"string"==typeof t?e.textContent=t:t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}(i,1===n?o.sortAsc:-1===n?o.sortDesc:o.sortNone),i}function oe(e,t,i){const n=document.createElement("div");return n.className="resize-handle",n.setAttribute("aria-hidden","true"),n.addEventListener("mousedown",n=>{n.stopPropagation(),n.preventDefault(),e._resizeController.start(n,t,i)}),n.addEventListener("dblclick",i=>{i.stopPropagation(),i.preventDefault(),e._resizeController.resetColumn(t)}),n}function se(e,t,i,n){n.classList.add("sortable"),n.tabIndex=0;const r=e._sortState?.field===t.field?e._sortState.direction:0;n.setAttribute("aria-sort",0===r?"none":1===r?"ascending":"descending"),n.addEventListener("click",i=>{e._resizeController?.isResizing||e._dispatchHeaderClick?.(i,t,n)||ee(e,t)}),n.addEventListener("keydown",i=>{if("Enter"===i.key||" "===i.key){if(i.preventDefault(),e._dispatchHeaderClick?.(i,t,n))return;ee(e,t)}})}function le(e){e._headerRowEl=e.findHeaderRow();const t=e._headerRowEl;t&&(t.innerHTML="",e._visibleColumns.forEach((i,n)=>{const r=document.createElement("div");r.className="cell",s(r,"header-cell"),r.setAttribute("role","columnheader"),r.setAttribute("aria-colindex",String(n+1)),r.setAttribute("data-field",i.field),r.setAttribute("data-col",String(n)),i.type&&r.setAttribute("data-type",i.type);const o=i.header??i.field,l=e._sortState?.field===i.field?e._sortState.direction:0,a=1===l?"asc":-1===l?"desc":null;if(i.headerRenderer){const t={column:i,value:o,sortState:a,filterActive:!1,cellEl:r,renderSortIcon:()=>ie(e,i)?re(e,i):null,renderFilterButton:()=>null},s=i.headerRenderer(t);!function(e,t){if(null!=t)if("string"==typeof t){const i=document.createElement("span");for(i.innerHTML=y(t);i.firstChild;)e.appendChild(i.firstChild)}else t instanceof Node&&e.appendChild(t)}(r,s),ie(e,i)&&se(e,i,0,r),ne(e,i)&&(r.classList.add("resizable"),r.appendChild(oe(e,n,r)))}else if(i.headerLabelRenderer){const t={column:i,value:o},s=i.headerLabelRenderer(t),l=document.createElement("span");null==s?l.textContent=o:"string"==typeof s?l.innerHTML=y(s):s instanceof Node&&l.appendChild(s),r.appendChild(l),ie(e,i)&&(se(e,i,0,r),r.appendChild(re(e,i))),ne(e,i)&&(r.classList.add("resizable"),r.appendChild(oe(e,n,r)))}else if(i.__headerTemplate)Array.from(i.__headerTemplate.childNodes).forEach(e=>r.appendChild(e.cloneNode(!0))),ie(e,i)&&(se(e,i,0,r),r.appendChild(re(e,i))),ne(e,i)&&(r.classList.add("resizable"),r.appendChild(oe(e,n,r)));else{const t=document.createElement("span");t.textContent=o,r.appendChild(t),ie(e,i)&&(se(e,i,0,r),r.appendChild(re(e,i))),ne(e,i)&&(r.classList.add("resizable"),r.appendChild(oe(e,n,r)))}t.appendChild(r)}),t.querySelectorAll(".cell.sortable").forEach(e=>{e.getAttribute("aria-sort")||e.setAttribute("aria-sort","none")}),t.children.length>0?(t.setAttribute("role","row"),t.setAttribute("aria-rowindex","1")):(t.removeAttribute("role"),t.removeAttribute("aria-rowindex")))}const ae="function"==typeof requestIdleCallback;function de(e){ae?cancelIdleCallback(e):clearTimeout(e)}function ce(e,t){if(t){const i=t({size:e});if("string"==typeof i){const e=document.createElement("div");return e.innerHTML=i,e}return i}return function(e){const t=document.createElement("div");return t.className=`tbw-spinner tbw-spinner--${e}`,t.setAttribute("role","progressbar"),t.setAttribute("aria-label","Loading"),t}(e)}var he=(e=>(e[e.STYLE=1]="STYLE",e[e.VIRTUALIZATION=2]="VIRTUALIZATION",e[e.HEADER=3]="HEADER",e[e.ROWS=4]="ROWS",e[e.COLUMNS=5]="COLUMNS",e[e.FULL=6]="FULL",e))(he||{});class ue{#u;#C=0;#x=0;#E=null;#R=null;#S=null;#_=!1;constructor(e){this.#u=e}requestPhase(e,t){e>this.#C&&(this.#C=e),0===this.#x&&(this.#A(),this.#x=requestAnimationFrame(()=>this.#k()))}whenReady(){return this.#E?this.#E:Promise.resolve()}setInitialReadyResolver(e){this.#S=e}cancel(){0!==this.#x&&(cancelAnimationFrame(this.#x),this.#x=0),this.#C=0,this.#R&&(this.#R(),this.#R=null,this.#E=null)}get isPending(){return 0!==this.#C}get pendingPhase(){return this.#C}#A(){this.#E||(this.#E=new Promise(e=>{this.#R=e}))}#k(){if(this.#x=0,!this.#u.isConnected())return this.#C=0,void(this.#R&&(this.#R(),this.#R=null,this.#E=null));const e=this.#C;this.#C=0,e>=5&&this.#u.mergeConfig(),e>=4&&this.#u.processRows(),e>=5&&(this.#u.processColumns(),this.#u.updateTemplate()),e>=3&&this.#u.renderHeader(),e>=2&&this.#u.renderVirtualWindow(),e>=1&&this.#u.afterRender(),!this.#_&&this.#S&&(this.#_=!0,this.#S()),this.#R&&(this.#R(),this.#R=null,this.#E=null)}}function ge(e){let t=null,i=null,n=null,r=null;const o=n=>{if(!t)return;const r=n.clientX-t.startX,o=Math.max(40,t.startWidth+r),s=e._visibleColumns[t.colIndex];s.width=o,s.__userResized=!0,s.__renderedWidth=o,null==i&&(i=requestAnimationFrame(()=>{i=null,e.updateTemplate?.()})),e.dispatchEvent(new CustomEvent("column-resize",{detail:{field:s.field,width:o}}))};let s=!1;const l=()=>{const i=null!==t;i&&(s=!0,requestAnimationFrame(()=>{s=!1})),window.removeEventListener("mousemove",o),window.removeEventListener("mouseup",l),null!==n&&(document.documentElement.style.cursor=n,n=null),null!==r&&(document.body.style.userSelect=r,r=null),t=null,i&&e.requestStateChange&&e.requestStateChange()};return{get isResizing(){return null!==t||s},start(i,s,a){i.preventDefault();const d=e._visibleColumns[s],c="number"==typeof d?.width?d.width:void 0,h=d?.__renderedWidth??c??a.getBoundingClientRect().width;t={startX:i.clientX,colIndex:s,startWidth:h},window.addEventListener("mousemove",o),window.addEventListener("mouseup",l),null===n&&(n=document.documentElement.style.cursor),document.documentElement.style.cursor="e-resize",null===r&&(r=document.body.style.userSelect),document.body.style.userSelect="none"},resetColumn(t){const i=e._visibleColumns[t];i&&(i.__userResized=!1,i.__renderedWidth=void 0,i.width=i.__originalWidth,e.updateTemplate?.(),e.requestStateChange?.(),e.dispatchEvent(new CustomEvent("column-resize-reset",{detail:{field:i.field,width:i.width}})))},dispose(){l()}}}const pe="data-animating",fe={change:"--tbw-row-change-duration",insert:"--tbw-row-insert-duration",remove:"--tbw-row-remove-duration"},we={change:500,insert:300,remove:200};function me(e,t){const i=fe[t],n=getComputedStyle(e).getPropertyValue(i);if(n){const e=function(e){const t=e.trim().toLowerCase();return t.endsWith("ms")?parseFloat(t):t.endsWith("s")?1e3*parseFloat(t):parseFloat(t)}(n);if(!isNaN(e)&&e>0)return e}return we[t]}function be(e,t,i){if(t<0)return Promise.resolve(!1);const n=e.findRenderedRowElement?.(t);return n?new Promise(e=>{!function(e,t,i){e.removeAttribute(pe),e.offsetWidth,e.setAttribute(pe,t);const n=me(e,t);setTimeout(()=>{"remove"!==t&&e.removeAttribute(pe),i?.()},n)}(n,i,()=>e(!0))}):Promise.resolve(!1)}function ve(e,t,i){const n=document.createElement(e);if(t)for(const r in t){const e=t[r];null!=e&&n.setAttribute(r,e)}return n}function ye(e,t){const i=document.createElement("div");if(e&&(i.className=e),t)for(const n in t){const e=t[n];null!=e&&i.setAttribute(n,e)}return i}function Ce(e,t,i){const n=document.createElement("button");if(e&&(n.className=e),t)for(const r in t){const e=t[r];null!=e&&n.setAttribute(r,e)}return n}const xe=document.createElement("template");function Ee(){return xe.content.cloneNode(!0)}function Re(e){const t=document.createDocumentFragment(),i=ye(e.hasShell?"tbw-grid-root has-shell":"tbw-grid-root");if(e.hasShell&&e.shellHeader&&e.shellBody)i.appendChild(e.shellHeader),i.appendChild(e.shellBody);else{const e=ye("tbw-grid-content");e.appendChild(Ee()),i.appendChild(e)}return t.appendChild(i),t}function Se(e){return e?"string"==typeof e?e:e.outerHTML:""}function _e(e){return!!e?.header?.title||(!!e?.header?.toolbarContents?.length||(!!e?.toolPanels?.length||(!!e?.headerContents?.length||(!!e?.header?.lightDomContent?.length||!!e?.header?.hasToolButtonsContainer))))}function Ae(e,t){const i=e.querySelector("tbw-grid-header");if(!i)return;if(!t.lightDomTitle){const e=i.getAttribute("title");e&&(t.lightDomTitle=e)}const n=i.querySelectorAll("tbw-grid-header-content");n.length>0&&0===t.lightDomHeaderContent.length&&(t.lightDomHeaderContent=Array.from(n)),i.style.display="none"}function ke(e,t,i){const n=e.querySelector(":scope > tbw-grid-tool-buttons");if(!n)return;t.hasToolButtonsContainer=!0;const r="light-dom-toolbar-content";if(t.lightDomToolbarContentIds.has(r))return;const o={id:r,order:0,render:e=>{for(;n.firstChild;)e.appendChild(n.firstChild);return()=>{for(;e.firstChild;)n.appendChild(e.firstChild)}}};t.toolbarContents.set(r,o),t.lightDomToolbarContentIds.add(r),n.style.display="none"}function Te(e,t,i){e.querySelectorAll(":scope > tbw-grid-tool-panel").forEach(e=>{const n=e,r=n.getAttribute("id"),o=n.getAttribute("title");if(!r||!o)return void console.warn(`[parseLightDomToolPanels] Tool panel missing required id or title attribute: id="${r??""}", title="${o??""}"`);const s=n.getAttribute("icon")??void 0,l=n.getAttribute("tooltip")??void 0,a=parseInt(n.getAttribute("order")??"100",10);let d;const c=i?.(n);if(c)d=c;else{const e=n.innerHTML.trim();d=t=>{const i=document.createElement("div");return i.innerHTML=e,t.appendChild(i),()=>i.remove()}}const h=t.toolPanels.get(r);if(h){if(c){h.render=d,h.order=a,h.icon=s,h.tooltip=l;const e=t.panelCleanups.get(r);e&&(e(),t.panelCleanups.delete(r))}return}const u={id:r,title:o,icon:s,tooltip:l,order:a,render:d};t.toolPanels.set(r,u),t.lightDomToolPanelIds.add(r),n.style.display="none"})}function Le(e,t,i){const n=t?.header?.toolbarContents??[],r=[...i.toolbarContents.values()],o=new Set(n.map(e=>e.id)),s=[...n];for(const l of r)o.has(l.id)||s.push(l);for(const l of s){if(i.toolbarContentCleanups.has(l.id))continue;if(!l.render)continue;const t=e.querySelector(`[data-toolbar-content="${l.id}"]`);if(!t)continue;const n=l.render(t);n&&i.toolbarContentCleanups.set(l.id,n)}}function Me(e,t){const i=t.lightDomHeaderContent.length>0&&!t.lightDomContentMoved,n=t.headerContents.size>0;if(!i&&!n)return;const r=e.querySelector(".tbw-shell-content");if(!r)return;if(i){for(const e of t.lightDomHeaderContent)e.style.display="",r.appendChild(e);t.lightDomContentMoved=!0}const o=[...t.headerContents.values()].sort((e,t)=>(e.order??100)-(t.order??100));for(const s of o){const e=t.headerContentCleanups.get(s.id);e&&(e(),t.headerContentCleanups.delete(s.id));let i=r.querySelector(`[data-header-content="${s.id}"]`);i||(i=document.createElement("div"),i.setAttribute("data-header-content",s.id),r.appendChild(i));const n=s.render(i);n&&t.headerContentCleanups.set(s.id,n)}}function Pe(e,t){const i=e.querySelector("[data-panel-toggle]");i&&(i.classList.toggle("active",t.isPanelOpen),i.setAttribute("aria-pressed",String(t.isPanelOpen)))}function He(e,t){const i=e.querySelector(".tbw-tool-panel");i&&(i.classList.toggle("open",t.isPanelOpen),t.isPanelOpen||(i.style.width=""))}function Ie(e){for(const t of e.toolbarContentCleanups.values())t();e.toolbarContentCleanups.clear()}function De(e,t){let i=!1;const n={get isInitialized(){return i},setInitialized(e){i=e},get isPanelOpen(){return e.isPanelOpen},get activePanel(){return e.isPanelOpen&&e.expandedSections.size>0?[...e.expandedSections][0]:null},get expandedSections(){return[...e.expandedSections]},openToolPanel(){if(e.isPanelOpen)return;if(0===e.toolPanels.size)return void console.warn("[tbw-grid] No tool panels registered");if(e.isPanelOpen=!0,0===e.expandedSections.size&&e.toolPanels.size>0){const t=[...e.toolPanels.values()].sort((e,t)=>(e.order??100)-(t.order??100))[0];t&&e.expandedSections.add(t.id)}const i=t.getShadow();Pe(i,e),He(i,e),function(e,t,i){if(!t.isPanelOpen)return;const n=Se(i?.expand??r.expand),o=Se(i?.collapse??r.collapse);for(const[r,s]of t.toolPanels){const i=t.expandedSections.has(r),l=e.querySelector(`[data-section="${r}"]`),a=l?.querySelector(".tbw-accordion-content");if(!l||!a)continue;l.classList.toggle("expanded",i);const d=l.querySelector(".tbw-accordion-header");d&&d.setAttribute("aria-expanded",String(i));const c=l.querySelector(".tbw-accordion-chevron");if(c&&(c.innerHTML=i?o:n),i){if(0===a.children.length){const e=s.render(a);e&&t.panelCleanups.set(r,e)}}else{const e=t.panelCleanups.get(r);e&&(e(),t.panelCleanups.delete(r)),a.innerHTML=""}}}(i,e,t.getAccordionIcons()),t.emit("tool-panel-open",{sections:n.expandedSections})},closeToolPanel(){if(!e.isPanelOpen)return;for(const t of e.panelCleanups.values())t();e.panelCleanups.clear();for(const t of e.toolPanels.values())t.onClose?.();e.isPanelOpen=!1;const i=t.getShadow();Pe(i,e),He(i,e),t.emit("tool-panel-close",{})},toggleToolPanel(){e.isPanelOpen?n.closeToolPanel():n.openToolPanel()},toggleToolPanelSection(i){const n=e.toolPanels.get(i);if(!n)return void console.warn(`[tbw-grid] Tool panel section "${i}" not found`);if(1===e.toolPanels.size)return;const r=t.getShadow(),o=e.expandedSections.has(i);if(o){const t=e.panelCleanups.get(i);t&&(t(),e.panelCleanups.delete(i)),n.onClose?.(),e.expandedSections.delete(i),ze(r,i,!1)}else{for(const[t,n]of e.toolPanels)if(t!==i&&e.expandedSections.has(t)){const i=e.panelCleanups.get(t);i&&(i(),e.panelCleanups.delete(t)),n.onClose?.(),e.expandedSections.delete(t),ze(r,t,!1);const o=r.querySelector(`[data-section="${t}"] .tbw-accordion-content`);o&&(o.innerHTML="")}e.expandedSections.add(i),ze(r,i,!0),function(e,t,i){const n=t.toolPanels.get(i);if(!n?.render)return;const r=e.querySelector(`[data-section="${i}"] .tbw-accordion-content`);if(!r)return;const o=n.render(r);o&&t.panelCleanups.set(i,o)}(r,e,i)}t.emit("tool-panel-section-toggle",{id:i,expanded:!o})},getToolPanels:()=>[...e.toolPanels.values()],registerToolPanel(n){e.toolPanels.has(n.id)?console.warn(`[tbw-grid] Tool panel "${n.id}" already registered`):(e.toolPanels.set(n.id,n),i&&t.refreshShellHeader())},unregisterToolPanel(n){if(e.expandedSections.has(n)){const t=e.panelCleanups.get(n);t&&(t(),e.panelCleanups.delete(n)),e.expandedSections.delete(n)}e.toolPanels.delete(n),i&&t.refreshShellHeader()},getHeaderContents:()=>[...e.headerContents.values()],registerHeaderContent(n){e.headerContents.has(n.id)?console.warn(`[tbw-grid] Header content "${n.id}" already registered`):(e.headerContents.set(n.id,n),i&&Me(t.getShadow(),e))},unregisterHeaderContent(i){const n=e.headerContentCleanups.get(i);n&&(n(),e.headerContentCleanups.delete(i));const r=e.headerContents.get(i);r?.onDestroy?.(),e.headerContents.delete(i);const o=t.getShadow().querySelector(`[data-header-content="${i}"]`);o?.remove()},getToolbarContents:()=>[...e.toolbarContents.values()].sort((e,t)=>(e.order??0)-(t.order??0)),registerToolbarContent(n){e.toolbarContents.has(n.id)?console.warn(`[tbw-grid] Toolbar content "${n.id}" already registered`):(e.toolbarContents.set(n.id,n),i&&t.refreshShellHeader())},unregisterToolbarContent(n){const r=e.toolbarContentCleanups.get(n);r&&(r(),e.toolbarContentCleanups.delete(n));const o=e.toolbarContents.get(n);o?.onDestroy&&o.onDestroy(),e.toolbarContents.delete(n),i&&t.refreshShellHeader()}};return n}function ze(e,t,i){const n=e.querySelector(`[data-section="${t}"]`);n&&n.classList.toggle("expanded",i)}function Oe(e,t,i,n){const o=_e(t),s=[],l=["tbw-grid-header","tbw-grid-tool-buttons","tbw-grid-tool-panel","tbw-grid-column","tbw-grid-detail","tbw-grid-responsive-card"];for(const r of l){e.querySelectorAll(`:scope > ${r}`).forEach(e=>s.push(e))}e.replaceChildren();for(const r of s)e.appendChild(r);if(o){const o=Se(n?.toolPanel??r.toolPanel),s=Se(n?.expand??r.expand),l=Se(n?.collapse??r.collapse),a=[...t?.header?.toolbarContents??[]].sort((e,t)=>(e.order??0)-(t.order??0)),d=[...t?.toolPanels??[]].sort((e,t)=>(e.order??100)-(t.order??100)),c={title:t?.header?.title??void 0,hasPanels:d.length>0,isPanelOpen:i.isPanelOpen,toolPanelIcon:o,configButtons:a.map(e=>({id:e.id,hasElement:!1,hasRender:!!e.render})),apiButtons:[]},h={position:t?.toolPanel?.position??"right",isPanelOpen:i.isPanelOpen,expandIcon:s,collapseIcon:l,panels:d.map(e=>({id:e.id,title:e.title,icon:Se(e.icon),isExpanded:i.expandedSections.has(e.id)}))},u=Re({hasShell:!0,shellHeader:function(e){const t=ye("tbw-shell-header",{part:"shell-header",role:"presentation"});if(e.title){const i=ye("tbw-shell-title");i.textContent=e.title,t.appendChild(i)}const i=ye("tbw-shell-content",{part:"shell-content",role:"presentation","data-light-dom-header-content":""});t.appendChild(i);const n=ye("tbw-shell-toolbar",{part:"shell-toolbar",role:"presentation"});for(const r of e.configButtons)r.hasRender&&n.appendChild(ye("tbw-toolbar-content-slot",{"data-toolbar-content":r.id}));for(const r of e.apiButtons)r.hasRender&&n.appendChild(ye("tbw-toolbar-content-slot",{"data-toolbar-content":r.id}));if((e.configButtons.some(e=>e.hasRender)||e.apiButtons.some(e=>e.hasRender))&&e.hasPanels&&n.appendChild(ye("tbw-toolbar-separator")),e.hasPanels){const t=Ce(e.isPanelOpen?"tbw-toolbar-btn active":"tbw-toolbar-btn",{"data-panel-toggle":"",title:"Settings","aria-label":"Toggle settings panel","aria-pressed":String(e.isPanelOpen),"aria-controls":"tbw-tool-panel"});t.innerHTML=e.toolPanelIcon,n.appendChild(t)}return t.appendChild(n),t}(c),shellBody:function(e){const t=ye("tbw-shell-body"),i=e.panels.length>0,n=1===e.panels.length,r=ye("tbw-grid-content");r.appendChild(Ee());let o=null;if(i){o=ve("aside",{class:e.isPanelOpen?"tbw-tool-panel open":"tbw-tool-panel",part:"tool-panel","data-position":e.position,role:"presentation",id:"tbw-tool-panel"});const t="left"===e.position?"right":"left";o.appendChild(ye("tbw-tool-panel-resize",{"data-resize-handle":"","data-handle-position":t,"aria-hidden":"true"}));const i=ye("tbw-tool-panel-content",{role:"presentation"}),r=ye("tbw-accordion");for(const o of e.panels){const t=ye(`tbw-accordion-section${o.isExpanded?" expanded":""}${n?" single":""}`,{"data-section":o.id}),i=Ce("tbw-accordion-header",{"aria-expanded":String(o.isExpanded),"aria-controls":`tbw-section-${o.id}`});if(n&&i.setAttribute("aria-disabled","true"),o.icon){const e=ve("span",{class:"tbw-accordion-icon"});e.innerHTML=o.icon,i.appendChild(e)}const s=ve("span",{class:"tbw-accordion-title"});if(s.textContent=o.title,i.appendChild(s),!n){const t=ve("span",{class:"tbw-accordion-chevron"});t.innerHTML=o.isExpanded?e.collapseIcon:e.expandIcon,i.appendChild(t)}t.appendChild(i),t.appendChild(ye("tbw-accordion-content",{id:`tbw-section-${o.id}`,role:"presentation"})),r.appendChild(t)}i.appendChild(r),o.appendChild(i)}return"left"===e.position&&o?(t.appendChild(o),t.appendChild(r)):(t.appendChild(r),o&&t.appendChild(o)),t}(h)});e.appendChild(u)}else{const t=Re({hasShell:!1});e.appendChild(t)}return o}xe.innerHTML='\n <div class="tbw-scroll-area">\n <div class="rows-body-wrapper">\n <div class="rows-body" role="grid">\n <div class="header" role="rowgroup">\n <div class="header-row" role="row" part="header-row"></div>\n </div>\n <div class="rows-container" role="presentation">\n <div class="rows-viewport" role="presentation">\n <div class="rows"></div>\n </div>\n </div>\n </div>\n </div>\n </div>\n <div class="faux-vscroll">\n <div class="faux-vscroll-spacer"></div>\n </div>\n';const Fe="tbw-grid-styles";let qe="";const Ne=new Map;function Ge(){const e=function(){let e=document.getElementById(Fe);return e||(e=document.createElement("style"),e.id=Fe,e.setAttribute("data-tbw-grid","true"),document.head.appendChild(e)),e}(),t=Array.from(Ne.values()).join("\n");e.textContent=`${qe}\n\n/* Plugin Styles */\n${t}`}async function Ve(e){if(qe)return;if("string"==typeof e&&e.length>0)return qe=e,void Ge();await new Promise(e=>setTimeout(e,50));const t=function(){try{for(const e of Array.from(document.styleSheets))try{const t=Array.from(e.cssRules||[]).map(e=>e.cssText).join("\n");if(t.includes(".tbw-grid-root")&&t.includes("tbw-grid"))return t}catch{continue}}catch(e){console.warn("[tbw-grid] Failed to extract grid.css from document stylesheets:",e)}return null}();t?(qe=t,Ge()):"undefined"!=typeof process&&"test"===process.env?.NODE_ENV||console.warn("[tbw-grid] Could not find grid.css in document.styleSheets. Grid styling will not work.","Available stylesheets:",Array.from(document.styleSheets).map(e=>e.href||"(inline)"))}function $e(e){e.momentumRaf&&(cancelAnimationFrame(e.momentumRaf),e.momentumRaf=0)}function Be(e,t){(Math.abs(e.velocityY)>.1||Math.abs(e.velocityX)>.1)&&function(e,t){const i=.95,n=.01,r=()=>{e.velocityY*=i,e.velocityX*=i;const o=16*e.velocityY,s=16*e.velocityX;Math.abs(e.velocityY)>n&&(t.fauxScrollbar.scrollTop+=o),Math.abs(e.velocityX)>n&&t.scrollArea&&(t.scrollArea.scrollLeft+=s),Math.abs(e.velocityY)>n||Math.abs(e.velocityX)>n?e.momentumRaf=requestAnimationFrame(r):e.momentumRaf=0};e.momentumRaf=requestAnimationFrame(r)}(e,t),function(e){e.startY=null,e.startX=null,e.scrollTop=null,e.scrollLeft=null,e.lastY=null,e.lastX=null,e.lastTime=null}(e)}function We(e,t,i,n){e.addEventListener("touchstart",e=>function(e,t,i){if(1!==e.touches.length)return;$e(t);const n=e.touches[0];t.startY=n.clientY,t.startX=n.clientX,t.lastY=n.clientY,t.lastX=n.clientX,t.lastTime=performance.now(),t.scrollTop=i.fauxScrollbar.scrollTop,t.scrollLeft=i.scrollArea?.scrollLeft??0,t.velocityY=0,t.velocityX=0}(e,t,i),{passive:!0,signal:n}),e.addEventListener("touchmove",e=>{const n=function(e,t,i){if(1!==e.touches.length||null===t.startY||null===t.startX||null===t.scrollTop||null===t.scrollLeft)return!1;const n=e.touches[0],r=n.clientY,o=n.clientX,s=performance.now(),l=t.startY-r,a=t.startX-o;if(null!==t.lastTime&&null!==t.lastY&&null!==t.lastX){const e=s-t.lastTime;e>0&&(t.velocityY=(t.lastY-r)/e,t.velocityX=(t.lastX-o)/e)}t.lastY=r,t.lastX=o,t.lastTime=s;const{scrollTop:d,scrollHeight:c,clientHeight:h}=i.fauxScrollbar,u=l>0&&d<c-h||l<0&&d>0;let g=!1;if(i.scrollArea){const{scrollLeft:e,scrollWidth:t,clientWidth:n}=i.scrollArea;g=a>0&&e<t-n||a<0&&e>0}return u&&(i.fauxScrollbar.scrollTop=t.scrollTop+l),g&&i.scrollArea&&(i.scrollArea.scrollLeft=t.scrollLeft+a),u||g}(e,t,i);n&&e.preventDefault()},{passive:!1,signal:n}),e.addEventListener("touchend",()=>Be(t,i),{passive:!0,signal:n})}const Ke=[{property:"editable",pluginName:"editing",level:"column",description:'the "editable" column property',isUsed:e=>!0===e},{property:"editor",pluginName:"editing",level:"column",description:'the "editor" column property'},{property:"editorParams",pluginName:"editing",level:"column",description:'the "editorParams" column property'},{property:"group",pluginName:"groupingColumns",level:"column",description:'the "group" column property'},{property:"pinned",pluginName:"pinnedColumns",level:"column",description:'the "pinned" column property',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e},{property:"sticky",pluginName:"pinnedColumns",level:"column",description:'the "sticky" column property (deprecated, use "pinned")',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e}],Ue=[{property:"columnGroups",pluginName:"groupingColumns",level:"config",description:'the "columnGroups" config property',isUsed:e=>Array.isArray(e)&&e.length>0}];function je(e){return`import { ${Ye(e)}Plugin } from '@toolbox-web/grid/plugins/${t=e,t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}';`;var t}function Ye(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Xe(e,t){return e.some(e=>e.name===t)}function Ze(e,t){return e&&"object"==typeof e?"__rowCacheKey"in e?e.__rowCacheKey:"rowId"in e&&null!=e.rowId?`id:${e.rowId}`:t?`id:${t(e)}`:e:e}function Qe(e,t,i){const n=Ze(t,i);return"string"==typeof n?e.byKey.get(n):n&&"object"==typeof n?e.byRef.get(n):void 0}function Je(e,t,i){if(t<0||t>=e.length)return;const n=e[t],r=i-n.height;if(0!==r){n.height=i,n.measured=!0;for(let i=t+1;i<e.length;i++)e[i].offset+=r}}function et(e,t){if(0===e.length)return-1;if(t<=0)return 0;let i=0,n=e.length-1;for(;i<=n;){const r=Math.floor((i+n)/2),o=e[r],s=o.offset+o.height;if(t<o.offset)n=r-1;else{if(!(t>=s))return r;i=r+1}}return Math.max(0,Math.min(i,e.length-1))}function tt(e,t){const{positionCache:i,heightCache:n,rows:r,start:o,end:s,getPluginHeight:l,getRowId:a}=e;let d=!1;t.forEach(e=>{const t=e.dataset.rowIndex;if(!t)return;const c=parseInt(t,10);if(c<o||c>=s||c>=r.length)return;const h=r[c],u=l?.(h,c);if(void 0!==u){const e=i[c];return void((!e.measured||Math.abs(e.height-u)>1)&&(Je(i,c,u),d=!0))}const g=e.offsetHeight;if(g>0){const e=i[c];(!e.measured||Math.abs(e.height-g)>1)&&(Je(i,c,g),function(e,t,i,n){const r=Ze(t,n);"string"==typeof r?e.byKey.set(r,i):r&&"object"==typeof r&&e.byRef.set(r,i)}(n,h,g,a),d=!0)}});const c=d?function(e){let t=0;for(const i of e)i.measured&&t++;return t}(i):0,h=d?function(e,t){let i=0,n=0;for(const r of e)r.measured&&(i+=r.height,n++);return n>0?i/n:t}(i,e.defaultHeight):0;return{hasChanges:d,measuredCount:c,averageHeight:h}}class it{constructor(e){this.grid=e}plugins=[];getPlugins(){return this.plugins}pluginMap=new Map;cellRenderers=new Map;headerRenderers=new Map;cellEditors=new Map;eventListeners=new Map;queryHandlers=new Map;static deprecationWarned=new WeakSet;attachAll(e){for(const t of e)this.attach(t)}attach(e){if(function(e,t){const i=e.name,n=e.constructor.dependencies??[];for(const r of n){const e=r.name,n=r.required??!0,o=r.reason;if(!t.some(t=>t.name===e)){const t=o??`${Ye(i)}Plugin requires ${Ye(e)}Plugin`,r=je(e);if(n)throw new Error(`[tbw-grid] Plugin dependency error:\n\n${t}.\n\n → Add the plugin to your gridConfig.plugins array BEFORE ${Ye(i)}Plugin:\n ${r}\n plugins: [new ${Ye(e)}Plugin(), new ${Ye(i)}Plugin()]`);console.info(`[tbw-grid] ${Ye(i)}Plugin: Optional "${e}" plugin not found. Some features may be unavailable.`)}}}(e,this.plugins),this.pluginMap.set(e.constructor,e),this.plugins.push(e),e.cellRenderers)for(const[t,i]of Object.entries(e.cellRenderers))this.cellRenderers.set(t,i);if(e.headerRenderers)for(const[t,i]of Object.entries(e.headerRenderers))this.headerRenderers.set(t,i);if(e.cellEditors)for(const[t,i]of Object.entries(e.cellEditors))this.cellEditors.set(t,i);this.registerQueryHandlers(e),this.warnDeprecatedHooks(e),e.attach(this.grid);for(const t of this.plugins)t!==e&&t.onPluginAttached&&t.onPluginAttached(e.name,e)}registerQueryHandlers(e){const t=e.constructor.manifest;if(t?.queries)for(const i of t.queries){let t=this.queryHandlers.get(i.type);t||(t=new Set,this.queryHandlers.set(i.type,t)),t.add(e)}}warnDeprecatedHooks(e){const t=e.constructor;if(it.deprecationWarned.has(t))return;if(!_())return;const i="function"==typeof e.getExtraHeight||"function"==typeof e.getExtraHeightBefore,n="function"==typeof e.getRowHeight;i&&!n&&(it.deprecationWarned.add(t),console.warn(`[tbw-grid] Deprecation warning: "${e.name}" uses getExtraHeight() / getExtraHeightBefore() which are deprecated and will be removed in v3.0.\n → Migrate to getRowHeight(row, index) for better variable row height support.\n → See: https://toolbox-web.dev/docs/grid/plugins/migration#row-height-hooks`))}unregisterQueryHandlers(e){for(const[t,i]of this.queryHandlers)i.delete(e),0===i.size&&this.queryHandlers.delete(t)}detachAll(){for(const e of this.plugins)for(const t of this.plugins)t!==e&&t.onPluginDetached&&t.onPluginDetached(e.name);for(let e=this.plugins.length-1;e>=0;e--){const t=this.plugins[e];this.unsubscribeAll(t),this.unregisterQueryHandlers(t),t.detach()}this.plugins=[],this.pluginMap.clear(),this.cellRenderers.clear(),this.headerRenderers.clear(),this.cellEditors.clear(),this.eventListeners.clear(),this.queryHandlers.clear()}getPlugin(e){return this.pluginMap.get(e)}getPluginByName(e){return this.plugins.find(t=>t.name===e)}hasPlugin(e){return this.pluginMap.has(e)}getAll(){return this.plugins}getRegisteredPluginNames(){return this.plugins.map(e=>e.name)}getCellRenderer(e){return this.cellRenderers.get(e)}getHeaderRenderer(e){return this.headerRenderers.get(e)}getCellEditor(e){return this.cellEditors.get(e)}getPluginStyles(){return this.plugins.filter(e=>e.styles).map(e=>({name:e.name,styles:e.styles}))}processRows(e){let t=[...e];for(const i of this.plugins)i.processRows&&(t=i.processRows(t));return t}processColumns(e){let t=[...e];for(const i of this.plugins)i.processColumns&&(t=i.processColumns(t));return t}beforeRender(){for(const e of this.plugins)e.beforeRender?.()}afterRender(){for(const e of this.plugins)e.afterRender?.()}afterCellRender(e){for(const t of this.plugins)t.afterCellRender?.(e)}hasAfterCellRenderHook(){return this.plugins.some(e=>"function"==typeof e.afterCellRender)}afterRowRender(e){for(const t of this.plugins)t.afterRowRender?.(e)}hasAfterRowRenderHook(){return this.plugins.some(e=>"function"==typeof e.afterRowRender)}onScrollRender(){for(const e of this.plugins)e.onScrollRender?.()}getExtraHeight(){let e=0;for(const t of this.plugins)"function"==typeof t.getExtraHeight&&(e+=t.getExtraHeight());return e}hasExtraHeight(){for(const e of this.plugins)if("function"==typeof e.getExtraHeight&&e.getExtraHeight()>0)return!0;return!1}getExtraHeightBefore(e){let t=0;for(const i of this.plugins)"function"==typeof i.getExtraHeightBefore&&(t+=i.getExtraHeightBefore(e));return t}getRowHeight(e,t){for(const i of this.plugins)if("function"==typeof i.getRowHeight){const n=i.getRowHeight(e,t);if(void 0!==n)return n}}hasRowHeightPlugin(){for(const e of this.plugins)if("function"==typeof e.getRowHeight)return!0;return!1}adjustVirtualStart(e,t,i){let n=e;for(const r of this.plugins)if("function"==typeof r.adjustVirtualStart){const o=r.adjustVirtualStart(e,t,i);o<n&&(n=o)}return n}renderRow(e,t,i){for(const n of this.plugins)if(n.renderRow?.(e,t,i))return!0;return!1}queryPlugins(e){const t=[],i=this.queryHandlers.get(e.type);if(i&&i.size>0){for(const n of i){const i=n.handleQuery?.(e)??n.onPluginQuery?.(e);void 0!==i&&t.push(i)}return t}for(const n of this.plugins){const i=n.handleQuery?.(e)??n.onPluginQuery?.(e);void 0!==i&&t.push(i)}return t}subscribe(e,t,i){let n=this.eventListeners.get(t);n||(n=new Map,this.eventListeners.set(t,n)),n.set(e,i)}unsubscribe(e,t){const i=this.eventListeners.get(t);i&&(i.delete(e),0===i.size&&this.eventListeners.delete(t))}unsubscribeAll(e){for(const[t,i]of this.eventListeners)i.delete(e),0===i.size&&this.eventListeners.delete(t)}emitPluginEvent(e,t){const i=this.eventListeners.get(e);if(i)for(const r of i.values())try{r(t)}catch(n){console.error(`[tbw-grid] Error in plugin event handler for "${e}":`,n)}}onKeyDown(e){for(const t of this.plugins)if(t.onKeyDown?.(e))return!0;return!1}onCellClick(e){for(const t of this.plugins)if(t.onCellClick?.(e))return!0;return!1}onRowClick(e){for(const t of this.plugins)if(t.onRowClick?.(e))return!0;return!1}onHeaderClick(e){for(const t of this.plugins)if(t.onHeaderClick?.(e))return!0;return!1}onScroll(e){for(const t of this.plugins)t.onScroll?.(e)}onCellMouseDown(e){for(const t of this.plugins)if(t.onCellMouseDown?.(e))return!0;return!1}onCellMouseMove(e){for(const t of this.plugins)if(t.onCellMouseMove?.(e))return!0;return!1}onCellMouseUp(e){for(const t of this.plugins)if(t.onCellMouseUp?.(e))return!0;return!1}getHorizontalScrollOffsets(e,t){let i=0,n=0,r=!1;for(const o of this.plugins){const s=o.getHorizontalScrollOffsets?.(e,t);s&&(i+=s.left,n+=s.right,s.skipScroll&&(r=!0))}return{left:i,right:n,skipScroll:r}}getToolPanels(){const e=[];for(const t of this.plugins){const i=t.getToolPanel?.();i&&e.push({plugin:t,panel:i})}return e.sort((e,t)=>(e.panel.order??0)-(t.panel.order??0))}getHeaderContents(){const e=[];for(const t of this.plugins){const i=t.getHeaderContent?.();i&&e.push({plugin:t,content:i})}return e.sort((e,t)=>(e.content.order??0)-(t.content.order??0))}}class nt extends HTMLElement{static tagName="tbw-grid";static version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";static#T=0;static adapters=[];static registerAdapter(e){this.adapters.push(e)}static getAdapters(){return this.adapters}static clearAdapters(){this.adapters=[]}static get observedAttributes(){return["rows","columns","grid-config","fit-mode","loading"]}get#L(){return this}#M=!1;#E;#R;#P=[];get#s(){return this.#H?.effective??{}}#I=!1;#D=!1;#z={rows:!1,columns:!1,gridConfig:!1,fitMode:!1};#O;#F=0;#q=null;#N=!1;#G=!1;#V=0;#$;#B={startY:null,startX:null,scrollTop:null,scrollLeft:null,lastY:null,lastX:null,lastTime:null,velocityY:0,velocityX:0,momentumRaf:0};#W;#K;#U;#j;#Y={scrollTop:0,scrollLeft:0,scrollHeight:0,scrollWidth:0,clientHeight:0,clientWidth:0};#X;#Z;#Q=!1;#J;#ee;#h;#H;#te=function(){return{toolPanels:new Map,headerContents:new Map,toolbarContents:new Map,hasToolButtonsContainer:!1,lightDomHeaderContent:[],lightDomTitle:null,lightDomToolPanelIds:new Set,lightDomToolbarContentIds:new Set,apiToolPanelIds:new Set,isPanelOpen:!1,expandedSections:new Set,headerContentCleanups:new Map,panelCleanups:new Map,toolbarContentCleanups:new Map,lightDomContentMoved:!1}}();#ie;#ne;#re;#oe=!1;#se=new Set;#le=new Map;#ae;#de=new Map;_rows=[];#ce=[];get _columns(){return this.#s.columns??[]}set _columns(e){this.#s.columns=e}get _visibleColumns(){return this._columns.filter(e=>!e.hidden)}_headerRowEl;_bodyEl;_rowPool=[];_resizeController;_virtualization={enabled:!0,rowHeight:28,bypassThreshold:24,start:0,end:0,container:null,viewportEl:null,totalHeightEl:null,positionCache:null,heightCache:{byKey:new Map,byRef:new WeakMap},averageHeight:28,measuredCount:0,variableHeights:!1,cachedViewportHeight:0,cachedFauxHeight:0,cachedScrollAreaHeight:0,scrollAreaEl:null};_focusRow=0;_focusCol=0;_restoreFocusAfterRender=!1;_sortState=null;_gridTemplate="";__rowRenderEpoch=0;__didInitialAutoSize=!1;get __lightDomColumnsCache(){return this.#H?.lightDomColumnsCache}set __lightDomColumnsCache(e){this.#H&&(this.#H.lightDomColumnsCache=e)}get __originalColumnNodes(){return this.#H?.originalColumnNodes}set __originalColumnNodes(e){this.#H&&(this.#H.originalColumnNodes=e)}__originalOrder=[];__frameworkAdapter;__rowsBodyEl=null;get rows(){return this._rows}set rows(e){const t=this.#P;this.#P=e,t!==e&&this.#he("rows")}get sourceRows(){return this.#P}get columns(){return[...this._columns]}set columns(e){const t=this.#H?.getColumns();this.#H?.setColumns(e),t!==e&&this.#he("columns")}get gridConfig(){return this.#s}set gridConfig(e){const t=this.#H?.getGridConfig();this.#H?.setGridConfig(e),t!==e&&(this.#H.clearLightDomCache(),this.#he("gridConfig"))}get fitMode(){return this.#s.fitMode??"stretch"}set fitMode(e){const t=this.#H?.getFitMode();this.#H?.setFitMode(e),t!==e&&this.#he("fitMode")}get loading(){return this.#oe}set loading(e){const t=this.#oe;this.#oe=e,e?this.setAttribute("loading",""):this.removeAttribute("loading"),t!==e&&this.#ue()}setRowLoading(e,t){const i=this.#se.has(e);t?this.#se.add(e):this.#se.delete(e),i!==t&&this.#ge(e,t)}setCellLoading(e,t,i){let n=this.#le.get(e);const r=n?.has(t)??!1;i?(n||(n=new Set,this.#le.set(e,n)),n.add(t)):(n?.delete(t),0===n?.size&&this.#le.delete(e)),r!==i&&this.#pe(e,t,i)}isRowLoading(e){return this.#se.has(e)}isCellLoading(e,t){return this.#le.get(e)?.has(t)??!1}clearAllLoading(){this.loading=!1;for(const e of this.#se)this.#ge(e,!1);this.#se.clear();for(const[e,t]of this.#le)for(const i of t)this.#pe(e,i,!1);this.#le.clear()}get effectiveConfig(){return this.#s}get disconnectSignal(){return this.#W||(this.#W=new AbortController),this.#W.signal}constructor(){super(),this.#fe(),this.#E=new Promise(e=>this.#R=e),this.#O=new ue({mergeConfig:()=>{this.#H.parseLightDomColumns(this),this.#H.merge(),this.#we(),function(e,t){const i=Ke,n=Ue,r=new Map;function o(e,t,i,n,o=!1){r.has(e)||r.set(e,{description:t,importHint:i,fields:[],isConfigProperty:o});const s=r.get(e);s.fields.includes(n)||s.fields.push(n)}for(const l of n){const i=e[l.property];(l.isUsed?l.isUsed(i):void 0!==i)&&!Xe(t,l.pluginName)&&o(l.pluginName,l.description,je(l.pluginName),l.property,!0)}const s=e.columns;if(s&&s.length>0)for(const l of s)for(const e of i){const i=l[e.property];if((e.isUsed?e.isUsed(i):void 0!==i)&&!Xe(t,e.pluginName)){const t=l.field||"<unknown>";o(e.pluginName,e.description,je(e.pluginName),t)}}if(r.size>0){const e=[];for(const[t,{description:i,importHint:n,fields:o,isConfigProperty:s}]of r)if(s)e.push(`Config uses ${i}, but the required plugin is not loaded.\n → Add the plugin to your gridConfig.plugins array:\n ${n}\n plugins: [new ${Ye(t)}Plugin(), ...]`);else{const r=o.slice(0,3).join(", ")+(o.length>3?`, ... (${o.length} total)`:"");e.push(`Column(s) [${r}] use ${i}, but the required plugin is not loaded.\n → Add the plugin to your gridConfig.plugins array:\n ${n}\n plugins: [new ${Ye(t)}Plugin(), ...]`)}throw new Error(`[tbw-grid] Configuration error:\n\n${e.join("\n\n")}\n\nThis validation helps catch misconfigurations early. The properties listed above require their respective plugins to function.`)}}(this.#s,this.#X?.getPlugins()??[]),function(e){const t=[],i=[];for(const n of e){const e=n.constructor.manifest;if(e?.configRules)for(const r of e.configRules){const e=n.config;if(r.check(e)){const e=`[tbw-grid:${Ye(n.name)}Plugin] Configuration warning: ${r.message}`;"error"===r.severity?t.push(e):i.push(e)}}}if(i.length>0&&_())for(const n of i)console.warn(n);if(t.length>0)throw new Error(`[tbw-grid] Configuration error:\n\n${t.join("\n\n")}`)}(this.#X?.getPlugins()??[]),function(e){if(!_())return;const t=new Set(e.map(e=>e.name)),i=new Set;for(const n of e){const e=n.constructor.manifest;if(e?.incompatibleWith)for(const r of e.incompatibleWith)if(t.has(r.name)){const e=[n.name,r.name].sort().join("↔");if(i.has(e))continue;i.add(e),console.warn(`[tbw-grid] Plugin incompatibility warning:\n\n${Ye(n.name)}Plugin and ${Ye(r.name)}Plugin are both loaded, but they are currently incompatible.\n\n → ${r.reason}\n\n Consider removing one of these plugins to avoid unexpected behavior.`)}}}(this.#X?.getPlugins()??[]),this.#me(),this.#ce=[...this._columns]},processColumns:()=>this.#be(),processRows:()=>this.#ve(),renderHeader:()=>le(this),updateTemplate:()=>c(this),renderVirtualWindow:()=>this.refreshVirtualWindow(!0,!0),afterRender:()=>{this.#X?.afterRender(),this._virtualization.enabled&&this._virtualization.totalHeightEl&&queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const e=this.#ye(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`});"fixed"!==this.#s.fitMode||this.__didInitialAutoSize||(this.__didInitialAutoSize=!0,l(this)),this._restoreFocusAfterRender&&(this._restoreFocusAfterRender=!1,K(this)),this._virtualization.enabled&&!this.#Ce&&this.#xe(),this.#G&&(this.#G=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.#Ee()})})),this.#oe&&this.#ue()},isConnected:()=>this.isConnected&&this.#I}),this.#O.setInitialReadyResolver(()=>this.#R?.()),this.#ie=De(this.#te,{getShadow:()=>this.#L,getShellConfig:()=>this.#s?.shell,getAccordionIcons:()=>({expand:this.#s?.icons?.expand??r.expand,collapse:this.#s?.icons?.collapse??r.collapse}),emit:(e,t)=>this.#Re(e,t),refreshShellHeader:()=>this.refreshShellHeader()}),this.#H=new S({getRows:()=>this.#P,getSortState:()=>this._sortState,setSortState:e=>{this._sortState=e},onConfigChange:()=>{this.#O.requestPhase(he.FULL,"configChange")},emit:(e,t)=>this.#Re(e,t),clearRowPool:()=>{this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++},setup:()=>this.#Se(),renderHeader:()=>le(this),updateTemplate:()=>c(this),refreshVirtualWindow:()=>this.#O.requestPhase(he.VIRTUALIZATION,"configManager"),getVirtualization:()=>this._virtualization,setRowHeight:e=>{this._virtualization.rowHeight=e},applyAnimationConfig:e=>this.#_e(e),getShellLightDomTitle:()=>this.#te.lightDomTitle,getShellToolPanels:()=>this.#te.toolPanels,getShellHeaderContents:()=>this.#te.headerContents,getShellToolbarContents:()=>this.#te.toolbarContents,getShellLightDomHeaderContent:()=>this.#te.lightDomHeaderContent,getShellHasToolButtonsContainer:()=>this.#te.hasToolButtonsContainer})}async#fe(){await Ve('@layer tbw-base, tbw-plugins, tbw-theme;\n\n@layer tbw-base{tbw-grid{--tbw-base-icon-size: 1em;--tbw-base-radius: .25em;--tbw-font-size: 1em;--tbw-font-size-sm: .9285em;--tbw-font-size-xs: .7857em;--tbw-font-size-2xs: .7142em;--tbw-spacing-xs: .25em;--tbw-spacing-sm: .375em;--tbw-spacing-md: .5em;--tbw-spacing-lg: .75em;--tbw-spacing-xl: 1em;--tbw-icon-size: var(--tbw-base-icon-size);--tbw-icon-size-sm: .875em;--tbw-checkbox-size: var(--tbw-base-icon-size);--tbw-toggle-size: 1.25em;--tbw-border-radius: var(--tbw-base-radius);--tbw-color-bg: transparent;--tbw-color-panel-bg: light-dark(#eeeeee, #222222);--tbw-color-fg: light-dark(#222222, #eeeeee);--tbw-color-fg-muted: light-dark(#555555, #aaaaaa);--tbw-color-accent: light-dark(#3b82f6, #3b82f6);--tbw-color-accent-fg: light-dark(#ffffff, #000000);--tbw-color-success: light-dark(hsl(122, 39%, 40%), hsl(122, 39%, 49%));--tbw-color-warning: light-dark(hsl(38, 92%, 50%), hsl(38, 92%, 50%));--tbw-color-error: light-dark(hsl(0, 65%, 51%), hsl(0, 65%, 55%));--tbw-color-danger: var(--tbw-color-error);--tbw-color-selection: light-dark(#fff7d6, #333333);--tbw-color-row-alt: var(--tbw-color-bg);--tbw-color-row-hover: light-dark(#f0f6ff, #1c1c1c);--tbw-color-header-bg: color-mix(in hsl, var(--tbw-color-panel-bg) 85%, var(--tbw-color-fg));--tbw-color-header-fg: color-mix(in hsl, var(--tbw-color-fg) 75%, var(--tbw-color-panel-bg));--tbw-color-border: light-dark(#d0d0d4, #454545);--tbw-color-border-strong: light-dark(#777777, #666666);--tbw-color-border-cell: var(--tbw-color-border);--tbw-color-border-header: var(--tbw-color-border);--tbw-color-shadow: light-dark(rgba(0, 0, 0, .1), rgba(0, 0, 0, .3));--tbw-font-family: inherit;--tbw-font-size-header: var(--tbw-font-size);--tbw-font-weight-header: bold;--tbw-cell-padding-header: var(--tbw-spacing-xs) var(--tbw-spacing-md);--tbw-cell-padding-v: var(--tbw-spacing-xs);--tbw-cell-padding-h: var(--tbw-spacing-md);--tbw-cell-padding: var(--tbw-cell-padding-v) var(--tbw-cell-padding-h);--tbw-cell-padding-input: var(--tbw-spacing-xs) var(--tbw-spacing-sm);--tbw-row-height: 1.75em;--tbw-header-height: 1.875em;--tbw-cell-white-space: nowrap;--tbw-border-width: 1px;--tbw-border-style: solid;--tbw-border-input: var(--tbw-border-width) var(--tbw-border-style) var(--tbw-color-border-strong);--tbw-border-header: var(--tbw-border-width) var(--tbw-border-style) var(--tbw-color-border-header);--tbw-row-divider: var(--tbw-border-width) var(--tbw-border-style) var(--tbw-color-border-cell);--tbw-row-hover-outline: 0;--tbw-color-active-row-bg: var(--tbw-color-selection);--tbw-active-row-outline: 0;--tbw-focus-outline-width: 2px;--tbw-focus-outline: var(--tbw-focus-outline-width) var(--tbw-border-style) var(--tbw-color-accent);--tbw-focus-outline-offset: -2px;--tbw-focus-background: rgba(from var(--tbw-color-accent) r g b / 12%);--tbw-range-border-color: var(--tbw-color-accent);--tbw-range-selection-bg: rgba(from var(--tbw-range-border-color) r g b / 12%);--tbw-resize-handle-width: var(--tbw-spacing-sm);--tbw-resize-handle-color: transparent;--tbw-resize-handle-color-hover: var(--tbw-color-accent);--tbw-resize-handle-border-radius: 0;--tbw-resize-indicator-width: 2px;--tbw-resize-indicator-color: var(--tbw-color-accent);--tbw-resize-indicator-opacity: .6;--tbw-transition-duration: .12s;--tbw-transition-ease: ease;--tbw-animation-duration: .2s;--tbw-animation-easing: ease-out;--tbw-animation-enabled: 1;--tbw-row-change-duration: .5s;--tbw-row-insert-duration: .3s;--tbw-row-remove-duration: .2s;--tbw-row-change-color: rgba(from var(--tbw-color-accent) r g b / 25%);--tbw-sort-indicator-color: var(--tbw-color-fg-muted);--tbw-sort-indicator-active-color: var(--tbw-color-accent);--tbw-sort-indicator-display: inline-flex;--tbw-sort-indicator-visibility: visible;--tbw-header-text-transform: none;--tbw-header-letter-spacing: normal;--tbw-color-header-separator: var(--tbw-color-border-cell);--tbw-density-scale: 1;--tbw-shell-header-height: 2.75em;--tbw-shell-header-bg: var(--tbw-color-panel-bg);--tbw-shell-header-border: var(--tbw-color-border);--tbw-shell-title-font-size: var(--tbw-font-size);--tbw-shell-title-font-weight: 600;--tbw-tool-panel-width: 17.5em;--tbw-tool-panel-bg: var(--tbw-color-panel-bg);--tbw-tool-panel-border: var(--tbw-color-border);--tbw-tool-panel-header-height: 2.5em;--tbw-tool-panel-transition: var(--tbw-animation-duration) var(--tbw-animation-easing);--tbw-toolbar-button-size: 2em;--tbw-toolbar-button-gap: var(--tbw-spacing-xs);--tbw-panel-padding: var(--tbw-spacing-lg);--tbw-panel-gap: var(--tbw-spacing-md);--tbw-menu-item-padding: var(--tbw-spacing-sm) var(--tbw-spacing-lg);--tbw-menu-item-gap: var(--tbw-spacing-md);--tbw-menu-min-width: 10rem;--tbw-button-padding: var(--tbw-spacing-sm) var(--tbw-spacing-lg);--tbw-button-padding-sm: var(--tbw-spacing-xs) var(--tbw-spacing-md);--tbw-input-height: var(--tbw-row-height);--tbw-input-padding: 0 var(--tbw-spacing-md);--tbw-detail-padding: var(--tbw-spacing-xl);--tbw-detail-max-height: 31.25rem;--tbw-indicator-size: var(--tbw-spacing-sm)}}\n@layer tbw-base{tbw-grid{color-scheme:inherit;position:relative;display:block;width:100%;height:100%;min-height:0;contain:content;font-family:var(--tbw-font-family);font-size:var(--tbw-font-size);font-feature-settings:"tnum","lnum";background:var(--tbw-color-bg);color:var(--tbw-color-fg);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);overflow:clip;outline:none}tbw-grid,tbw-grid *{box-sizing:border-box}tbw-grid .tbw-grid-root{position:relative;display:flex;flex-direction:column;height:100%}tbw-grid .tbw-grid-root.has-shell{display:flex;flex-direction:column;height:100%}tbw-grid .tbw-grid-root:has(.selected){-webkit-user-select:none;user-select:none}tbw-grid .rows-body-wrapper{flex:1;min-height:0;display:flex;flex-direction:row;width:100%;min-width:fit-content}tbw-grid .rows-body{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:visible}tbw-grid .rows-container{display:flex;flex-direction:row;flex:1;min-height:0;overflow:visible}tbw-grid .rows-viewport{flex:1;min-width:0;position:relative;display:block;overflow:clip}tbw-grid .rows-viewport .rows{position:absolute;top:0;left:0;min-width:100%;will-change:transform;z-index:var(--tbw-z-layer-rows, 1)}tbw-grid .faux-vscroll{position:sticky;inset-inline-end:0;flex-shrink:0;width:auto;overflow-y:auto;overflow-x:hidden;z-index:var(--tbw-z-layer-header, 30)}tbw-grid .faux-vscroll-spacer{width:1px}tbw-grid[data-has-focus] .cell-focus,tbw-grid[data-has-focus] .row-focus{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}tbw-grid .sticky-left,tbw-grid .sticky-right{position:sticky;z-index:25}tbw-grid .sticky-left{box-shadow:1px 0 0 var(--tbw-color-border)}tbw-grid .sticky-right{box-shadow:-1px 0 0 var(--tbw-color-border)}}\n@layer tbw-base{tbw-grid .header{display:block;flex-shrink:0;z-index:var(--tbw-z-layer-header, 30);background:var(--tbw-color-header-bg);overflow:visible}tbw-grid .header-group-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-color-header-bg);z-index:var(--tbw-z-layer-header, 30)}tbw-grid .header-group-cell{display:flex;align-items:center;justify-content:flex-start;padding:var(--tbw-cell-padding-header, 2px 8px);color:var(--tbw-color-header-group-fg, var(--tbw-color-header-fg));font-weight:var(--tbw-font-weight-header-group, var(--tbw-font-weight-header));justify-content:var(--tbw-align-header-group, var(--tbw-align-header, flex-start))}tbw-grid .header-group-cell:not(:last-child){border-right:2px solid var(--tbw-color-border)}tbw-grid .header-row{display:grid;grid-template-columns:var(--tbw-column-template);color:var(--tbw-color-header-fg);font-size:var(--tbw-font-size-header);min-height:var(--tbw-header-height);border-bottom:var(--tbw-border-header);z-index:var(--tbw-z-layer-header, 30);text-transform:var(--tbw-header-text-transform);letter-spacing:var(--tbw-header-letter-spacing)}tbw-grid .header-row>.cell{display:flex;align-items:center;gap:4px;padding:var(--tbw-cell-padding-header, 2px 8px);background-color:var(--tbw-color-header-bg);font-weight:var(--tbw-font-weight-header);border-right:1px solid var(--tbw-color-border-cell);overflow:visible;min-width:0}tbw-grid .header-row>.cell>span:first-child{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:inherit}tbw-grid .header-row>.cell>span[part~=sort-indicator]{flex-shrink:0;opacity:.6;color:var(--tbw-sort-indicator-color);display:var(--tbw-sort-indicator-display, inline-flex);visibility:var(--tbw-sort-indicator-visibility, visible);transition:opacity .15s,visibility 0s,display 0s allow-discrete;transition-behavior:allow-discrete}tbw-grid .header-row>.cell:hover>span[part~=sort-indicator]{display:inline-flex;visibility:visible}tbw-grid .header-row>.cell[aria-sort=ascending]>span[part~=sort-indicator],tbw-grid .header-row>.cell[aria-sort=descending]>span[part~=sort-indicator]{display:inline-flex;visibility:visible;opacity:1;color:var(--tbw-sort-indicator-active-color)}tbw-grid .header-row>.cell:last-child{border-right:0}tbw-grid .header-row>.cell:last-child .resize-handle{right:0;width:calc(var(--tbw-resize-handle-width) / 2)}tbw-grid .header-row>.cell.grouped.group-end:not(:last-child){border-right:2px solid var(--tbw-color-border)}tbw-grid .header-row>.cell.resizable{position:relative}tbw-grid .header-row>.cell.sticky-left,tbw-grid .header-row>.cell.sticky-right{background:var(--tbw-color-header-bg);z-index:35}tbw-grid .sortable{cursor:pointer;-webkit-user-select:none;user-select:none}tbw-grid .resize-handle{position:absolute;top:0;right:calc(var(--tbw-resize-handle-width) / -2);width:var(--tbw-resize-handle-width);height:100%;cursor:e-resize;-webkit-user-select:none;user-select:none;touch-action:none;z-index:20;background:var(--tbw-resize-handle-color);transition:background .12s ease;border-radius:var(--tbw-resize-handle-border-radius)}tbw-grid .resize-handle:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);width:var(--tbw-resize-indicator-width, 2px);height:0;background:var(--tbw-resize-indicator-color, var(--tbw-color-accent));opacity:0;pointer-events:none;transition:opacity .12s ease,height 0s .12s;z-index:1000}tbw-grid .resize-handle:hover{background:var(--tbw-resize-handle-color-hover)}tbw-grid .resize-handle:hover:after{height:100vh;opacity:var(--tbw-resize-indicator-opacity, .6);transition:opacity .12s ease,height 0s}}\n@layer tbw-base{tbw-grid .data-grid-row{display:grid;grid-template-columns:var(--tbw-column-template);contain:layout style}tbw-grid .data-grid-row:nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid .data-grid-row:hover{background:var(--tbw-color-row-hover)}tbw-grid .data-grid-row>.cell{display:block;padding:var(--tbw-cell-padding, 2px 8px);border-bottom:var(--tbw-row-divider);min-height:var(--tbw-row-height);align-content:center;border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;min-width:0;white-space:var(--tbw-cell-white-space, nowrap);text-overflow:ellipsis}tbw-grid .data-grid-row>.cell>*{overflow:hidden;text-overflow:ellipsis;white-space:inherit;min-width:0}tbw-grid .data-grid-row>.cell:last-child{border-right:0}tbw-grid .data-grid-row>.cell[data-type=boolean]{text-align:center}tbw-grid .data-grid-row>.cell[data-type=boolean] input[type=checkbox]{margin:0;width:var(--tbw-checkbox-size);height:var(--tbw-checkbox-size);vertical-align:middle}tbw-grid .data-grid-row>.cell.selected:focus-visible,tbw-grid .data-grid-row>.cell:focus-visible:not(.cell-focus){outline:none}tbw-grid .data-grid-row>.cell.sticky-left,tbw-grid .data-grid-row>.cell.sticky-right{background:var(--tbw-color-panel-bg)}tbw-grid .selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}}\n@layer tbw-base{tbw-grid .tbw-shell-header{display:flex;align-items:center;gap:8px;min-height:var(--tbw-shell-header-height);padding:0 8px;background:var(--tbw-shell-header-bg);border-bottom:1px solid var(--tbw-shell-header-border);flex-shrink:0}tbw-grid .tbw-shell-title{font-size:var(--tbw-shell-title-font-size);font-weight:var(--tbw-shell-title-font-weight);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}tbw-grid .tbw-shell-content{flex:1;display:flex;align-items:center;gap:12px;min-width:0;overflow:hidden}tbw-grid .tbw-shell-toolbar{display:flex;align-items:center;gap:var(--tbw-toolbar-button-gap);flex-shrink:0}tbw-grid .tbw-toolbar-btn{display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-toolbar-button-size);height:var(--tbw-toolbar-button-size);padding:0;border:1px solid transparent;border-radius:var(--tbw-border-radius);background:transparent;color:var(--tbw-color-fg);cursor:pointer;font-size:16px;transition:background var(--tbw-transition-duration) var(--tbw-transition-ease),border-color var(--tbw-transition-duration) var(--tbw-transition-ease)}tbw-grid .tbw-toolbar-btn:hover{background:var(--tbw-color-row-hover)}tbw-grid .tbw-toolbar-btn:focus-visible{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}tbw-grid .tbw-toolbar-btn.active{background:var(--tbw-focus-background);border-color:var(--tbw-color-accent)}tbw-grid .tbw-toolbar-btn:disabled{opacity:.5;cursor:not-allowed}tbw-grid .tbw-toolbar-separator{width:1px;height:20px;background:var(--tbw-color-border);margin:0 4px}tbw-grid .tbw-shell-body{position:relative;display:flex;flex:1;min-height:0;overflow:visible}tbw-grid .tbw-grid-content{flex:1;min-width:0;min-height:0;display:flex;flex-direction:row;overflow:hidden}tbw-grid .tbw-scroll-area{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow-x:auto;overflow-y:hidden;overflow-anchor:none}}\n@layer tbw-base{tbw-grid .tbw-tool-panel{position:absolute;top:0;bottom:0;right:0;width:0;overflow:hidden;background:var(--tbw-tool-panel-bg);border-left:1px solid var(--tbw-tool-panel-border);transition:width var(--tbw-tool-panel-transition);display:flex;flex-direction:column;z-index:30;box-shadow:-2px 0 8px var(--tbw-color-shadow)}tbw-grid .tbw-tool-panel[data-position=left]{right:auto;left:0;border-left:none;border-right:1px solid var(--tbw-tool-panel-border);box-shadow:2px 0 8px var(--tbw-color-shadow)}tbw-grid .tbw-tool-panel.open{width:var(--tbw-tool-panel-width)}tbw-grid .tbw-tool-panel-resize{position:absolute;top:0;bottom:0;width:6px;cursor:col-resize;background:transparent;z-index:10;transition:background var(--tbw-transition-duration) var(--tbw-transition-ease)}tbw-grid .tbw-tool-panel-resize[data-handle-position=left]{left:0}tbw-grid .tbw-tool-panel-resize[data-handle-position=right]{right:0}tbw-grid .tbw-tool-panel-resize:hover,tbw-grid .tbw-tool-panel-resize.resizing{background:var(--tbw-color-accent)}tbw-grid .tbw-tool-panel-header{display:flex;align-items:center;justify-content:space-between;min-height:var(--tbw-tool-panel-header-height);padding:0 12px;border-bottom:1px solid var(--tbw-tool-panel-border);flex-shrink:0}tbw-grid .tbw-tool-panel-title{font-weight:600;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}tbw-grid .tbw-tool-panel-close{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:none;border-radius:var(--tbw-border-radius);background:transparent;color:var(--tbw-color-fg-muted);cursor:pointer;font-size:14px}tbw-grid .tbw-tool-panel-close:hover{background:var(--tbw-color-row-hover);color:var(--tbw-color-fg)}tbw-grid .tbw-tool-panel-content{flex:1;overflow:auto}tbw-grid .tbw-accordion{display:flex;flex-direction:column;gap:0}tbw-grid .tbw-accordion-section{border-bottom:1px solid var(--tbw-tool-panel-border)}tbw-grid .tbw-accordion-section:last-child{border-bottom:none}tbw-grid .tbw-accordion-section.single .tbw-accordion-header{cursor:default}tbw-grid .tbw-accordion-section.single .tbw-accordion-header:hover{background:transparent}tbw-grid .tbw-accordion-section.expanded .tbw-accordion-chevron{transform:rotate(90deg)}tbw-grid .tbw-accordion-section.expanded .tbw-accordion-content{display:block}tbw-grid .tbw-accordion-header{display:flex;align-items:center;gap:8px;width:100%;padding:10px 12px;border:none;background:transparent;color:var(--tbw-color-fg);font-size:13px;font-weight:600;text-align:start;cursor:pointer;-webkit-user-select:none;user-select:none}tbw-grid .tbw-accordion-header:hover{background:var(--tbw-color-row-hover)}tbw-grid .tbw-accordion-chevron{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;font-size:10px;color:var(--tbw-color-fg-muted);transition:transform .15s ease;flex-shrink:0}tbw-grid .tbw-accordion-icon{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;font-size:14px;flex-shrink:0}tbw-grid .tbw-accordion-title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}tbw-grid .tbw-accordion-content{display:none}}\n@layer tbw-base{.tbw-loading-overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:1000;pointer-events:all;animation:tbw-fade-in .15s ease-out}.tbw-spinner{--tbw-spinner-size: 48px;--tbw-spinner-border-width: 3px;--tbw-spinner-color: var(--tbw-color-accent);--tbw-spinner-track-color: var(--tbw-color-border);width:var(--tbw-spinner-size);height:var(--tbw-spinner-size);border:var(--tbw-spinner-border-width) solid var(--tbw-spinner-track-color);border-top-color:var(--tbw-spinner-color);border-radius:50%;animation:tbw-spin .8s linear infinite}.tbw-spinner--large{--tbw-spinner-size: min(48px, calc(100% - 16px) )}.tbw-spinner--small{--tbw-spinner-size: calc(var(--tbw-row-height, 28px) * .6);--tbw-spinner-border-width: 2px}.data-grid-row.tbw-row-loading{position:relative;pointer-events:none}.tbw-row-loading-overlay{position:absolute;inset:0;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:26;animation:tbw-fade-in .15s ease-out;pointer-events:none;display:flex;align-items:center}.tbw-row-loading-spinner{--_spinner-size: calc(var(--tbw-row-height, 28px) * .6);margin-left:var(--tbw-spacing-md);width:var(--_spinner-size);height:var(--_spinner-size);border:2px solid var(--tbw-spinner-track-color, var(--tbw-color-border));border-top-color:var(--tbw-spinner-color, var(--tbw-color-accent));border-radius:50%;animation:tbw-spin .8s linear infinite}.cell.tbw-cell-loading{position:relative;pointer-events:none}.cell.tbw-cell-loading:before{content:"";position:absolute;inset:0;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:26;animation:tbw-fade-in .15s ease-out}.cell.tbw-cell-loading:after{--_spinner-size: calc(var(--tbw-row-height, 28px) * .5);content:"";position:absolute;left:var(--tbw-spacing-sm);top:0;bottom:0;margin:auto 0;width:var(--_spinner-size);height:var(--_spinner-size);border:2px solid var(--tbw-spinner-track-color, var(--tbw-color-border));border-top-color:var(--tbw-spinner-color, var(--tbw-color-accent));border-radius:50%;animation:tbw-spin .8s linear infinite;z-index:27}}\n@layer tbw-base{tbw-grid .tbw-expanding{animation:tbw-expand var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}tbw-grid .tbw-collapsing{animation:tbw-collapse var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}tbw-grid[data-animation-mode=off]{--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}tbw-grid[data-animation-mode=off] .data-grid-row[data-animating]{animation:none}tbw-grid .data-grid-row[data-animating=change]{animation:tbw-row-change var(--tbw-row-change-duration) ease-out}tbw-grid .data-grid-row[data-animating=insert]{animation:tbw-row-insert var(--tbw-row-insert-duration) ease-out;will-change:max-height,opacity}tbw-grid .data-grid-row[data-animating=remove]{animation:tbw-row-remove var(--tbw-row-remove-duration) ease-out forwards;will-change:max-height,opacity,transform;pointer-events:none}}@keyframes tbw-expand{0%{opacity:0;max-height:0;transform:translateY(-8px)}to{opacity:1;max-height:500px;transform:translateY(0)}}@keyframes tbw-collapse{0%{opacity:1;max-height:500px;transform:translateY(0)}to{opacity:0;max-height:0;transform:translateY(-8px)}}@keyframes tbw-row-change{0%{background-color:transparent}20%{background-color:var(--tbw-row-change-color)}to{background-color:transparent}}@keyframes tbw-row-insert{0%{opacity:0;max-height:0;overflow:hidden}to{opacity:1;max-height:var(--tbw-row-height, 28px);overflow:hidden}}@keyframes tbw-row-remove{0%{opacity:1;transform:translateY(0);max-height:var(--tbw-row-height, 28px)}to{opacity:0;max-height:0;transform:translateY(-8px)}}@keyframes tbw-spin{to{transform:rotate(360deg)}}@keyframes tbw-fade-in{0%{opacity:0}to{opacity:1}}\n@layer tbw-base{@media(forced-colors:active){tbw-grid{--tbw-color-border: CanvasText;--tbw-color-border-strong: CanvasText;--tbw-color-border-cell: CanvasText;--tbw-color-border-header: CanvasText;--tbw-color-fg: CanvasText;--tbw-color-bg: Canvas;--tbw-color-panel-bg: Canvas;--tbw-color-header-bg: Canvas;--tbw-color-header-fg: CanvasText;--tbw-color-accent: Highlight;--tbw-color-accent-fg: HighlightText;--tbw-color-selection: Highlight;--tbw-color-row-hover: Highlight;--tbw-focus-outline: 2px solid Highlight;--tbw-range-border-color: Highlight}tbw-grid .cell:focus,tbw-grid .cell.active-cell{outline:2px solid Highlight!important;outline-offset:-2px}tbw-grid .data-grid-row[aria-selected=true]{background:Highlight!important;color:HighlightText!important}}@media(prefers-reduced-motion:reduce){tbw-grid[data-animation-mode=reduced-motion]{--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}tbw-grid[data-animation-mode=reduced-motion] .data-grid-row[data-animating]{animation:none}}}\n')}getPlugin(e){return this.#X?.getPlugin(e)}getPluginByName(e){return this.#X?.getPluginByName(e)}requestRender(){this.#O.requestPhase(he.ROWS,"plugin:requestRender")}requestColumnsRender(){this.#O.requestPhase(he.COLUMNS,"plugin:requestColumnsRender")}requestRenderWithFocus(){this._restoreFocusAfterRender=!0,this.#O.requestPhase(he.ROWS,"plugin:requestRenderWithFocus")}updateTemplate(){c(this)}requestAfterRender(){this.#O.requestPhase(he.STYLE,"plugin:requestAfterRender")}#Ae(){this.#X=new it(this);const e=this.#s?.plugins,t=Array.isArray(e)?e:[];this.#X.attachAll(t)}#ke(){!function(e){let t=!1;for(const{name:i,styles:n}of e)Ne.has(i)||(Ne.set(i,n),t=!0);t&&Ge()}(this.#X?.getPluginStyles()??[])}#we(){const e=this.#s?.plugins,t=Array.isArray(e)?e:[];if(this.#Z===t)return;if(this.#Z&&this.#Z.length===t.length&&this.#Z.every((e,i)=>e===t[i]))return void(this.#Z=t);this.#X&&this.#X.detachAll();for(const n of this.#te.toolPanels.keys()){const e=this.#te.lightDomToolPanelIds.has(n),t=this.#te.apiToolPanelIds.has(n);if(!e&&!t){const e=this.#te.panelCleanups.get(n);e&&(e(),this.#te.panelCleanups.delete(n)),this.#te.toolPanels.delete(n)}}for(const n of this.#te.headerContents.keys()){const e=this.#te.headerContentCleanups.get(n);e&&(e(),this.#te.headerContentCleanups.delete(n)),this.#te.headerContents.delete(n)}this.#Ae(),this.#ke(),this.#Z=t,this.#Te(),this.#Le();const i=this.#N;if(this.#N=this.#X?.getAll().some(e=>e.onScroll)??!1,!i&&this.#N){const e=this.#L.querySelector(".tbw-grid-content")??this.#L.querySelector(".tbw-grid-root");this.#Me(e)}}#Pe(){this.#X?.detachAll()}#Le(){if(!this.#X)return;const e=this.#X.getToolPanels();for(const{panel:i}of e)this.#te.toolPanels.has(i.id)||this.#te.toolPanels.set(i.id,i);const t=this.#X.getHeaderContents();for(const{content:i}of t)this.#te.headerContents.has(i.id)||this.#te.headerContents.set(i.id,i)}#He(){const e=nt.getAdapters();if(0===e.length&&!this.__frameworkAdapter)return;const t=this.__frameworkAdapter;return i=>{if(t?.createToolPanelRenderer){const e=t.createToolPanelRenderer(i);if(e)return e}for(const t of e)if(t.createToolPanelRenderer){const e=t.createToolPanelRenderer(i);if(e)return e}}}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=0),this.hasAttribute("version")||this.setAttribute("version",nt.version),this.id||(this.id="tbw-grid-"+ ++nt.#T),this._rows=Array.isArray(this.#P)?[...this.#P]:[],this.#W&&(this.#W.abort(),this.#Q=!1),this.#W=new AbortController,this.#j&&(de(this.#j),this.#j=void 0),this.#Ie(),this.#H.parseLightDomColumns(this),this.#H.merge(),this.#Ae();const e=this.#s?.plugins;var t,i;this.#Z=Array.isArray(e)?e:[],this.#Le(),this.#M||(this.#De(),this.#ke(),this.#M=!0),this.#ze(),this.#j=(t=()=>{this.#Oe()},i={timeout:100},ae?requestIdleCallback(t,i):window.setTimeout(()=>{const e=Date.now();t({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-e))})},1))}disconnectedCallback(){this.#j&&(de(this.#j),this.#j=void 0),this.#V&&(clearTimeout(this.#V),this.#V=0),this.#Pe(),function(e){for(const t of e.headerContentCleanups.values())t();e.headerContentCleanups.clear();for(const t of e.panelCleanups.values())t();e.panelCleanups.clear();for(const t of e.toolbarContentCleanups.values())t();e.toolbarContentCleanups.clear();for(const t of e.toolbarContents.values())t.onDestroy?.();if(e.isPanelOpen)for(const t of e.expandedSections){const i=e.toolPanels.get(t);i?.onClose?.()}e.isPanelOpen=!1,e.expandedSections.clear(),e.toolPanels.clear(),e.headerContents.clear(),e.toolbarContents.clear(),e.lightDomHeaderContent=[],e.lightDomToolPanelIds.clear(),e.lightDomToolbarContentIds.clear(),e.lightDomContentMoved=!1}(this.#te),this.#ie.setInitialized(!1),this.#ne?.(),this.#ne=void 0,this.#re?.(),this.#re=void 0,$e(this.#B),this.#W&&(this.#W.abort(),this.#W=void 0),this.#J?.abort(),this.#J=void 0,this.#Q=!1,this._resizeController&&this._resizeController.dispose(),this.#K&&(this.#K.disconnect(),this.#K=void 0),this.#U&&(this.#U.disconnect(),this.#U=void 0,this.#Ce=!1),V(this),this.#Fe.clear(),this.#Z=void 0;for(const e of this._rowPool)e.remove();this._rowPool.length=0,this.__rowsBodyEl=null,this.#I=!1}attributeChangedCallback(e,t,i){if("loading"===e){const e=null!==i&&"false"!==i;return void(this.loading!==e&&(this.loading=e))}if(t!==i&&i&&"null"!==i&&"undefined"!==i)if("rows"===e||"columns"===e||"grid-config"===e)try{const t=JSON.parse(i);"rows"===e?this.rows=t:"columns"===e?this.columns=t:"grid-config"===e&&(this.gridConfig=t)}catch{console.warn(`[tbw-grid] Invalid JSON for '${e}' attribute:`,i)}else"fit-mode"===e&&(this.fitMode=i)}#ze(){const e=this.#L.querySelector(".tbw-grid-content")??this.#L.querySelector(".tbw-grid-root");if(this._headerRowEl=e?.querySelector(".header-row"),this._virtualization.totalHeightEl=e?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=e?.querySelector(".rows-viewport"),this._bodyEl=e?.querySelector(".rows"),this.__rowsBodyEl=e?.querySelector(".rows-body"),this.#ie.isInitialized){Me(this.#L,this.#te),Le(this.#L,this.#s?.shell,this.#te);const e=this.#s?.shell?.toolPanel?.defaultOpen;e&&this.#te.toolPanels.has(e)&&(this.openToolPanel(),this.#te.expandedSections.add(e))}if(this.setAttribute("data-upgraded",""),this.#I=!0,this._resizeController=ge(this),this.#Se(),this.#Me(e),this.#Q)return;this.#Q=!0;const t=this.disconnectSignal;X(this,this,this.#L,t),this.#Te(),queueMicrotask(()=>this.#qe()),this.#O.requestPhase(he.FULL,"afterConnect")}#Te(){const e=this.#s.rowHeight,t=this.#X.hasRowHeightPlugin();"function"==typeof e||t?this._virtualization.variableHeights||(this._virtualization.variableHeights=!0,this._virtualization.rowHeight="number"==typeof e&&e>0?e:this._virtualization.rowHeight||28,this.#Ne(),"function"!=typeof e&&(this.#G=!0)):!t&&"function"!=typeof e&&this._virtualization.variableHeights?(this._virtualization.variableHeights=!1,this._virtualization.positionCache=null):"number"==typeof e&&e>0?(this._virtualization.rowHeight=e,this._virtualization.variableHeights=!1):requestAnimationFrame(()=>this.#Ge())}#Ge(){if(this.#X.hasExtraHeight())return;const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;const t=e.querySelectorAll(".cell");let i=0;t.forEach(e=>{const t=e.offsetHeight;t>i&&(i=t)});const n=e.getBoundingClientRect(),r=Math.max(n.height,i);r>0&&Math.abs(r-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=r,this.#O.requestPhase(he.VIRTUALIZATION,"measureRowHeight"))}#Ee(){const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;const t=e.querySelectorAll(".cell");let i=0;t.forEach(e=>{const t=e.offsetHeight;t>i&&(i=t)});const n=e.getBoundingClientRect(),r=Math.max(n.height,i);if(r>0){if(Math.abs(r-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=r),this.#Ne(),this._virtualization.totalHeightEl){const e=this.#ye(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}}#Me(e){this.#J?.abort(),this.#J=new AbortController;const t=this.#J.signal,i=e?.querySelector(".faux-vscroll"),n=e?.querySelector(".rows");if(this._virtualization.container=i??this,this.#N=this.#X?.getAll().some(e=>e.onScroll)??!1,i&&n){i.addEventListener("scroll",()=>{if(!this._virtualization.enabled&&!this.#N)return;const e=i.scrollTop,t=this._virtualization.rowHeight;if(this._rows.length<=this._virtualization.bypassThreshold)n.style.transform=`translateY(${-e}px)`;else{const i=this._virtualization.positionCache;let r,o;if(this._virtualization.variableHeights&&i&&i.length>0){r=et(i,e),-1===r&&(r=0);const n=r-r%2;o=i[n]?.offset??n*t}else{r=Math.floor(e/t);o=(r-r%2)*t}const s=-(e-o);n.style.transform=`translateY(${s}px)`}this.#q=e,this.#F||(this.#F=requestAnimationFrame(()=>{this.#F=0,null!==this.#q&&(this.#Ve(this.#q),this.#q=null)}))},{passive:!0,signal:t});const e=this.#L.querySelector(".tbw-scroll-area");this.#ee=e,this._virtualization.scrollAreaEl=e,e&&this.#N&&e.addEventListener("scroll",()=>{const t=this.#Y;t.scrollTop=i.scrollTop,t.scrollLeft=e.scrollLeft,t.scrollHeight=i.scrollHeight,t.scrollWidth=e.scrollWidth,t.clientHeight=i.clientHeight,t.clientWidth=e.clientWidth,this.#X?.onScroll(t)},{passive:!0,signal:t});const r=this.#L.querySelector(".tbw-grid-content"),o=this.#ee;r&&(r.addEventListener("wheel",e=>{const t=e.shiftKey||Math.abs(e.deltaX)>Math.abs(e.deltaY);if(t&&o){const t=e.shiftKey?e.deltaY:e.deltaX,{scrollLeft:i,scrollWidth:n,clientWidth:r}=o;(t>0&&i<n-r||t<0&&i>0)&&(e.preventDefault(),o.scrollLeft+=t)}else if(!t){const{scrollTop:t,scrollHeight:n,clientHeight:r}=i;(e.deltaY>0&&t<n-r||e.deltaY<0&&t>0)&&(e.preventDefault(),i.scrollTop+=e.deltaY)}},{passive:!1,signal:t}),We(r,this.#B,{fauxScrollbar:i,scrollArea:o},t))}var r,o,s;this._bodyEl&&(r=this,o=this._bodyEl,s=t,o.addEventListener("mousedown",e=>{const t=e.target.closest(".cell[data-col]");t&&(t.classList.contains("editing")||(e.preventDefault(),j(r,t)))},{signal:s}),o.addEventListener("click",e=>{const t=e.target.closest(".data-grid-row");if(t&&W(r,e,t),!document.activeElement?.closest(".cell.editing")){const t=e.target.closest("tbw-grid");t&&t.focus({preventScroll:!0})}},{signal:s}),o.addEventListener("dblclick",e=>{const t=e.target.closest(".data-grid-row");t&&W(r,e,t)},{signal:s})),this.#K?.disconnect(),this._virtualization.viewportEl&&(this.#K=new ResizeObserver(()=>{this.#$e(),this.#O.requestPhase(he.VIRTUALIZATION,"resize-observer")}),this.#K.observe(this._virtualization.viewportEl)),this.#L.addEventListener("focusin",()=>{this.dataset.hasFocus=""},{signal:t}),this.#L.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.#L.contains(t)||this.#Be(t))||delete this.dataset.hasFocus},{signal:t})}#Ce=!1;#xe(){if(this.#Ce)return;const e=this._bodyEl?.querySelector(".data-grid-row");e&&(this.#Ce=!0,this.#U?.disconnect(),this.#U=new ResizeObserver(()=>{this.#Ge()}),this.#U.observe(e))}addEventListener(e,t,i){super.addEventListener(e,t,i)}removeEventListener(e,t,i){super.removeEventListener(e,t,i)}#Re(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}#qe(){const e=this._bodyEl?.querySelectorAll(".data-grid-row");e?.forEach((e,t)=>{const i=t===this._focusRow;e.setAttribute("aria-selected",String(i)),e.querySelectorAll(".cell").forEach((e,t)=>{e.setAttribute("aria-selected",String(i&&t===this._focusCol))})})}#he(e){this.#z[e]=!0,this.#D||(this.#D=!0,queueMicrotask(()=>this.#We()))}#We(){if(!this.#D||!this.#I)return void(this.#D=!1);const e=this.#z;if(this.#D=!1,this.#z={rows:!1,columns:!1,gridConfig:!1,fitMode:!1},e.gridConfig)return this.#Ke(),void(e.rows&&this.#Ue());e.columns&&this.#je(),e.rows&&this.#Ue(),e.fitMode&&this.#Ye()}#Ue(){this._rows=Array.isArray(this.#P)?[...this.#P]:[],this.#Xe(),this.#O.requestPhase(he.ROWS,"applyRowsUpdate")}#Xe(){this.#de.clear();const e=this.#s.getRowId;this._rows.forEach((t,i)=>{const n=this.#Ze(t,e);void 0!==n&&this.#de.set(n,{row:t,index:i})})}#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}#Qe(e,t){const i=this.#Ze(e,t);if(void 0===i)throw new Error('[tbw-grid] Cannot determine row ID. Configure getRowId in gridConfig or ensure rows have an "id" property.');return i}#je(){V(this),this.#H.merge(),this.#Se()}#Ye(){this.#H.merge();"fixed"===this.#s.fitMode?(this.__didInitialAutoSize=!1,l(this)):(this._columns.forEach(e=>{!e.__userResized&&e.__autoSized&&delete e.width}),c(this))}#Ke(){Ae(this,this.#te),ke(this,this.#te);const e=!!this.#L.querySelector(".has-shell"),t=!!this.#L.querySelector(".tbw-tool-panel"),i=this.#L.querySelectorAll(".tbw-accordion-section").length;this.#H.parseLightDomColumns(this),this.#H.merge(),this.#we(),Te(this,this.#te,this.#He()),this.#H.markSourcesChanged(),this.#H.merge();const n=_e(this.#s?.shell),r=(this.#s?.shell?.toolPanels?.length??0)>0,o=this.#s?.shell?.toolPanels?.length??0;if(e!==n||!t&&r||t&&o!==i)return Ie(this.#te),this.#De(),this.#ke(),this.#ze(),void this.#Xe();e&&this.#Je(),this.#Xe(),this.#O.requestPhase(he.COLUMNS,"applyGridConfigUpdate")}#Je(){const e=this.#L.querySelector(".tbw-shell-header");if(!e)return;const t=this.#s.shell?.header?.title??this.#te.lightDomTitle;let i=e.querySelector(".tbw-shell-title");t?(i||(i=document.createElement("h2"),i.className="tbw-shell-title",i.setAttribute("part","shell-title"),e.insertBefore(i,e.firstChild)),i.textContent=t):i&&i.remove()}#be(){if(this.__rowRenderEpoch++,this.#X){const e=this.#ce.length>0?this.#ce:this._columns,t=e.filter(e=>!e.hidden),i=e.filter(e=>e.hidden),n=this.#X.processColumns([...t]);if(n!==t){const r=new Set(n.map(e=>e.field));!t.some(e=>r.has(e.field))&&n.length>0?this._columns=[...n,...i]:this._columns=this.#et(e,n,i)}else this._columns=[...e]}}#et(e,t,i){if(0===i.length)return t;const n=new Map;for(const l of t)n.set(l.field,l);const r=new Set(e.map(e=>e.field)),o=[];for(const l of t)r.has(l.field)||o.push(l);const s=[];for(const l of e){const e=n.get(l.field);e?s.push(e):l.hidden&&s.push(l)}return s.push(...o),s}#ve(){V(this);const e=function(e,t){if(!e._sortState)return t;e.__originalOrder=[...t];const i=(e.effectiveConfig?.sortHandler??Q)(t,e._sortState,e._columns);return i&&"function"==typeof i.then?t:i}(this,Array.isArray(this.#P)?[...this.#P]:[]),t=this.#X?.processRows(e)??e;this._rows=t,this.#Xe(),this._virtualization.variableHeights&&this.#Ne()}#_e(e){const t={...i,...e.animation},n=t.mode??"reduced-motion";let r=1;!1===n||"off"===n?r=0:!0!==n&&"on"!==n||(r=1),this.style.setProperty("--tbw-animation-duration",`${t.duration}ms`),this.style.setProperty("--tbw-animation-easing",t.easing??"ease-out"),this.style.setProperty("--tbw-animation-enabled",String(r)),this.dataset.animationMode="boolean"==typeof n?n?"on":"off":n}#tt(e,t,i=this.__rowRenderEpoch){if(this.#$||(this.#$=(e,t,i)=>this.#X?.renderRow(e,t,i)??!1),function(e,t,i,n,r){const o=Math.max(0,i-t),s=e._bodyEl,l=e._visibleColumns,a=l.length;let d=e.__cachedHeaderRowCount;for(void 0===d&&(d=e.querySelector(".header-group-row")?2:1,e.__cachedHeaderRowCount=d);e._rowPool.length<o;){const t=G();e._rowPool.push(t)}if(e._rowPool.length>o){for(let t=o;t<e._rowPool.length;t++){const i=e._rowPool[t];i.parentNode===s&&i.remove()}e._rowPool.length=o}const c=r&&!1!==e.__hasRenderRowPlugins,h=e._hasAfterRowRenderHook?.()??!1;for(let g=0;g<o;g++){const i=t+g,o=e._rows[i],p=e._rowPool[g];if(p.setAttribute("aria-rowindex",String(i+d+1)),c&&r(o,p,i)){p.__epoch=n,p.__rowDataRef=o,p.parentNode!==s&&s.appendChild(p);continue}const f=p.__epoch,w=p.__rowDataRef;let m=p.children.length;m>a&&p.lastElementChild?.classList.contains("tbw-row-loading-overlay")&&m--;const b=f===n&&m===a,v=w!==o,y=!!e._isGridEditMode;let C=!1;if(b&&v)for(let e=0;e<a;e++)if(l[e].externalView&&!p.querySelector(`.cell[data-col="${e}"] [data-external-view]`)){C=!0;break}if(!b||C){const t=z(p),r=y||e._activeEditRows===i;t&&!r?(p.__isCustomRow&&(p.className="data-grid-row",p.setAttribute("role","row"),p.__isCustomRow=!1),O(p),B(e,p,o,i),p.__epoch=n,p.__rowDataRef=o):t&&r?($(e,p,o,i),p.__rowDataRef=o):(p.__isCustomRow&&(p.className="data-grid-row",p.setAttribute("role","row"),p.__isCustomRow=!1),B(e,p,o,i),p.__epoch=n,p.__rowDataRef=o)}else if(v){const t=z(p),r=y||e._activeEditRows===i;t&&!r?(O(p),B(e,p,o,i),p.__epoch=n,p.__rowDataRef=o):($(e,p,o,i),p.__rowDataRef=o)}else{const t=z(p),r=y||e._activeEditRows===i;t&&!r?(O(p),B(e,p,o,i),p.__epoch=n,p.__rowDataRef=o):$(e,p,o,i)}let x=!1;const E=e.changedRowIds;if(E&&E.length>0)try{const t=e.getRowId?.(o);t&&(x=E.includes(t))}catch{}x!==p.classList.contains("changed")&&p.classList.toggle("changed",x);const R=e.effectiveConfig?.rowClass;if(R){const e=p.getAttribute("data-dynamic-classes");e&&e.split(" ").forEach(e=>e&&p.classList.remove(e));try{const e=R(o);if(e&&e.length>0){const t=e.filter(e=>e&&"string"==typeof e);t.forEach(e=>p.classList.add(e)),p.setAttribute("data-dynamic-classes",t.join(" "))}else p.removeAttribute("data-dynamic-classes")}catch(u){console.warn("[tbw-grid] rowClass callback error:",u),p.removeAttribute("data-dynamic-classes")}}h&&e._afterRowRender?.({row:o,rowIndex:i,rowElement:p}),p.parentNode!==s&&s.appendChild(p)}}(this,e,t,i,this.#$),this.#se.size>0)for(const n of this.#se)this.#ge(n,!0)}#it={rowCount:-1,colCount:-1,ariaLabel:void 0,ariaDescribedBy:void 0};#nt(e,t){!function(e,t,i,n,r){if(n===e.rowCount&&r===e.colCount)return!1;const o=e.rowCount;e.rowCount=n,e.colCount=r,t&&(t.setAttribute("aria-rowcount",String(n)),t.setAttribute("aria-colcount",String(r))),n!==o&&i&&(n>0?i.setAttribute("role","rowgroup"):i.removeAttribute("role"))}(this.#it,this.__rowsBodyEl,this._bodyEl,e,t)}#me(){!function(e,t,i,n){if(!t)return!1;let r=!1;const o=function(e,t){const i=e?.gridAriaLabel;return i||(e?.shell?.header?.title??t?.lightDomTitle??void 0)}(i,n);o!==e.ariaLabel&&(e.ariaLabel=o,o?t.setAttribute("aria-label",o):t.removeAttribute("aria-label"),r=!0);const s=i?.gridAriaDescribedBy;s!==e.ariaDescribedBy&&(e.ariaDescribedBy=s,s?t.setAttribute("aria-describedby",s):t.removeAttribute("aria-describedby"),r=!0)}(this.#it,this.__rowsBodyEl,this.#s,this.#te)}#ue(){const e=this.querySelector(".tbw-grid-root");var t;e&&(this.#oe?(this.#ae||(this.#ae=function(e){const t=document.createElement("div");return t.className="tbw-loading-overlay",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.appendChild(ce("large",e)),t}(this.#s?.loadingRenderer)),function(e,t){e.appendChild(t)}(e,this.#ae)):(t=this.#ae,t?.remove()))}#ge(e,t){const i=this.#de.get(e);if(!i)return;const n=this.findRenderedRowElement?.(i.index);n&&function(e,t){if(t){if(e.classList.add("tbw-row-loading"),e.setAttribute("aria-busy","true"),!e.querySelector(".tbw-row-loading-overlay")){const t=document.createElement("div");t.className="tbw-row-loading-overlay",t.setAttribute("aria-hidden","true");const i=document.createElement("div");i.className="tbw-row-loading-spinner",t.appendChild(i),e.appendChild(t)}}else e.classList.remove("tbw-row-loading"),e.removeAttribute("aria-busy"),e.querySelector(".tbw-row-loading-overlay")?.remove()}(n,t)}#pe(e,t,i){const n=this.#de.get(e);if(!n)return;const r=this.findRenderedRowElement?.(n.index);if(!r)return;const o=this._visibleColumns.findIndex(e=>e.field===t);if(o<0)return;const s=r.children[o];s&&function(e,t){t?(e.classList.add("tbw-cell-loading"),e.setAttribute("aria-busy","true")):(e.classList.remove("tbw-cell-loading"),e.removeAttribute("aria-busy"))}(s,i)}#Se(){if(this.isConnected&&this._headerRowEl&&this._bodyEl){if(this.#H.parseLightDomColumns(this),this.#h){const e=this.#h;this.#h=void 0,this.#H.merge();const t=this.#X?.getAll()??[];this.#H.applyState(e,t)}this._bodyEl&&(this._bodyEl.style.display="",this._bodyEl.style.gridTemplateColumns=""),this.#O.requestPhase(he.FULL,"setup")}}#Ve(e){let t=0,i=0,n=0,r=0,o=0;if(this.#N){const e=this._virtualization.container,s=this.#ee;t=s?.scrollLeft??0,i=e?.scrollHeight??0,n=s?.scrollWidth??0,r=e?.clientHeight??0,o=s?.clientWidth??0}if(this.refreshVirtualWindow(!1)&&this.#X?.onScrollRender(),this._virtualization.variableHeights&&(this.#V&&clearTimeout(this.#V),this.#V=window.setTimeout(()=>{this.#V=0,this.#rt(this._virtualization.start,this._virtualization.end)},100)),this.#N){const s=this.#Y;s.scrollTop=e,s.scrollLeft=t,s.scrollHeight=i,s.scrollWidth=n,s.clientHeight=r,s.clientWidth=o,this.#X?.onScroll(s)}}findHeaderRow(){return this.#L.querySelector(".header-row")}findRenderedRowElement(e){return Array.from(this._bodyEl.querySelectorAll(".data-grid-row")).find(t=>{const i=t.querySelector(".cell[data-row]");return i&&Number(i.getAttribute("data-row"))===e})||null}_dispatchCellClick(e,t,i,n){const r=this._rows[t],o=this._visibleColumns[i];if(!r||!o)return!1;const s=o.field,l=r[s],a=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,composed:!0,detail:{rowIndex:t,colIndex:i,column:o,field:s,value:l,row:r,cellEl:n,trigger:"pointer",originalEvent:e}});if(this.dispatchEvent(a),a.defaultPrevented)return!0;const d={row:r,rowIndex:t,colIndex:i,column:o,field:s,value:l,cellEl:n,originalEvent:e},c=this.#X?.onCellClick(d)??!1;return this.#Re("cell-click",d),c}_dispatchRowClick(e,t,i,n){if(!i)return!1;const r={rowIndex:t,row:i,rowEl:n,originalEvent:e},o=this.#X?.onRowClick(r)??!1;return this.#Re("row-click",r),o}_dispatchHeaderClick(e,t,i){if(!t)return!1;const n={colIndex:this._columns.indexOf(t),field:t.field,column:t,headerEl:i,originalEvent:e};return this.#X?.onHeaderClick(n)??!1}_dispatchKeyDown(e){return this.#X?.onKeyDown(e)??!1}_getHorizontalScrollOffsets(e,t){return this.#X?.getHorizontalScrollOffsets(e,t)??{left:0,right:0}}queryPlugins(e){return this.#X?.queryPlugins(e)??[]}query(e,t){return this.#X?.queryPlugins({type:e,context:t})??[]}_dispatchCellMouseDown(e){return this.#X?.onCellMouseDown(e)??!1}_dispatchCellMouseMove(e){this.#X?.onCellMouseMove(e)}_dispatchCellMouseUp(e){this.#X?.onCellMouseUp(e)}_afterCellRender(e){this.#X?.afterCellRender(e)}_hasAfterCellRenderHook(){return this.#X?.hasAfterCellRenderHook()??!1}_afterRowRender(e){this.#X?.afterRowRender(e)}_hasAfterRowRenderHook(){return this.#X?.hasAfterRowRenderHook()??!1}async ready(){return this.#E}async forceLayout(){return this.#O.requestPhase(he.FULL,"forceLayout"),this.#O.whenReady()}async getConfig(){return Object.freeze({...this.#s||{}})}getRowId(e){return this.#Qe(e,this.#s.getRowId)}getRow(e){return this.#de.get(e)?.row}_getRowEntry(e){return this.#de.get(e)}updateRow(e,t,i="api"){const n=this.#de.get(e);if(!n)throw new Error(`[tbw-grid] Row with ID "${e}" not found. Ensure the row exists and getRowId is correctly configured.`);const{row:r,index:o}=n,s=[];for(const[l,a]of Object.entries(t)){const e=r[l];e!==a&&(s.push({field:l,oldValue:e,newValue:a}),r[l]=a)}for(const{field:l,oldValue:a,newValue:d}of s)this.#Re("cell-change",{row:r,rowId:e,rowIndex:o,field:l,oldValue:a,newValue:d,changes:t,source:i});s.length>0&&this.#O.requestPhase(he.ROWS,"updateRow")}updateRows(e,t="api"){let i=!1;for(const{id:n,changes:r}of e){const e=this.#de.get(n);if(!e)throw new Error(`[tbw-grid] Row with ID "${n}" not found. Ensure the row exists and getRowId is correctly configured.`);const{row:o,index:s}=e;for(const[l,a]of Object.entries(r)){const e=o[l];e!==a&&(i=!0,o[l]=a,this.#Re("cell-change",{row:o,rowId:n,rowIndex:s,field:l,oldValue:e,newValue:a,changes:r,source:t}))}}i&&this.#O.requestPhase(he.ROWS,"updateRows")}animateRow(e,t){return be(this,e,t)}animateRows(e,t){return function(e,t,i){return Promise.all(t.map(t=>be(e,t,i))).then(e=>e.filter(Boolean).length)}(this,e,t)}animateRowById(e,t){return function(e,t,i){const n=e._rows??[],r=e.getRowId;if(!r)return Promise.resolve(!1);const o=n.findIndex(e=>{if(null==e)return!1;try{return r(e)===t}catch{return!1}});return o<0?Promise.resolve(!1):be(e,o,i)}(this,e,t)}async insertRow(e,t,i=!0){const n=Math.max(0,Math.min(e,this._rows.length));this.#P=[...this.#P,t];const r=[...this._rows];r.splice(n,0,t),this._rows=r,this._sortState&&(this.__originalOrder=[...this.__originalOrder,t]),V(this),this.#Xe(),this.__rowRenderEpoch++;for(const o of this._rowPool)o.__epoch=-1;this.refreshVirtualWindow(!0),i&&(await new Promise(e=>requestAnimationFrame(()=>e())),await this.animateRow(n,"insert"))}async removeRow(e,t=!0){const i=this._rows[e];if(!i)return;t&&await this.animateRow(e,"remove");const n=this._rows.indexOf(i);if(n<0)return i;const r=[...this._rows];r.splice(n,1),this._rows=r;const o=this.#P.indexOf(i);if(o>=0){const e=[...this.#P];e.splice(o,1),this.#P=e}if(this._sortState){const e=this.__originalOrder.indexOf(i);if(e>=0){const t=[...this.__originalOrder];t.splice(e,1),this.__originalOrder=t}}V(this),this.#Xe(),this.__rowRenderEpoch++;for(const s of this._rowPool)s.__epoch=-1;return this.refreshVirtualWindow(!0),t&&requestAnimationFrame(()=>{this.querySelectorAll('[data-animating="remove"]').forEach(e=>{e.removeAttribute("data-animating")})}),i}suspendProcessing(){}setColumnVisible(e,t){const i=this.#H.setColumnVisible(e,t);return i&&this.requestStateChange(),i}toggleColumnVisibility(e){const t=this.#H.toggleColumnVisibility(e);return t&&this.requestStateChange(),t}isColumnVisible(e){return this.#H.isColumnVisible(e)}showAllColumns(){this.#H.showAllColumns(),this.requestStateChange()}getAllColumns(){return this.#H.getAllColumns()}setColumnOrder(e){this.#H.setColumnOrder(e),this.requestStateChange()}getColumnOrder(){return this.#H.getColumnOrder()}getColumnState(){const e=this.#X?.getAll()??[];return this.#H.collectState(e)}set columnState(e){e&&(this.#h=e,this.#H.initialColumnState=e,this.#M&&this.#ot(e))}get columnState(){return this.getColumnState()}#ot(e){const t=this.#X?.getAll()??[];this.#H.applyState(e,t),this.#Se()}requestStateChange(){const e=this.#X?.getAll()??[];this.#H.requestStateChange(e)}resetColumnState(){this.#h=void 0,this.__originalOrder=[];const e=this.#X?.getAll()??[];this.#H.resetState(e),this.#H.merge(),this.#Se()}get isToolPanelOpen(){return this.#ie.isPanelOpen}get defaultRowHeight(){return this._virtualization.rowHeight}get expandedToolPanelSections(){return this.#ie.expandedSections}openToolPanel(){this.#ie.openToolPanel()}closeToolPanel(){this.#ie.closeToolPanel()}toggleToolPanel(){this.#ie.toggleToolPanel()}toggleToolPanelSection(e){this.#ie.toggleToolPanelSection(e)}getToolPanels(){return this.#ie.getToolPanels()}registerToolPanel(e){this.#te.apiToolPanelIds.add(e.id),this.#ie.registerToolPanel(e)}unregisterToolPanel(e){this.#te.apiToolPanelIds.delete(e),this.#ie.unregisterToolPanel(e)}getHeaderContents(){return this.#ie.getHeaderContents()}registerHeaderContent(e){this.#ie.registerHeaderContent(e)}unregisterHeaderContent(e){this.#ie.unregisterHeaderContent(e)}getToolbarContents(){return this.#ie.getToolbarContents()}registerToolbarContent(e){this.#ie.registerToolbarContent(e)}unregisterToolbarContent(e){this.#ie.unregisterToolbarContent(e)}#st=!1;refreshShellHeader(){this.#st||(this.#st=!0,queueMicrotask(()=>{this.#st=!1,this.isConnected&&(this.#Ie(),this.#H.markSourcesChanged(),this.#H.merge(),Ie(this.#te),this.#De(),this.#ke(),this.#lt())}))}#lt(){const e=this.#L.querySelector(".tbw-grid-content")??this.#L.querySelector(".tbw-grid-root");if(this._headerRowEl=e?.querySelector(".header-row"),this._virtualization.totalHeightEl=e?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=e?.querySelector(".rows-viewport"),this._bodyEl=e?.querySelector(".rows"),this.__rowsBodyEl=e?.querySelector(".rows-body"),this.#ie.isInitialized){Me(this.#L,this.#te),Le(this.#L,this.#s?.shell,this.#te);const e=this.#s?.shell?.toolPanel?.defaultOpen;e&&this.#te.toolPanels.has(e)&&(this.openToolPanel(),this.#te.expandedSections.add(e))}this._resizeController=ge(this),this.#Me(e),this.#O.requestPhase(he.COLUMNS,"shellRefresh")}#Fe=new Map;registerStyles(e,t){let i=this.#Fe.get(e);i||(i=new CSSStyleSheet,this.#Fe.set(e,i)),i.replaceSync(t),this.#at()}unregisterStyles(e){this.#Fe.delete(e)&&this.#at()}getRegisteredStyles(){return Array.from(this.#Fe.keys())}#at(){const e=Array.from(this.#Fe.values()),t=document.adoptedStyleSheets.filter(e=>!Array.from(this.#Fe.values()).includes(e));document.adoptedStyleSheets=[...t,...e]}#dt=new Set;#ct=new Map;registerExternalFocusContainer(e){if(this.#dt.has(e))return;this.#dt.add(e);const t=new AbortController,i=t.signal;e.addEventListener("focusin",()=>{this.dataset.hasFocus=""},{signal:i}),e.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&this.containsFocus(t)||delete this.dataset.hasFocus},{signal:i}),this.#ct.set(e,()=>t.abort())}unregisterExternalFocusContainer(e){this.#dt.delete(e);const t=this.#ct.get(e);t&&(t(),this.#ct.delete(e))}containsFocus(e){const t=e??document.activeElement;return!!t&&(!!this.contains(t)||this.#Be(t))}#Be(e){for(const t of this.#dt)if(t.contains(e))return!0;return!1}#Ie(){Ae(this,this.#te),ke(this,this.#te),Te(this,this.#te,this.#He())}#ht(){const e=this.#L.querySelector(".tbw-shell-header");if(!e)return;Ie(this.#te);const t=function(e,t,i="☰"){const n=e?.header?.title??t.lightDomTitle??"",r=!!n,o=Se(i),s=e?.header?.toolbarContents??[],l=[...t.toolbarContents.values()],a=new Set(s.map(e=>e.id)),d=[...s];for(const w of l)a.has(w.id)||d.push(w);const c=d.length>0,h=t.toolPanels.size>0,u=c&&h,g=[...d].sort((e,t)=>(e.order??0)-(t.order??0));let p="";for(const w of g)p+=`<div class="tbw-toolbar-content-slot" data-toolbar-content="${w.id}"></div>`;if(u&&(p+='<div class="tbw-toolbar-separator"></div>'),h){const e=t.isPanelOpen;p+=`<button class="${e?"tbw-toolbar-btn active":"tbw-toolbar-btn"}" data-panel-toggle title="Settings" aria-label="Toggle settings panel" aria-pressed="${e}" aria-controls="tbw-tool-panel">${o}</button>`}return`\n <div class="tbw-shell-header" part="shell-header" role="presentation">\n ${r?`<div class="tbw-shell-title">${f=n,f&&"string"==typeof f?f.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"):""}</div>`:""}\n <div class="tbw-shell-content" part="shell-content" role="presentation" data-light-dom-header-content></div>\n <div class="tbw-shell-toolbar" part="shell-toolbar" role="presentation">\n ${p}\n </div>\n </div>\n `;var f}(this.#s.shell,this.#te,this.#s.icons?.toolPanel),i=document.createElement("div");i.innerHTML=t;const n=i.firstElementChild;n&&(e.replaceWith(n),this.#ut(),Le(this.#L,this.#s?.shell,this.#te))}#Oe(){const e=()=>{const e=this.#te.lightDomTitle,t=this.#te.hasToolButtonsContainer;this.#Ie();const i=this.#te.lightDomTitle,n=this.#te.hasToolButtonsContainer;(i&&!e||n&&!t)&&(this.#H.markSourcesChanged(),this.#H.merge(),this.#ht())},t=()=>{this.__lightDomColumnsCache=void 0,this.#Se()};this.#H.registerLightDomHandler("tbw-grid-header",e),this.#H.registerLightDomHandler("tbw-grid-tool-buttons",e),this.#H.registerLightDomHandler("tbw-grid-tool-panel",e),this.#H.registerLightDomHandler("tbw-grid-column",t),this.#H.registerLightDomHandler("tbw-grid-detail",t),this.#H.observeLightDOM(this)}refreshColumns(){this.__lightDomColumnsCache=void 0,V(this),this.#H.parseLightDomColumns(this);const e=this.#te.lightDomTitle,t=this.#te.hasToolButtonsContainer;this.#Ie();const i=this.#te.lightDomTitle,n=this.#te.hasToolButtonsContainer;(i&&!e||n&&!t)&&(this.#H.markSourcesChanged(),this.#H.merge(),this.#ht()),this.#O.requestPhase(he.COLUMNS,"refreshColumns")}#$e(){const e=this._virtualization.container,t=this._virtualization.viewportEl??e;t&&(this._virtualization.cachedViewportHeight=t.clientHeight),e&&(this._virtualization.cachedFauxHeight=e.clientHeight);const i=this._virtualization.scrollAreaEl;i&&(this._virtualization.cachedScrollAreaHeight=i.clientHeight)}#ye(e,t=!1){const i=this._virtualization;let n,r,o;if(t){const e=i.container??this,t=i.viewportEl??e,s=i.scrollAreaEl;n=e.clientHeight,r=t.clientHeight,o=s?s.clientHeight:n,i.cachedFauxHeight=n,i.cachedViewportHeight=r,i.cachedScrollAreaHeight=o}else n=i.cachedFauxHeight,r=i.cachedViewportHeight,o=i.cachedScrollAreaHeight||n;const s=o-r,l=Math.max(0,n-o);let a,d=0;i.variableHeights&&i.positionCache?a=function(e){if(0===e.length)return 0;const t=e[e.length-1];return t.offset+t.height}(i.positionCache):(a=e*i.rowHeight,d=this.#X?.getExtraHeight()??0);return a+s+d+l}#Ne(){if(!this._virtualization.variableHeights)return;const e=this._rows,t=this._virtualization.rowHeight||28,i=this.#s.rowHeight,n=this.#s.getRowId,r=n?e=>n(e):void 0;this._virtualization.positionCache=function(e,t,i,n,r){const o=new Array(e.length);let s=0;for(let l=0;l<e.length;l++){const a=e[l];let d=r?.(a,l),c=void 0!==d;void 0===d&&(d=Qe(t,a,n.rowId),c=void 0!==d),void 0===d&&(d=i,c=!1),o[l]={offset:s,height:d,measured:c},s+=d}return o}(e,this._virtualization.heightCache,t,{rowId:r},(e,t)=>{const n=this.#X?.getRowHeight?.(e,t);if(void 0!==n)return n;if(i){const n=i(e,t);if(void 0!==n&&n>0)return n}});const o=function(e,t,i,n){let r=0,o=0;for(let s=0;s<e.length;s++){const i=e[s];if(i.measured){const e=n?.(t[s],s);void 0===e&&(o+=i.height,r++)}}return{measuredCount:r,averageHeight:r>0?o/r:i}}(this._virtualization.positionCache,e,t,(e,t)=>this.#X?.getRowHeight?.(e,t));this._virtualization.measuredCount=o.measuredCount,o.measuredCount>0&&(this._virtualization.averageHeight=o.averageHeight)}invalidateRowHeight(e,t){if(!this._virtualization.variableHeights)return;if(!this._virtualization.positionCache)return;if(e<0||e>=this._rows.length)return;const i=this._virtualization.positionCache,n=this._rows[e];let r=t;void 0===r&&(r=this.#X?.getRowHeight?.(n,e)),void 0===r&&(r=this._virtualization.rowHeight);const o=i[e];if(o&&!(Math.abs(o.height-r)<1)&&(Je(i,e,r),this._virtualization.totalHeightEl)){const e=this.#ye(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}#rt(e,t){if(!this._virtualization.variableHeights)return;if(!this._virtualization.positionCache)return;if(!this._bodyEl)return;const i=this._bodyEl.querySelectorAll(".data-grid-row"),n=this.#s.getRowId,r=tt({positionCache:this._virtualization.positionCache,heightCache:this._virtualization.heightCache,rows:this._rows,defaultHeight:this._virtualization.rowHeight,start:e,end:t,getPluginHeight:(e,t)=>this.#X?.getRowHeight?.(e,t),getRowId:n?e=>n(e):void 0},i);if(r.hasChanges&&(this._virtualization.measuredCount=r.measuredCount,this._virtualization.averageHeight=r.averageHeight,this._virtualization.totalHeightEl)){const e=this.#ye(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}refreshVirtualWindow(e=!1,t=!1){if(!this._bodyEl)return!1;const i=this._rows.length;if(!this._virtualization.enabled)return this.#tt(0,i),t||this.#X?.afterRender(),!0;if(this._rows.length<=this._virtualization.bypassThreshold)return this._virtualization.start=0,this._virtualization.end=i,e&&(this._bodyEl.style.transform="translateY(0px)"),this.#tt(0,i,this.__rowRenderEpoch),e&&this._virtualization.totalHeightEl&&(this._virtualization.totalHeightEl.style.height=`${this.#ye(i,!0)}px`),this.#nt(i,this._visibleColumns.length),t||this.#X?.afterRender(),!0;const n=this._virtualization.container??this,r=this._virtualization.viewportEl??n,o=e?this._virtualization.cachedViewportHeight=r.clientHeight:this._virtualization.cachedViewportHeight||(this._virtualization.cachedViewportHeight=r.clientHeight),s=this._virtualization.rowHeight,l=n.scrollTop;let a;const d=this._virtualization.positionCache;if(this._virtualization.variableHeights&&d&&d.length>0)a=et(d,l),-1===a&&(a=0);else{a=Math.floor(l/s);let e=0;const t=10;for(;e<t;){const t=this.#X?.getExtraHeightBefore?.(a)??0,i=Math.floor((l-t)/s);if(i>=a||i<0)break;a=i,e++}}a-=a%2,a<0&&(a=0);const c=this.#X?.adjustVirtualStart(a,l,s);let h;if(void 0!==c&&c<a&&(a=c,a-=a%2,a<0&&(a=0)),this._virtualization.variableHeights&&d&&d.length>0){const e=o+3*s;let t=0;for(h=a;h<i&&t<e;)t+=d[h].height,h++;const n=Math.ceil(o/s)+3;h-a<n&&(h=Math.min(a+n,i))}else{h=a+(Math.ceil(o/s)+3)}h>i&&(h=i);const u=this._virtualization.start,g=this._virtualization.end;if(!e&&a===u&&h===g)return!1;this._virtualization.start=a,this._virtualization.end=h;const p=e?this._virtualization.cachedFauxHeight=n.clientHeight:this._virtualization.cachedFauxHeight||(this._virtualization.cachedFauxHeight=n.clientHeight);if(e){const e=this._virtualization.scrollAreaEl;e&&(this._virtualization.cachedScrollAreaHeight=e.clientHeight)}if(0===p&&o>0)return this.#O.requestPhase(he.VIRTUALIZATION,"stale-refs-retry"),!1;if(e&&this._virtualization.totalHeightEl){const e=this.#ye(i);this._virtualization.totalHeightEl.style.height=`${e}px`}let f;if(this._virtualization.variableHeights&&d&&d[a])f=d[a].offset;else{f=a*s+(this.#X?.getExtraHeightBefore?.(a)??0)}const w=-(l-f);return this._bodyEl.style.transform=`translateY(${w}px)`,this.#tt(a,h,this.__rowRenderEpoch),e&&this._virtualization.variableHeights&&this.#rt(a,h),this.#nt(i,this._visibleColumns.length),e&&!t&&(this.#X?.afterRender(),queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const e=this.#ye(i);0===this._virtualization.cachedFauxHeight&&this._virtualization.cachedViewportHeight>0||(this._virtualization.totalHeightEl.style.height=`${e}px`)})),!0}#De(){this.#Ie(),this.#H.markSourcesChanged(),this.#H.merge();const e=this.#s?.shell;Oe(this.#L,e,{isPanelOpen:this.#te.isPanelOpen,expandedSections:this.#te.expandedSections},this.#s?.icons)&&(this.#ut(),this.#ie.setInitialized(!0))}#ut(){!function(e,t,i,n){const r=e.querySelector(".tbw-shell-toolbar");r&&r.addEventListener("click",e=>{e.target.closest("[data-panel-toggle]")&&n.onPanelToggle()});const o=e.querySelector(".tbw-accordion");o&&o.addEventListener("click",e=>{const t=e.target.closest(".tbw-accordion-header");if(t){const e=t.closest("[data-section]"),i=e?.getAttribute("data-section");i&&n.onSectionToggle(i)}})}(this.#L,this.#s,this.#te,{onPanelToggle:()=>this.toggleToolPanel(),onSectionToggle:e=>this.toggleToolPanelSection(e)}),this.#ne?.(),this.#ne=function(e,t,i){const n=e.querySelector(".tbw-tool-panel"),r=e.querySelector("[data-resize-handle]"),o=e.querySelector(".tbw-shell-body");if(!n||!r||!o)return()=>{};const s=t?.toolPanel?.position??"right";let l=0,a=0,d=0,c=!1;const h=e=>{if(!c)return;e.preventDefault();const t="left"===s?e.clientX-l:l-e.clientX,i=Math.min(d,Math.max(200,a+t));n.style.width=`${i}px`},u=()=>{if(!c)return;c=!1,r.classList.remove("resizing"),n.style.transition="",document.body.style.cursor="",document.body.style.userSelect="";const e=n.getBoundingClientRect().width;i(e),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",u)},g=e=>{e.preventDefault(),c=!0,l=e.clientX,a=n.getBoundingClientRect().width,d=o.getBoundingClientRect().width-20,r.classList.add("resizing"),n.style.transition="none",document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",h),document.addEventListener("mouseup",u)};return r.addEventListener("mousedown",g),()=>{r.removeEventListener("mousedown",g),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",u)}}(this.#L,this.#s?.shell,e=>{this.style.setProperty("--tbw-tool-panel-width",`${e}px`)}),this.#re?.(),this.#re=function(e,t,i,n){if(!t?.toolPanel?.closeOnClickOutside)return()=>{};const r=e=>{if(!i.isPanelOpen)return;const t=e.target;t&&(t.closest(".tbw-tool-panel")||t.closest("[data-panel-toggle]")||n())};return e.addEventListener("mousedown",r),()=>e.removeEventListener("mousedown",r)}(this,this.#s?.shell,this.#te,()=>this.closeToolPanel())}}customElements.get(nt.tagName)||customElements.define(nt.tagName,nt),globalThis.DataGridElement=nt;class rt{static dependencies;static manifest;version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#gt;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}attach(e){this.#gt?.abort(),this.#gt=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#gt?.abort(),this.#gt=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const i=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(i),i.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid}get disconnectSignal(){return this.#gt?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...r,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),i=parseInt(t,10);if(!isNaN(i))return i}return 200}resolveIcon(e,t){return void 0!==t?t:this.gridIcons[e]}setIcon(e,t){"string"==typeof t?e.innerHTML=t:t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}warn(e){console.warn(`[tbw-grid:${this.name}] ${e}`)}}const ot={ROOT:"tbw-grid-root",HEADER:"header",HEADER_ROW:"header-row",HEADER_CELL:"header-cell",ROWS_VIEWPORT:"rows-viewport",ROWS_SPACER:"rows-spacer",ROWS_CONTAINER:"rows",DATA_ROW:"data-row",GROUP_ROW:"group-row",DATA_CELL:"data-cell",SELECTED:"selected",FOCUSED:"focused",EDITING:"editing",EXPANDED:"expanded",COLLAPSED:"collapsed",DRAGGING:"dragging",RESIZING:"resizing",SORTABLE:"sortable",SORTED_ASC:"sorted-asc",SORTED_DESC:"sorted-desc",HIDDEN:"hidden",STICKY_LEFT:"sticky-left",STICKY_RIGHT:"sticky-right",PINNED_TOP:"pinned-top",PINNED_BOTTOM:"pinned-bottom",TREE_TOGGLE:"tree-toggle",TREE_INDENT:"tree-indent",GROUP_TOGGLE:"group-toggle",GROUP_LABEL:"group-label",GROUP_COUNT:"group-count",RANGE_SELECTION:"range-selection",SELECTION_OVERLAY:"selection-overlay"},st={ROW_INDEX:"data-row-index",COL_INDEX:"data-col-index",FIELD:"data-field",GROUP_KEY:"data-group-key",TREE_LEVEL:"data-tree-level",STICKY:"data-sticky"},lt={ROOT:`.${ot.ROOT}`,HEADER:`.${ot.HEADER}`,HEADER_ROW:`.${ot.HEADER_ROW}`,HEADER_CELL:`.${ot.HEADER_CELL}`,ROWS_VIEWPORT:`.${ot.ROWS_VIEWPORT}`,ROWS_CONTAINER:`.${ot.ROWS_CONTAINER}`,DATA_ROW:`.${ot.DATA_ROW}`,DATA_CELL:`.${ot.DATA_CELL}`,GROUP_ROW:`.${ot.GROUP_ROW}`,ROW_BY_INDEX:e=>`.${ot.DATA_ROW}[${st.ROW_INDEX}="${e}"]`,CELL_BY_FIELD:e=>`.${ot.DATA_CELL}[${st.FIELD}="${e}"]`,CELL_AT:(e,t)=>`.${ot.DATA_ROW}[${st.ROW_INDEX}="${e}"] .${ot.DATA_CELL}[${st.COL_INDEX}="${t}"]`,SELECTED_ROWS:`.${ot.DATA_ROW}.${ot.SELECTED}`,EDITING_CELL:`.${ot.DATA_CELL}.${ot.EDITING}`};function at(e,t,i=!0){let n=e;if(i&&(n=n.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.meta?.utility)),t?.length){const e=new Set(t);n=n.filter(t=>e.has(t.field))}return n}function dt(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}function ct(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}function ht(e,t){const i=t.delimiter??"\t",n=t.newline??"\n",r=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),o=[];let s=[],l="",a=!1;for(let d=0;d<r.length;d++){const e=r[d];'"'!==e||a?'"'===e&&a?'"'===r[d+1]?(l+='"',d++):a=!1:e!==i||a?e!==n||a?l+=e:(s.push(l),l="",(s.length>1||s.some(e=>""!==e.trim()))&&o.push(s),s=[]):(s.push(l),l=""):a=!0}return s.push(l),(s.length>1||s.some(e=>""!==e.trim()))&&o.push(s),o}function ut(e,t){const{rows:i,target:n,fields:r}=e;if(!n)return;const o=t.rows,s=t.effectiveConfig.columns??[],l=s.map(e=>e.field),a=new Map;s.forEach(e=>{a.set(e.field,!0===e.editable)});const d=[...o],c=n.bounds?n.bounds.endRow:1/0;i.forEach((e,t)=>{const i=n.row+t;if(!(i>c)){if(n.bounds){if(i>=d.length)return}else for(;i>=d.length;){const e={};l.forEach(t=>e[t]=""),d.push(e)}d[i]={...d[i]},e.forEach((e,t)=>{const n=r[t];n&&a.get(n)&&(d[i][n]=e)})}}),t.rows=d}function gt(e){if(null==e)return 100;if("number"==typeof e)return e;const t=parseFloat(e);return isNaN(t)?100:t}function pt(e){return e.map(e=>gt(e.width))}function ft(e){const t=[];let i=0;for(const n of e)t.push(i),i+=gt(n.width);return t}function wt(e){return e.reduce((e,t)=>e+gt(t.width),0)}function mt(e,t,i,n,r){const o=i.length;if(0===o)return{startCol:0,endCol:0,visibleColumns:[]};let s=function(e,t,i){let n=0,r=t.length-1;for(;n<r;){const o=Math.floor((n+r)/2);t[o]+i[o]<=e?n=o+1:r=o}return n}(e,i,n);s=Math.max(0,s-r);const l=e+t;let a=s;for(let c=s;c<o;c++){if(i[c]>=l){a=c-1;break}a=c}a=Math.min(o-1,a+r);const d=[];for(let c=s;c<=a;c++)d.push(c);return{startCol:s,endCol:a,visibleColumns:d}}const bt="@layer tbw-plugins{.tbw-context-menu{position:fixed;background:var(--tbw-context-menu-bg, var(--tbw-color-panel-bg));color:var(--tbw-context-menu-fg, var(--tbw-color-fg));border:1px solid var(--tbw-context-menu-border, var(--tbw-color-border));border-radius:var(--tbw-context-menu-radius, var(--tbw-border-radius));box-shadow:var(--tbw-context-menu-shadow, 0 2px 10px var(--tbw-color-shadow));min-width:var(--tbw-context-menu-min-width, var(--tbw-menu-min-width));padding:var(--tbw-spacing-xs) 0;z-index:10000;font-size:var(--tbw-context-menu-font-size, var(--tbw-font-size-sm));font-family:var(--tbw-context-menu-font-family, var(--tbw-font-family))}.tbw-context-menu-item{display:flex;align-items:center;padding:var(--tbw-context-menu-item-padding, var(--tbw-menu-item-padding));cursor:pointer;gap:var(--tbw-context-menu-item-gap, var(--tbw-menu-item-gap))}.tbw-context-menu-item:hover:not(.disabled){background:var(--tbw-context-menu-hover, var(--tbw-color-row-hover))}.tbw-context-menu-item.disabled{opacity:.5;cursor:default}.tbw-context-menu-item.danger{color:var(--tbw-context-menu-danger, var(--tbw-color-danger))}.tbw-context-menu-icon{width:var(--tbw-context-menu-icon-size, var(--tbw-icon-size));text-align:center}.tbw-context-menu-label{flex:1}.tbw-context-menu-shortcut kbd{color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted));font-size:var(--tbw-context-menu-shortcut-size, var(--tbw-font-size-xs))}.tbw-context-menu-arrow{font-size:var(--tbw-context-menu-arrow-size, var(--tbw-font-size-2xs));color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted))}.tbw-context-menu-separator{height:1px;background:var(--tbw-context-menu-border, var(--tbw-color-border));margin:var(--tbw-spacing-xs) 0}}";function vt(e,t){return("function"==typeof e?e(t):e).filter(e=>!0!==e.hidden&&("function"!=typeof e.hidden||!e.hidden(t)))}function yt(e){const t=[];for(const i of e)i.separator&&(0===t.length||t[t.length-1].separator)||t.push(i);return t.length>0&&t[t.length-1].separator&&t.pop(),t}function Ct(e,t){return!0===e.disabled||"function"==typeof e.disabled&&e.disabled(t)}function xt(e,t,i,n=r.submenuArrow){const o=document.createElement("div");o.className="tbw-context-menu",o.setAttribute("role","menu");const s=e.some(e=>!e.separator&&e.icon);for(const r of e){if(r.separator){const e=document.createElement("div");e.className="tbw-context-menu-separator",e.setAttribute("role","separator"),o.appendChild(e);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",r.cssClass&&e.classList.add(r.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",r.id);const l=Ct(r,t);if(l&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),r.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=r.icon,e.appendChild(t)}else if(s){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML="&nbsp;",e.appendChild(t)}const a=document.createElement("span");if(a.className="tbw-context-menu-label",a.textContent=r.name,e.appendChild(a),r.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(r.shortcut))r.shortcut.forEach((e,i)=>{i>0&&t.appendChild(document.createTextNode("+"));const n=document.createElement("kbd");n.textContent=e,t.appendChild(n)});else{const e=document.createElement("kbd");e.textContent=r.shortcut,t.appendChild(e)}e.appendChild(t)}if(r.subMenu?.length){const o=document.createElement("span");o.className="tbw-context-menu-arrow","string"==typeof n?o.innerHTML=n:n instanceof HTMLElement&&o.appendChild(n.cloneNode(!0)),e.appendChild(o),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!r.subMenu)return;const o=xt(vt(r.subMenu,t),t,i,n);o.classList.add("tbw-context-submenu"),o.style.position="absolute",o.style.left="100%",o.style.top="0",e.style.position="relative",e.appendChild(o)}),e.addEventListener("mouseleave",()=>{const t=e.querySelector(".tbw-context-menu");t&&t.remove()})}l||!r.action||r.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),i(r)}),o.appendChild(e)}return o}function Et(e,t,i){e.style.position="fixed",e.style.left=`${t}px`,e.style.top=`${i}px`,e.style.visibility="hidden",e.style.zIndex="10000";const n=e.getBoundingClientRect(),r=window.innerWidth,o=window.innerHeight;let s=t,l=i;t+n.width>r&&(s=t-n.width),i+n.height>o&&(l=i-n.height),s=Math.max(0,s),l=Math.max(0,l),e.style.left=`${s}px`,e.style.top=`${l}px`,e.style.visibility="visible"}const Rt="getContextMenuItems";let St=null,_t=null,At=null,kt=0;const Tt=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:e=>{const t=e.grid;t?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:e=>{const t=e.grid;t?.plugins?.export?.exportCsv?.()}}];class Lt extends rt{static manifest={queries:[{type:Rt,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:Tt}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),kt++}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,this.uninstallGlobalHandlers()}syncSelectionOnContextMenu(e){if(e<0)return[];const t=this.grid?.query("getSelectedRowIndices"),i=t?.[0];return i?i.includes(e)?i:(this.grid?.query("selectRows",[e]),[e]):[e]}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size"];copyGridStyles(e){const t=this.gridElement;if(!t)return;const i=getComputedStyle(t),n=[],r=i.getPropertyValue("color-scheme").trim();r&&n.push(`color-scheme: ${r}`);for(const o of Lt.CSS_VARS_TO_COPY){const e=i.getPropertyValue(o).trim();e&&n.push(`${o}: ${e}`)}if(n.length>0){const t=e.getAttribute("style")||"";e.setAttribute("style",t+n.join("; ")+";")}}installGlobalHandlers(){!At&&"undefined"!=typeof document&&bt&&(At=document.createElement("style"),At.id="tbw-context-menu-styles",At.textContent=bt,document.head.appendChild(At)),St||(St=()=>{document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())},document.addEventListener("click",St)),_t||(_t=e=>{if("Escape"===e.key){document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())}},document.addEventListener("keydown",_t))}uninstallGlobalHandlers(){kt--,kt>0||(St&&(document.removeEventListener("click",St),St=null),_t&&(document.removeEventListener("keydown",_t),_t=null),At&&(At.remove(),At=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(Rt,e),i=[];for(const n of t)Array.isArray(n)&&i.push(...n);return i.sort((e,t)=>(e.order??100)-(t.order??100)),this.insertGroupSeparators(i)}insertGroupSeparators(e){if(e.length<=1)return e;const t=[];let i=-1;for(const n of e){if(n.separator){t.push(n);continue}const e=Math.floor((n.order??100)/10);i>=0&&e!==i&&t.push({id:`__sep-${i}-${e}`,label:"",separator:!0,action:()=>{}}),i=e,t.push(n)}return t}convertPluginItems(e){return e.map(e=>({id:e.id,name:e.label,icon:e.icon,shortcut:e.shortcut,disabled:e.disabled??!1,action:()=>e.action(),separator:e.separator,cssClass:e.cssClass}))}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root");t&&"true"!==t.getAttribute("data-context-menu-bound")&&(t.setAttribute("data-context-menu-bound","true"),t.addEventListener("contextmenu",e=>{const t=e;t.preventDefault();const i=t.target,n=i.closest("[data-row][data-col]"),r=i.closest('[part~="header-cell"]');let o;if(n){const e=parseInt(n.getAttribute("data-row")??"-1",10),i=parseInt(n.getAttribute("data-col")??"-1",10),r=this.visibleColumns[i],s=this.rows[e],l=this.syncSelectionOnContextMenu(e);o={row:s,rowIndex:e,column:r,columnIndex:i,field:r?.field??"",value:s?.[r?.field]??null,isHeader:!1,event:t,selectedRows:l}}else{if(!r)return;{const e=parseInt(r.getAttribute("data-col")??"-1",10),i=this.visibleColumns[e];o={row:null,rowIndex:-1,column:i,columnIndex:e,field:i?.field??"",value:null,isHeader:!0,event:t,selectedRows:[]}}}this.params=o,this.position={x:t.clientX,y:t.clientY};const s=this.collectPluginItems(o);let l=vt(this.config.items??Tt,o);if(s.length>0){const e=this.convertPluginItems(s);l=l.length>0&&e.length>0?[...l,{id:"__plugin-sep",name:"",separator:!0},...e]:[...l,...e]}l=yt(l),l.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=xt(l,o,e=>{e.action&&e.action(o),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),Et(this.menuElement,t.clientX,t.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:o,items:l}))}))}showMenu(e,t,i){const n={row:i.row??null,rowIndex:i.rowIndex??-1,column:i.column??null,columnIndex:i.columnIndex??-1,field:i.field??"",value:i.value??null,isHeader:i.isHeader??!1,event:i.event??new MouseEvent("contextmenu"),selectedRows:i.selectedRows??[]},r=this.collectPluginItems(n);let o=vt(this.config.items??Tt,n);if(r.length>0){const e=this.convertPluginItems(r);o=o.length>0&&e.length>0?[...o,{id:"__plugin-sep",name:"",separator:!0},...e]:[...o,...e]}o=yt(o),this.menuElement&&this.menuElement.remove(),this.menuElement=xt(o,n,e=>{e.action&&e.action(n),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),Et(this.menuElement,e,t),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}function Mt(e){switch(e.type){case"number":return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");n.type="number",n.value=null!=t.value?String(t.value):"",void 0!==i?.min&&(n.min=String(i.min)),void 0!==i?.max&&(n.max=String(i.max)),void 0!==i?.step&&(n.step=String(i.step)),i?.placeholder&&(n.placeholder=i.placeholder);const r=()=>t.commit(""===n.value?null:Number(n.value));return n.addEventListener("blur",r),n.addEventListener("keydown",e=>{"Enter"===e.key&&r(),"Escape"===e.key&&t.cancel()}),n}}(e);case"boolean":return e=>{const t=document.createElement("input");return t.type="checkbox",t.checked=!!e.value,t.addEventListener("change",()=>e.commit(t.checked)),t};case"date":return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");return n.type="date",t.value instanceof Date?n.valueAsDate=t.value:"string"==typeof t.value&&t.value&&(n.value=t.value.split("T")[0]),i?.min&&(n.min=i.min),i?.max&&(n.max=i.max),i?.placeholder&&(n.placeholder=i.placeholder),n.addEventListener("change",()=>{"string"==typeof t.value?t.commit(n.value):t.commit(n.valueAsDate)}),n.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),n}}(e);case"select":return function(e){return t=>{const i=e.editorParams,n=document.createElement("select");if(e.multi&&(n.multiple=!0),i?.includeEmpty){const e=document.createElement("option");e.value="",e.textContent=i.emptyLabel??"",n.appendChild(e)}const r=function(e){const t=e.options;return t?"function"==typeof t?t():t:[]}(e);r.forEach(i=>{const r=document.createElement("option");r.value=String(i.value),r.textContent=i.label,e.multi&&Array.isArray(t.value)&&t.value.includes(i.value)?r.selected=!0:e.multi||t.value!==i.value||(r.selected=!0),n.appendChild(r)});const o=()=>{if(e.multi){const e=Array.from(n.selectedOptions).map(e=>e.value);t.commit(e)}else t.commit(n.value)};return n.addEventListener("change",o),n.addEventListener("blur",o),n.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),n}}(e);default:return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");n.type="text",n.value=null!=t.value?String(t.value):"",void 0!==i?.maxLength&&(n.maxLength=i.maxLength),i?.pattern&&(n.pattern=i.pattern),i?.placeholder&&(n.placeholder=i.placeholder);const r=()=>{const e=n.value;(null!==t.value&&void 0!==t.value||""!==e)&&("string"==typeof t.value&&e===t.value.replace(/[\n\r]/g,"")||("number"==typeof t.value&&""!==e?t.commit(Number(e)):t.commit(e)))};return n.addEventListener("blur",r),n.addEventListener("keydown",e=>{"Enter"===e.key&&r(),"Escape"===e.key&&t.cancel()}),n}}(e)}}function Pt(e){return"string"==typeof e&&("__proto__"!==e&&"constructor"!==e&&"prototype"!==e)}function Ht(e,t,i){return e instanceof HTMLInputElement?"checkbox"===e.type?e.checked:"number"===e.type?""===e.value?null:Number(e.value):"date"===e.type?"string"==typeof i?e.value:e.valueAsDate:"number"==typeof i?""===e.value?null:Number(e.value):null==i&&""===e.value||"string"==typeof i&&e.value===i.replace(/[\n\r]/g,"")?i:e.value:"number"===t?.type&&""!==e.value||"number"==typeof i&&""!==e.value?Number(e.value):null==i&&""===e.value?i:e.value}function It(e){}function Dt(e,t=!0){if(null==e)return"";if(e instanceof Date)return e.toISOString();if("object"==typeof e)return JSON.stringify(e);const i=String(e);return t&&(i.includes(",")||i.includes('"')||i.includes("\n")||i.includes("\r"))?`"${i.replace(/"/g,'""')}"`:i}function zt(e,t){const i=URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(i)}function Ot(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}const Ft="(Blank)";function qt(e){if(e instanceof Date)return e.getTime();const t=Number(e);if(!isNaN(t))return t;return new Date(e).getTime()}function Nt(e,t,i=!1,n){return t.length?e.filter(e=>t.every(t=>function(e,t,i=!1,n){const r=e[t.field];if("blank"===t.operator)return null==r||""===r;if("notBlank"===t.operator)return null!=r&&""!==r;if(n&&("notIn"===t.operator||"in"===t.operator)){const i=n(r,e),o=Array.isArray(i)?i:null!=i?[i]:[];if("notIn"===t.operator){const e=t.value;return!Array.isArray(e)||(0===o.length?!e.includes(Ft):!o.some(t=>e.includes(t)))}if("in"===t.operator){const e=t.value;return!!Array.isArray(e)&&(0===o.length?e.includes(Ft):o.some(t=>e.includes(t)))}}if("notIn"===t.operator)return null==r||""===r?!Array.isArray(t.value)||!t.value.includes(Ft):Array.isArray(t.value)&&!t.value.includes(r);if("in"===t.operator)return null==r||""===r?Array.isArray(t.value)&&t.value.includes(Ft):Array.isArray(t.value)&&t.value.includes(r);if(null==r)return!1;const o=String(r),s=i?o:o.toLowerCase(),l=i?String(t.value):String(t.value).toLowerCase();switch(t.operator){case"contains":return s.includes(l);case"notContains":return!s.includes(l);case"equals":return s===l;case"notEquals":return s!==l;case"startsWith":return s.startsWith(l);case"endsWith":return s.endsWith(l);case"lessThan":return qt(r)<qt(t.value);case"lessThanOrEqual":return qt(r)<=qt(t.value);case"greaterThan":return qt(r)>qt(t.value);case"greaterThanOrEqual":return qt(r)>=qt(t.value);case"between":return qt(r)>=qt(t.value)&&qt(r)<=qt(t.valueTo);default:return!0}}(e,t,i,n?.get(t.field)))):e}function Gt(e,t,i){const n=new Set;let r=!1;for(const o of e){const e=o[t];if(i){const t=i(e,o);if(Array.isArray(t)){0===t.length&&(r=!0);for(const e of t)null!=e&&n.add(e)}else null!=t?n.add(t):r=!0}else null!=e&&""!==e?n.add(e):r=!0}return r&&n.add(Ft),[...n].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t)))}function Vt(e,t){const i=new Map;for(const{field:r,filterValue:o}of t)i.set(r,{values:new Set,hasBlank:!1,hasExtractor:!!o});for(const r of e)for(const{field:e,filterValue:n}of t){const t=i.get(e),o=r[e];if(n){const e=n(o,r);if(Array.isArray(e)){0===e.length&&(t.hasBlank=!0);for(const i of e)null!=i&&t.values.add(i)}else null!=e?t.values.add(e):t.hasBlank=!0}else null!=o&&""!==o?t.values.add(o):t.hasBlank=!0}const n=new Map;for(const[r,{values:o,hasBlank:s}]of i)s&&o.add(Ft),n.set(r,[...o].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t))));return n}const $t="__tbw_expander";function Bt(e){return e.field===$t}function Wt(e){return!0===e.meta?.utility}class Kt extends rt{static manifest={events:[{type:"filter-applied",description:"Emitted when filter criteria change. Subscribers can react to row visibility changes."}],queries:[{type:"getContextMenuItems",description:"Contributes filter-related items to the header context menu"}]};name="filtering";styles='@layer tbw-plugins{tbw-grid .tbw-quick-filter-input{flex:1;max-width:300px;height:var(--tbw-input-height, 1.75rem);padding:var(--tbw-input-padding, 0 .5rem);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);background:var(--tbw-color-bg);color:var(--tbw-color-fg);font-size:var(--tbw-font-size-sm, .8125rem)}tbw-grid .tbw-quick-filter-input:focus{outline:none;border-color:var(--tbw-color-accent)}tbw-grid .header-cell.filtered:before{content:"";position:absolute;top:var(--tbw-spacing-xs, .25rem);right:var(--tbw-spacing-xs, .25rem);width:var(--tbw-indicator-size, .375rem);height:var(--tbw-indicator-size, .375rem);background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border-radius:50%}tbw-grid .tbw-filter-btn{display:var(--tbw-filter-btn-display, inline-flex);visibility:var(--tbw-filter-btn-visibility, visible);align-items:center;justify-content:center;background:transparent;border:none;cursor:pointer;padding:2px;margin-left:var(--tbw-spacing-xs, .25rem);opacity:.4;transition:opacity .15s,visibility 0s,display 0s allow-discrete;color:inherit;vertical-align:middle;transition-behavior:allow-discrete}tbw-grid .tbw-filter-btn:hover,tbw-grid .tbw-filter-btn.active{opacity:1;visibility:visible;display:inline-flex}tbw-grid .tbw-filter-btn.active{color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6))}tbw-grid .header-row .cell:hover .tbw-filter-btn,tbw-grid .header-row .cell.filtered .tbw-filter-btn{display:inline-flex;visibility:visible}}';get defaultConfig(){return{debounceMs:300,caseSensitive:!1,trimInput:!0,useWorker:!0}}isFilteringEnabled(){return!1!==this.grid.effectiveConfig?.filterable}isColumnFilterable(e){return!!this.isFilteringEnabled()&&!1!==e.filterable}getFilterValues(){const e=this.grid.effectiveConfig?.columns;if(!e)return;let t;for(const i of e)i.field&&i.filterValue&&(t||(t=new Map),t.set(i.field,i.filterValue));return t}filters=new Map;cachedResult=null;cacheKey=null;cachedInputSpot=null;openPanelField=null;panelElement=null;panelAnchorElement=null;searchText=new Map;excludedValues=new Map;panelAbortController=null;globalStylesInjected=!1;static DEFAULT_LIST_ITEM_HEIGHT=28;static LIST_OVERSCAN=3;static LIST_BYPASS_THRESHOLD=50;getListItemHeight(){if(this.panelElement){const e=getComputedStyle(this.panelElement).getPropertyValue("--tbw-filter-item-height");if(e&&e.trim()){const t=parseFloat(e);if(!isNaN(t)&&t>0)return t}}return Kt.DEFAULT_LIST_ITEM_HEIGHT}computeSelected(){const e=[];for(const[n,r]of this.filters){if("set"!==r.type||"notIn"!==r.operator)continue;const t=this.grid.effectiveConfig?.columns?.find(e=>e.field===n);e.push({field:n,filterValue:t?.filterValue})}if(0===e.length)return{};const t=Vt(this.sourceRows,e),i={};for(const{field:n}of e){const e=this.excludedValues.get(n),r=t.get(n)??[];i[n]=e?r.filter(t=>!e.has(t)):r}return i}syncExcludedValues(e,t){t?"set"===t.type&&"notIn"===t.operator&&Array.isArray(t.value)?this.excludedValues.set(e,new Set(t.value)):"set"===t.type&&this.excludedValues.delete(e):this.excludedValues.delete(e)}attach(e){super.attach(e),this.injectGlobalStyles()}detach(){this.filters.clear(),this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,this.openPanelField=null,this.panelElement&&(this.panelElement.remove(),this.panelElement=null),this.searchText.clear(),this.excludedValues.clear(),this.panelAbortController?.abort(),this.panelAbortController=null}handleQuery(e){if("getContextMenuItems"===e.type){const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field)return;if(!this.isFilteringEnabled())return;if(!this.isColumnFilterable(i))return;const n=[],r=this.isFieldFiltered(i.field),o=this.filters.size>0;return r&&n.push({id:"filtering/clear-column-filter",label:"Clear Filter",icon:"✕",order:20,action:()=>this.clearFieldFilter(i.field)}),o&&n.push({id:"filtering/clear-all-filters",label:"Clear All Filters",icon:"✕",order:21,disabled:!o,action:()=>this.clearAllFilters()}),n.length>0?n:void 0}}processRows(e){const t=[...this.filters.values()];if(!t.length)return[...e];if(this.config.filterHandler)return this.cachedResult?this.cachedResult:[...e];const i=(n=t,JSON.stringify(n.map(e=>({field:e.field,operator:e.operator,value:e.value,valueTo:e.valueTo}))));var n;const r={len:e.length,first:e[0],mid:e[Math.floor(e.length/2)],last:e[e.length-1]},o=null!=this.cachedInputSpot&&r.len===this.cachedInputSpot.len&&r.first===this.cachedInputSpot.first&&r.mid===this.cachedInputSpot.mid&&r.last===this.cachedInputSpot.last;if(this.cacheKey===i&&this.cachedResult&&o)return this.cachedResult;const s=Nt([...e],t,this.config.caseSensitive,this.getFilterValues());return this.cachedResult=s,this.cacheKey=i,this.cachedInputSpot=r,s}afterRender(){const e=this.gridElement;if(!e)return;e.querySelectorAll('[part~="header-cell"]').forEach(e=>{const t=e.getAttribute("data-col");if(null===t)return;const i=this.visibleColumns[parseInt(t,10)];if(!i||!this.isColumnFilterable(i))return;if(Wt(i))return;const n=i.field;if(!n)return;const r=this.filters.has(n);let o=e.querySelector(".tbw-filter-btn");if(o){const t=o.classList.contains("active");if(o.classList.toggle("active",r),e.classList.toggle("filtered",r),t!==r){const e=r?"filterActive":"filter";this.setIcon(o,this.resolveIcon(e))}return}o=document.createElement("button"),o.className="tbw-filter-btn",o.setAttribute("aria-label",`Filter ${i.header??n}`);const s=r?"filterActive":"filter";this.setIcon(o,this.resolveIcon(s)),r&&(o.classList.add("active"),e.classList.add("filtered")),o.addEventListener("click",e=>{e.stopPropagation(),this.toggleFilterPanel(n,i,o)});const l=e.querySelector(".resize-handle");l?e.insertBefore(o,l):e.appendChild(o)})}setFilter(e,t){if(null===t)this.filters.delete(e),this.syncExcludedValues(e,null);else{const i={...t,field:e};this.filters.set(e,i),this.syncExcludedValues(e,i)}this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:[...this.filters.values()]}),this.requestRender()}getFilter(e){return this.filters.get(e)}getFilters(){return[...this.filters.values()]}getFilterModel(){return this.getFilters()}setFilterModel(e){this.filters.clear(),this.excludedValues.clear();for(const t of e)this.filters.set(t.field,t),this.syncExcludedValues(t.field,t);this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:[...this.filters.values()]}),this.requestRender()}clearAllFilters(){this.filters.clear(),this.excludedValues.clear(),this.searchText.clear(),this.applyFiltersInternal()}clearFieldFilter(e){this.filters.delete(e),this.excludedValues.delete(e),this.searchText.delete(e),this.applyFiltersInternal()}isFieldFiltered(e){return this.filters.has(e)}getFilteredRowCount(){return this.cachedResult?.length??this.rows.length}getActiveFilters(){return this.getFilters()}getUniqueValues(e){const t=this.grid.effectiveConfig?.columns?.find(t=>t.field===e),i=t?.filterValue;return Gt(this.sourceRows,e,i)}copyGridThemeContext(e){const t=this.gridElement;if(!t)return;for(const n of t.classList)n.startsWith("tbw-")||"selecting"===n||e.classList.add(n);const i=t.dataset.theme;i&&(e.dataset.theme=i)}injectGlobalStyles(){if(this.globalStylesInjected)return;if(document.getElementById("tbw-filter-panel-styles"))return void(this.globalStylesInjected=!0);const e=document.createElement("style");e.id="tbw-filter-panel-styles",e.textContent="@layer tbw-plugins{.tbw-filter-panel{position:fixed;background:var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));color:var(--tbw-filter-panel-fg, var(--tbw-color-fg, light-dark(#222222, #eeeeee)));border:1px solid var(--tbw-filter-panel-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-panel-radius, var(--tbw-border-radius, .25rem));box-shadow:0 4px 16px var(--tbw-filter-panel-shadow, var(--tbw-color-shadow, light-dark(rgba(0, 0, 0, .1), rgba(0, 0, 0, .3))));padding:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));z-index:10000;min-width:200px;max-width:280px;max-height:350px;display:flex;flex-direction:column;font-family:var(--tbw-font-family, system-ui, sans-serif);font-size:var(--tbw-font-size, .8125rem);transform-origin:top center}.tbw-filter-panel.tbw-filter-panel-above{transform-origin:bottom center}.tbw-filter-panel.tbw-filter-panel-animated{animation:tbw-filter-panel-enter var(--tbw-animation-duration, .15s) var(--tbw-animation-easing, ease-out)}.tbw-filter-panel.tbw-filter-panel-above.tbw-filter-panel-animated{animation:tbw-filter-panel-enter-above var(--tbw-animation-duration, .15s) var(--tbw-animation-easing, ease-out)}@keyframes tbw-filter-panel-enter{0%{opacity:0;transform:scaleY(.3) translateY(-10px)}to{opacity:1;transform:scaleY(1) translateY(0)}}@keyframes tbw-filter-panel-enter-above{0%{opacity:0;transform:scaleY(.3) translateY(10px)}to{opacity:1;transform:scaleY(1) translateY(0)}}@supports (anchor-name: --test){.tbw-filter-panel{position-anchor:--tbw-filter-anchor;top:anchor(bottom);left:anchor(left);margin-top:4px;position-try-fallbacks:flip-inline,flip-block,flip-block flip-inline}}.tbw-filter-search{margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));min-height:var(--tbw-filter-item-height, 28px)}.tbw-filter-search-input{height:var(--tbw-filter-item-height, 28px);width:100%;padding:var(--tbw-filter-search-padding, var(--tbw-spacing-sm, .375rem) var(--tbw-spacing-md, .5rem));background:var(--tbw-filter-input-bg, var(--tbw-color-bg, transparent));color:inherit;border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-input-radius, var(--tbw-border-radius, .25rem));font-size:inherit;box-sizing:border-box}.tbw-filter-search-input:focus{outline:none;border-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));box-shadow:0 0 0 2px rgba(from var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6)) r g b / 15%)}.tbw-filter-actions{display:flex;padding:var(--tbw-button-padding-sm, .25rem .125rem);margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border-bottom:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));min-height:var(--tbw-filter-item-height, 28px)}.tbw-filter-actions .tbw-filter-value-item{flex:1}.tbw-filter-values{flex:1;overflow-y:auto;margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));max-height:180px;position:relative}.tbw-filter-values-spacer{width:1px}.tbw-filter-values-content{position:absolute;top:0;left:0;right:0}.tbw-filter-value-item{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding-sm, .25rem .125rem);cursor:pointer;border-radius:3px;height:var(--tbw-filter-item-height, 28px)}.tbw-filter-value-item:hover{background:var(--tbw-filter-hover, var(--tbw-color-row-hover, light-dark(#f0f6ff, #1c1c1c)))}.tbw-filter-checkbox{margin:0;cursor:pointer;accent-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6))}.tbw-filter-no-match{color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem)) 0;text-align:center;font-style:italic}.tbw-filter-buttons{display:flex;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding-top:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border-top:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)))}.tbw-filter-apply-btn{flex:1;padding:var(--tbw-filter-btn-padding, var(--tbw-button-padding, .375rem .75rem));background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));color:var(--tbw-filter-accent-fg, var(--tbw-color-accent-fg, light-dark(#ffffff, #000000)));border:none;border-radius:var(--tbw-border-radius, .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);font-weight:var(--tbw-filter-btn-font-weight, 500);min-height:var(--tbw-filter-btn-min-height, auto)}.tbw-filter-apply-btn:hover{filter:brightness(.9)}.tbw-filter-clear-btn{flex:1;padding:var(--tbw-filter-btn-padding, var(--tbw-button-padding, .375rem .75rem));background:transparent;color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-border-radius, .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);font-weight:var(--tbw-filter-btn-font-weight, 500);min-height:var(--tbw-filter-btn-min-height, auto)}.tbw-filter-clear-btn:hover{background:var(--tbw-filter-hover, var(--tbw-color-row-hover, light-dark(#f0f6ff, #1c1c1c)))}.tbw-filter-range-inputs,.tbw-filter-date-range{display:flex;align-items:flex-end;gap:var(--tbw-spacing-sm, .375rem);margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-filter-range-group,.tbw-filter-date-group{display:flex;flex-direction:column;gap:var(--tbw-spacing-xs, .25rem);flex:1}.tbw-filter-range-label{font-size:var(--tbw-font-size-xs, .75rem);color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)))}.tbw-filter-range-input,.tbw-filter-date-input{width:100%;height:var(--tbw-filter-item-height, 28px);padding:var(--tbw-spacing-xs, .25rem) var(--tbw-spacing-sm, .375rem);background:var(--tbw-filter-input-bg, var(--tbw-color-bg, transparent));color:inherit;border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-input-radius, var(--tbw-border-radius, .25rem));font-size:inherit;box-sizing:border-box}.tbw-filter-range-input:focus,.tbw-filter-date-input:focus{outline:none;border-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));box-shadow:0 0 0 2px rgba(from var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6)) r g b / 15%)}.tbw-filter-range-separator{color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));padding-bottom:var(--tbw-spacing-xs, .25rem)}.tbw-filter-blank-option{display:flex;align-items:center;gap:var(--tbw-spacing-sm, .375rem);padding:var(--tbw-spacing-xs, .25rem) 0;margin-bottom:var(--tbw-spacing-xs, .25rem);font-size:var(--tbw-font-size-sm, .8125rem);cursor:pointer;-webkit-user-select:none;user-select:none}.tbw-filter-blank-checkbox{accent-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));margin:0;cursor:pointer}.tbw-filter-date-range.tbw-filter-disabled,.tbw-filter-range-inputs.tbw-filter-disabled,.tbw-filter-range-slider.tbw-filter-disabled{opacity:.4;pointer-events:none}.tbw-filter-range-slider{position:relative;height:24px;margin:var(--tbw-spacing-md, .5rem) 0 var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-filter-range-track{position:absolute;top:50%;left:0;right:0;height:4px;background:var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:2px;transform:translateY(-50%)}.tbw-filter-range-fill{position:absolute;top:50%;height:4px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border-radius:2px;transform:translateY(-50%)}.tbw-filter-range-thumb{position:absolute;top:0;width:100%;height:100%;background:none;pointer-events:none;-webkit-appearance:none;appearance:none}.tbw-filter-range-thumb::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:16px;height:16px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border:2px solid var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));border-radius:50%;cursor:pointer;pointer-events:all;box-shadow:0 1px 3px #0003}.tbw-filter-range-thumb::-moz-range-thumb{width:16px;height:16px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border:2px solid var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));border-radius:50%;cursor:pointer;pointer-events:all;box-shadow:0 1px 3px #0003}.tbw-filter-range-thumb::-webkit-slider-thumb:hover{transform:scale(1.1)}.tbw-filter-range-thumb::-moz-range-thumb:hover{transform:scale(1.1)}}",document.head.appendChild(e),this.globalStylesInjected=!0}toggleFilterPanel(e,t,i){if(this.openPanelField===e)return void this.closeFilterPanel();this.closeFilterPanel();const n=document.createElement("div");if(n.className="tbw-filter-panel",this.copyGridThemeContext(n),this.isAnimationEnabled&&n.classList.add("tbw-filter-panel-animated"),this.panelElement=n,this.openPanelField=e,this.config.valuesHandler)return n.innerHTML='<div class="tbw-filter-loading">Loading...</div>',document.body.appendChild(n),this.positionPanel(n,i),this.setupPanelCloseHandler(n,i),void this.config.valuesHandler(e,t).then(i=>{this.openPanelField===e&&this.panelElement&&(n.innerHTML="",this.renderPanelContent(e,t,n,i))});const r=Gt(this.sourceRows,e,t.filterValue);document.body.appendChild(n),this.positionPanel(n,i),this.renderPanelContent(e,t,n,r),this.setupPanelCloseHandler(n,i)}renderPanelContent(e,t,i,n){let r=this.excludedValues.get(e);r||(r=new Set,this.excludedValues.set(e,r));const o=this.searchText.get(e)??"",s={field:e,column:t,uniqueValues:n,excludedValues:r,searchText:o,currentFilter:this.filters.get(e),applySetFilter:(t,i)=>{this.applySetFilter(e,t,i),this.closeFilterPanel()},applyTextFilter:(t,i,n)=>{this.applyTextFilter(e,t,i,n),this.closeFilterPanel()},clearFilter:()=>{this.clearFieldFilter(e),this.closeFilterPanel()},closePanel:()=>this.closeFilterPanel()};let l=!1;if(this.config.filterPanelRenderer&&(this.config.filterPanelRenderer(i,s),l=i.children.length>0),!l&&t.type){const e=this.grid.effectiveConfig.typeDefaults?.[t.type];e?.filterPanelRenderer&&(e.filterPanelRenderer(i,s),l=i.children.length>0)}if(!l){const e=t.type;"number"===e?this.renderNumberFilterPanel(i,s,n):"date"===e?this.renderDateFilterPanel(i,s,n):this.renderDefaultFilterPanel(i,s,n,r)}}setupPanelCloseHandler(e,t){this.panelAbortController=new AbortController,setTimeout(()=>{document.addEventListener("click",i=>{e.contains(i.target)||i.target===t||this.closeFilterPanel()},{signal:this.panelAbortController?.signal})},0)}closeFilterPanel(){const e=this.panelElement;e&&(e.remove(),this.panelElement=null),this.panelAnchorElement&&(this.panelAnchorElement.style.anchorName="",this.panelAnchorElement=null),this.openPanelField=null,this.panelAbortController?.abort(),this.panelAbortController=null}static supportsAnchorPositioning=null;static checkAnchorPositioningSupport(){return null===Kt.supportsAnchorPositioning&&(Kt.supportsAnchorPositioning=CSS.supports("anchor-name","--test")),Kt.supportsAnchorPositioning}positionPanel(e,t){const i=t.closest(".cell")??t;if(i.style.anchorName="--tbw-filter-anchor",this.panelAnchorElement=i,Kt.checkAnchorPositioningSupport())return void requestAnimationFrame(()=>{const t=e.getBoundingClientRect(),n=i.getBoundingClientRect();t.top<n.top&&e.classList.add("tbw-filter-panel-above")});const n=i.getBoundingClientRect();e.style.position="fixed",e.style.top=`${n.bottom+4}px`,e.style.left=`${n.left}px`,requestAnimationFrame(()=>{const t=e.getBoundingClientRect();t.right>window.innerWidth-8&&(e.style.left=n.right-t.width+"px"),t.bottom>window.innerHeight-8&&(e.style.top=n.top-t.height-4+"px",e.classList.add("tbw-filter-panel-above"))})}renderDefaultFilterPanel(e,t,i,n){const{field:r,column:o}=t,s=this.getListItemHeight(),l=e=>{if(null==e)return"(Blank)";if(o.format&&!o.filterValue){const t=o.format(e,void 0);if(t)return t}return String(e)};i=i.slice().sort((e,t)=>l(e).localeCompare(l(t)));const a=document.createElement("div");a.className="tbw-filter-search";const d=document.createElement("input");d.type="text",d.placeholder="Search...",d.className="tbw-filter-search-input",d.value=this.searchText.get(r)??"",a.appendChild(d),e.appendChild(a);const c=document.createElement("div");c.className="tbw-filter-actions";const h=document.createElement("label");h.className="tbw-filter-value-item",h.style.padding="0",h.style.margin="0";const u=document.createElement("input");u.type="checkbox",u.className="tbw-filter-checkbox";const g=document.createElement("span");g.textContent="Select All",h.appendChild(u),h.appendChild(g),c.appendChild(h);const p=()=>{const e=[...b.values()],t=e.every(e=>e),i=e.every(e=>!e);u.checked=t,u.indeterminate=!t&&!i};u.addEventListener("change",()=>{const e=u.checked;for(const t of b.keys())b.set(t,e);p(),C()}),e.appendChild(c);const f=document.createElement("div");f.className="tbw-filter-values";const w=document.createElement("div");w.className="tbw-filter-values-spacer",f.appendChild(w);const m=document.createElement("div");m.className="tbw-filter-values-content",f.appendChild(m);const b=new Map;i.forEach(e=>{const t=null==e?"__null__":String(e);b.set(t,!n.has(e))}),p();let v=[];const y=(e,t)=>{const i=l(e),n=null==e?"__null__":String(e),r=document.createElement("label");r.className="tbw-filter-value-item",r.style.position="absolute",r.style.top=`calc(var(--tbw-filter-item-height, 28px) * ${t})`,r.style.left="0",r.style.right="0",r.style.boxSizing="border-box";const o=document.createElement("input");o.type="checkbox",o.className="tbw-filter-checkbox",o.checked=b.get(n)??!0,o.dataset.value=n,o.addEventListener("change",()=>{b.set(n,o.checked),p()});const s=document.createElement("span");return s.textContent=i,r.appendChild(o),r.appendChild(s),r},C=()=>{const e=v.length,t=f.clientHeight,i=f.scrollTop;if(w.style.height=e*s+"px",n=e,r=Kt.LIST_BYPASS_THRESHOLD/3,n<=r)return m.innerHTML="",m.style.transform="translateY(0px)",void v.forEach((e,t)=>{m.appendChild(y(e,t))});var n,r;const o=function(e){const{totalRows:t,viewportHeight:i,scrollTop:n,rowHeight:r,overscan:o}=e,s=Math.ceil(i/r);let l=Math.floor(n/r)-o;l<0&&(l=0);let a=l+s+2*o;return a>t&&(a=t),a===t&&l>0&&(l=Math.max(0,a-s-2*o)),{start:l,end:a,offsetY:l*r,totalHeight:t*r}}({totalRows:e,viewportHeight:t,scrollTop:i,rowHeight:s,overscan:Kt.LIST_OVERSCAN});m.style.transform=`translateY(${o.offsetY}px)`,m.innerHTML="";for(let s=o.start;s<o.end;s++)m.appendChild(y(v[s],s-o.start))},x=e=>{const t=this.config.caseSensitive??!1,n=t?e:e.toLowerCase();if(v=i.filter(i=>{const r=l(i),o=t?r:r.toLowerCase();return!e||o.includes(n)}),0===v.length){w.style.height="0px",m.innerHTML="";const e=document.createElement("div");return e.className="tbw-filter-no-match",e.textContent="No matching values",void m.appendChild(e)}C()};let E;f.addEventListener("scroll",()=>{v.length>0&&C()},{passive:!0}),x(d.value),e.appendChild(f),d.addEventListener("input",()=>{clearTimeout(E),E=setTimeout(()=>{this.searchText.set(r,d.value),x(d.value)},this.config.debounceMs??150)});const R=document.createElement("div");R.className="tbw-filter-buttons";const S=document.createElement("button");S.className="tbw-filter-apply-btn",S.textContent="Apply",S.addEventListener("click",()=>{const e=[];for(const[t,n]of b)if(!n)if("__null__"===t)e.push(null);else{const n=i.find(e=>String(e)===t);e.push(void 0!==n?n:t)}t.applySetFilter(e)}),R.appendChild(S);const _=document.createElement("button");_.className="tbw-filter-clear-btn",_.textContent="Clear Filter",_.addEventListener("click",()=>{t.clearFilter()}),R.appendChild(_),e.appendChild(R)}renderNumberFilterPanel(e,t,i){const{field:n,column:r}=t,o=r.filterParams,s=r.editorParams,l=(e,t)=>{if("number"==typeof e)return e;if("string"==typeof e){const i=parseFloat(e);return isNaN(i)?t:i}return t},a=i.filter(e=>"number"==typeof e&&!isNaN(e)),d=a.length>0?Math.min(...a):0,c=a.length>0?Math.max(...a):100,h=l(o?.min??s?.min,d),u=l(o?.max??s?.max,c),g=o?.step??s?.step??1,p=this.filters.get(n);let f=h,w=u;const m="blank"===p?.operator;"between"===p?.operator?(f=l(p.value,h),w=l(p.valueTo,u)):"greaterThanOrEqual"===p?.operator?f=l(p.value,h):"lessThanOrEqual"===p?.operator&&(w=l(p.value,u));const b=document.createElement("div");b.className="tbw-filter-range-inputs";const v=document.createElement("div");v.className="tbw-filter-range-group";const y=document.createElement("label");y.textContent="Min",y.className="tbw-filter-range-label";const C=document.createElement("input");C.type="number",C.className="tbw-filter-range-input",C.min=String(h),C.max=String(u),C.step=String(g),C.value=String(f),v.appendChild(y),v.appendChild(C),b.appendChild(v);const x=document.createElement("span");x.className="tbw-filter-range-separator",x.textContent="–",b.appendChild(x);const E=document.createElement("div");E.className="tbw-filter-range-group";const R=document.createElement("label");R.textContent="Max",R.className="tbw-filter-range-label";const S=document.createElement("input");S.type="number",S.className="tbw-filter-range-input",S.min=String(h),S.max=String(u),S.step=String(g),S.value=String(w),E.appendChild(R),E.appendChild(S),b.appendChild(E),e.appendChild(b);const _=document.createElement("div");_.className="tbw-filter-range-slider";const A=document.createElement("div");A.className="tbw-filter-range-track";const k=document.createElement("div");k.className="tbw-filter-range-fill";const T=document.createElement("input");T.type="range",T.className="tbw-filter-range-thumb tbw-filter-range-thumb-min",T.min=String(h),T.max=String(u),T.step=String(g),T.value=String(f);const L=document.createElement("input");L.type="range",L.className="tbw-filter-range-thumb tbw-filter-range-thumb-max",L.min=String(h),L.max=String(u),L.step=String(g),L.value=String(w),_.appendChild(A),_.appendChild(k),_.appendChild(T),_.appendChild(L),e.appendChild(_);const M=document.createElement("label");M.className="tbw-filter-blank-option";const P=document.createElement("input");P.type="checkbox",P.className="tbw-filter-blank-checkbox",P.checked=m;const H=document.createTextNode("Blank");M.appendChild(P),M.appendChild(H);const I=e=>{C.disabled=e,S.disabled=e,T.disabled=e,L.disabled=e,b.classList.toggle("tbw-filter-disabled",e),_.classList.toggle("tbw-filter-disabled",e)};I(m),P.addEventListener("change",()=>{I(P.checked)}),e.appendChild(M);const D=()=>{const e=parseFloat(T.value),t=parseFloat(L.value),i=u-h,n=(e-h)/i*100,r=(t-h)/i*100;k.style.left=`${n}%`,k.style.width=r-n+"%"};T.addEventListener("input",()=>{const e=Math.min(parseFloat(T.value),parseFloat(L.value));T.value=String(e),C.value=String(e),D()}),L.addEventListener("input",()=>{const e=Math.max(parseFloat(L.value),parseFloat(T.value));L.value=String(e),S.value=String(e),D()}),C.addEventListener("input",()=>{let e=parseFloat(C.value)||h;e=Math.max(h,Math.min(e,parseFloat(S.value))),T.value=String(e),D()}),S.addEventListener("input",()=>{let e=parseFloat(S.value)||u;e=Math.min(u,Math.max(e,parseFloat(C.value))),L.value=String(e),D()}),D();const z=document.createElement("div");z.className="tbw-filter-buttons";const O=document.createElement("button");O.className="tbw-filter-apply-btn",O.textContent="Apply",O.addEventListener("click",()=>{if(P.checked)return void t.applyTextFilter("blank","");const e=parseFloat(C.value),i=parseFloat(S.value);t.applyTextFilter("between",e,i)}),z.appendChild(O);const F=document.createElement("button");F.className="tbw-filter-clear-btn",F.textContent="Clear Filter",F.addEventListener("click",()=>{t.clearFilter()}),z.appendChild(F),e.appendChild(z)}renderDateFilterPanel(e,t,i){const{field:n,column:r}=t,o=r.filterParams,s=r.editorParams,l=i.filter(e=>e instanceof Date||"string"==typeof e&&!isNaN(Date.parse(e))).map(e=>e instanceof Date?e:new Date(e)).filter(e=>!isNaN(e.getTime())),a=l.length>0?new Date(Math.min(...l.map(e=>e.getTime()))):null,d=l.length>0?new Date(Math.max(...l.map(e=>e.getTime()))):null,c=e=>e?e.toISOString().split("T")[0]:"",h=e=>e?"string"==typeof e?e:"number"==typeof e?c(new Date(e)):"":"",u=h(o?.min)||h(s?.min)||c(a),g=h(o?.max)||h(s?.max)||c(d),p=this.filters.get(n);let f="",w="";const m="blank"===p?.operator;"between"===p?.operator?(f=h(p.value)||"",w=h(p.valueTo)||""):"greaterThanOrEqual"===p?.operator?f=h(p.value)||"":"lessThanOrEqual"===p?.operator&&(w=h(p.value)||"");const b=document.createElement("div");b.className="tbw-filter-date-range";const v=document.createElement("div");v.className="tbw-filter-date-group";const y=document.createElement("label");y.textContent="From",y.className="tbw-filter-range-label";const C=document.createElement("input");C.type="date",C.className="tbw-filter-date-input",u&&(C.min=u),g&&(C.max=g),C.value=f,v.appendChild(y),v.appendChild(C),b.appendChild(v);const x=document.createElement("span");x.className="tbw-filter-range-separator",x.textContent="–",b.appendChild(x);const E=document.createElement("div");E.className="tbw-filter-date-group";const R=document.createElement("label");R.textContent="To",R.className="tbw-filter-range-label";const S=document.createElement("input");S.type="date",S.className="tbw-filter-date-input",u&&(S.min=u),g&&(S.max=g),S.value=w,E.appendChild(R),E.appendChild(S),b.appendChild(E),e.appendChild(b);const _=document.createElement("label");_.className="tbw-filter-blank-option";const A=document.createElement("input");A.type="checkbox",A.className="tbw-filter-blank-checkbox",A.checked=m;const k=document.createTextNode("Show only blank");_.appendChild(A),_.appendChild(k);const T=e=>{C.disabled=e,S.disabled=e,b.classList.toggle("tbw-filter-disabled",e)};T(m),A.addEventListener("change",()=>{T(A.checked)}),e.appendChild(_);const L=document.createElement("div");L.className="tbw-filter-buttons";const M=document.createElement("button");M.className="tbw-filter-apply-btn",M.textContent="Apply",M.addEventListener("click",()=>{if(A.checked)return void t.applyTextFilter("blank","");const e=C.value,i=S.value;e&&i?t.applyTextFilter("between",e,i):e?t.applyTextFilter("greaterThanOrEqual",e):i?t.applyTextFilter("lessThanOrEqual",i):t.clearFilter()}),L.appendChild(M);const P=document.createElement("button");P.className="tbw-filter-clear-btn",P.textContent="Clear Filter",P.addEventListener("click",()=>{t.clearFilter()}),L.appendChild(P),e.appendChild(L)}applySetFilter(e,t,i){this.excludedValues.set(e,new Set(t)),0===t.length?this.filters.delete(e):this.filters.set(e,{field:e,type:"set",operator:"notIn",value:t,...void 0!==i&&{valueTo:i}}),this.applyFiltersInternal()}applyTextFilter(e,t,i,n){this.filters.set(e,{field:e,type:"text",operator:t,value:i,valueTo:n}),this.applyFiltersInternal()}applyFiltersInternal(){this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null;const e=[...this.filters.values()];if(this.config.filterHandler){const t=this.grid;t.setAttribute("aria-busy","true");const i=this.config.filterHandler(e,this.sourceRows),n=i=>{t.removeAttribute("aria-busy"),this.cachedResult=i,this.grid.rows=i,this.emit("filter-change",{filters:e,filteredRowCount:i.length,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:e}),this.requestRender()};return void(i&&"function"==typeof i.then?i.then(n):n(i))}this.emit("filter-change",{filters:e,filteredRowCount:0,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:e}),this.requestRender()}getColumnState(e){const t=this.filters.get(e);if(t)return{filter:{type:t.type,operator:t.operator,value:t.value,valueTo:t.valueTo}}}applyColumnState(e,t){if(!t.filter)return void this.filters.delete(e);const i={field:e,type:t.filter.type,operator:t.filter.operator,value:t.filter.value,valueTo:t.filter.valueTo};this.filters.set(e,i),this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null}}function Ut(e){if(!e.length)return[];const t=new Map,i=[],n=(e,t)=>{if(!t.length)return;const n=i[i.length-1];n&&n.implicit&&n.firstIndex+n.columns.length===e?n.columns.push(...t):i.push({id:"__implicit__"+e,label:void 0,columns:t,firstIndex:e,implicit:!0})};let r=[],o=0;return e.forEach((e,s)=>{const l=e.group;if(!l)return 0===r.length&&(o=s),void r.push(e);r.length&&(n(o,r.slice()),r=[]);const a="string"==typeof l?l:l.id;let d=t.get(a);d||(d={id:a,label:"string"==typeof l?void 0:l.label,columns:[],firstIndex:s},t.set(a,d),i.push(d)),d.columns.push(e)}),r.length&&n(o,r),1===i.length&&i[0].implicit&&i[0].columns.length===e.length?[]:i}const jt={sum:(e,t)=>e.reduce((e,i)=>e+(Number(i[t])||0),0),avg:(e,t)=>{const i=e.reduce((e,i)=>e+(Number(i[t])||0),0);return e.length?i/e.length:0},count:e=>e.length,min:(e,t)=>e.length?Math.min(...e.map(e=>Number(e[t])||1/0)):0,max:(e,t)=>e.length?Math.max(...e.map(e=>Number(e[t])||-1/0)):0,first:(e,t)=>e[0]?.[t],last:(e,t)=>e[e.length-1]?.[t]},Yt=new Map,Xt={register(e,t){Yt.set(e,t)},unregister(e){Yt.delete(e)},get(e){if(void 0!==e)return"function"==typeof e?e:Yt.get(e)??jt[e]},run(e,t,i,n){const r=this.get(e);return r?r(t,i,n):void 0},has:e=>Yt.has(e)||e in jt,list:()=>[...Object.keys(jt),...Yt.keys()]},Zt={sum:e=>e.reduce((e,t)=>e+t,0),avg:e=>e.length?e.reduce((e,t)=>e+t,0)/e.length:0,count:e=>e.length,min:e=>e.length?Math.min(...e):0,max:e=>e.length?Math.max(...e):0,first:e=>e[0]??0,last:e=>e[e.length-1]??0};Xt.register.bind(Xt),Xt.unregister.bind(Xt);const Qt=Xt.get.bind(Xt),Jt=Xt.run.bind(Xt);function ei({rows:e,config:t,expanded:i,initialExpanded:n}){const r=t.groupOn;if("function"!=typeof r)return[];const o={key:"__root__",value:null,depth:-1,rows:[],children:new Map};if(e.forEach(e=>{let t=r(e);null==t||!1===t?t=["__ungrouped__"]:Array.isArray(t)||(t=[t]);let i=o;t.forEach((e,t)=>{const n=null==e?"∅":String(e),r="__root__"===i.key?n:i.key+"||"+n;let o=i.children.get(n);o||(o={key:r,value:e,depth:t,rows:[],children:new Map,parent:i},i.children.set(n,o)),i=o}),i.rows.push(e)}),1===o.children.size&&o.children.has("__ungrouped__")){if(o.children.get("__ungrouped__").rows.length===e.length)return[]}const s=new Set([...i,...n??[]]),l=[],a=t=>{if(t===o)return void t.children.forEach(e=>a(e));const i=s.has(t.key);l.push({kind:"group",key:t.key,value:t.value,depth:t.depth,rows:t.rows,expanded:i}),i&&(t.children.size?t.children.forEach(e=>a(e)):t.rows.forEach(t=>l.push({kind:"data",row:t,rowIndex:e.indexOf(t)})))};return a(o),l}Xt.list.bind(Xt);function ti(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}function ii(e,t,i,n){const r=document.createElement("div");r.className="master-detail-row",r.setAttribute("data-detail-for",String(t)),r.setAttribute("role","row");const o=document.createElement("div");o.className="master-detail-cell",o.setAttribute("role","cell"),o.style.gridColumn=`1 / ${n+1}`;const s=i(e,t);return"string"==typeof s?o.innerHTML=s:s instanceof HTMLElement&&o.appendChild(s),r.appendChild(o),r}class ni extends rt{name="masterDetail";styles="@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-right:none!important;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1 / 3}tbw-grid .master-detail-expander{display:flex;align-items:center;justify-content:center;width:100%;height:100%}tbw-grid .master-detail-toggle{cursor:pointer;opacity:.7;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center}tbw-grid .master-detail-toggle:hover{opacity:1}tbw-grid .master-detail-row{grid-column:1 / -1;display:grid;background:var(--tbw-master-detail-bg, var(--tbw-color-row-alt));border-bottom:1px solid var(--tbw-master-detail-border, var(--tbw-color-border));overflow:hidden}tbw-grid .master-detail-cell{padding:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));overflow:auto}tbw-grid .master-detail-row.tbw-expanding{animation:tbw-detail-expand var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .master-detail-row.tbw-collapsing{animation:tbw-detail-collapse var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-detail-expand{0%{opacity:0;max-height:0;padding-top:0;padding-bottom:0}to{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem);padding-top:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));padding-bottom:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem))}}@keyframes tbw-detail-collapse{0%{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem)}to{opacity:0;max-height:0}}}";get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,animation:"slide"}}attach(e){super.attach(e),this.parseLightDomDetail()}parseLightDomDetail(){const e=this.grid;if(!e||"function"!=typeof e.querySelector)return;const t=e.querySelector("tbw-grid-detail");if(!t)return;const i=e;if(i.__frameworkAdapter?.parseDetailElement){const e=i.__frameworkAdapter.parseDetailElement(t);if(e)return void(this.config={...this.config,detailRenderer:e})}const n=t.getAttribute("animation"),r=t.getAttribute("show-expand-column"),o=t.getAttribute("expand-on-row-click"),s=t.getAttribute("collapse-on-click-outside"),l=t.getAttribute("height"),a={};null!==n&&(a.animation="false"!==n&&n),null!==r&&(a.showExpandColumn="false"!==r),null!==o&&(a.expandOnRowClick="true"===o),null!==s&&(a.collapseOnClickOutside="true"===s),null!==l&&(a.detailHeight="auto"===l?"auto":parseInt(l,10));const d=t.innerHTML.trim();d&&!this.config.detailRenderer&&(a.detailRenderer=(e,t)=>y(C(d,{value:e,row:e}))),Object.keys(a).length>0&&(this.config={...this.config,...a})}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}animateExpand(e,t,i){if(!this.isAnimationEnabled||!1===this.animationStyle)return!1;e.classList.add("tbw-expanding");let n=!1;const r=()=>{n||(n=!0,e.classList.remove("tbw-expanding"),void 0!==t&&void 0!==i&&this.#pt(e,t,i))};return e.addEventListener("animationend",r,{once:!0}),setTimeout(r,this.animationDuration+50),!0}animateCollapse(e,t){if(!this.isAnimationEnabled||!1===this.animationStyle)return void t();e.classList.add("tbw-collapsing");const i=()=>{e.classList.remove("tbw-collapsing"),t()};e.addEventListener("animationend",i,{once:!0}),setTimeout(i,this.animationDuration+50)}#pt(e,t,i){if(!e.isConnected)return;const n=e.offsetHeight;if(n>0){const e=this.measuredDetailHeights.get(t);this.measuredDetailHeights.set(t,n),e!==n&&this.grid.invalidateRowHeight(i)}}expandedRows=new Set;detailElements=new Map;measuredDetailHeights=new Map;rowsToAnimate=new Set;static DEFAULT_DETAIL_HEIGHT=150;getDetailHeight(e){const t=this.detailElements.get(e);if(t){if(!(t.classList.contains("tbw-expanding")||t.classList.contains("tbw-collapsing"))){const i=t.offsetHeight;if(i>0)return this.measuredDetailHeights.set(e,i),i}}const i=this.measuredDetailHeights.get(e);return i&&i>0?i:"number"==typeof this.config?.detailHeight?this.config.detailHeight:ni.DEFAULT_DETAIL_HEIGHT}toggleAndEmit(e,t){this.expandedRows=ti(this.expandedRows,e);const i=this.expandedRows.has(e);i&&this.rowsToAnimate.add(e),this.emit("detail-expand",{rowIndex:t,row:e,expanded:i}),this.requestRender()}detach(){this.expandedRows.clear(),this.detailElements.clear(),this.measuredDetailHeights.clear(),this.rowsToAnimate.clear()}processColumns(e){if(!(!0===this.config.showExpandColumn||!1!==this.config.showExpandColumn&&!!this.config.detailRenderer))return[...e];const t=[...e],i=function(e){return e.find(Bt)}(t);if(i)return t;const n=(r=this.name,{field:$t,header:"",width:32,resizable:!1,sortable:!1,filterable:!1,meta:{lockPosition:!0,suppressMovable:!0,expanderColumn:!0,expanderPlugin:r,utility:!0}});var r;return n.viewRenderer=e=>{const{row:t}=e,i=this.expandedRows.has(t),n=document.createElement("span");n.className="master-detail-expander expander-cell";const r=document.createElement("span");return r.className="master-detail-toggle"+(i?" expanded":""),this.setIcon(r,this.resolveIcon(i?"collapse":"expand")),r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.setAttribute("aria-expanded",String(i)),r.setAttribute("aria-label",i?"Collapse details":"Expand details"),n.appendChild(r),n},[n,...t]}onRowClick(e){if(this.config.expandOnRowClick&&this.config.detailRenderer)return this.toggleAndEmit(e.row,e.rowIndex),!1}onCellClick(e){const t=e.originalEvent?.target;if(t?.classList.contains("master-detail-toggle"))return this.toggleAndEmit(e.row,e.rowIndex),!0;this.expandedRows.size>0&&queueMicrotask(()=>this.#ft())}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusCol,i=this.grid._focusRow,n=this.visibleColumns[t];if(!n||!Bt(n))return;const r=this.rows[i];return r?(e.preventDefault(),this.toggleAndEmit(r,i),this.requestRenderWithFocus(),!0):void 0}afterRender(){this.#ft()}onScrollRender(){this.config.detailRenderer&&0!==this.expandedRows.size&&this.#ft()}#ft(){if(!this.config.detailRenderer)return;const e=this.gridElement?.querySelector(".rows");if(!e)return;const t=this.grid,i=t._rowPool,n=t._virtualization?.start??0,r=t._virtualization?.end??0,o=this.columns.length,s=n,l=r,a=new Map;if(i){const t=Math.min(i.length,l-s);for(let n=0;n<t;n++){const t=i[n];t.parentNode===e&&a.set(s+n,t)}}else{const t=e.querySelectorAll(".data-grid-row");for(const e of t){const t=e.querySelector(".cell[data-row]"),i=t?parseInt(t.getAttribute("data-row")??"-1",10):-1;i>=0&&a.set(i,e)}}for(const[d,c]of this.detailElements){const e=this.rows.indexOf(d),t=this.expandedRows.has(d),i=e>=0&&a.has(e);if(!t||!i){const e=this.grid.__frameworkAdapter;if(e?.unmount){const t=c.querySelector(".master-detail-cell"),i=t?.firstElementChild;i&&e.unmount(i)}c.parentNode&&c.remove(),this.detailElements.delete(d)}}for(const[d,c]of a){const e=this.rows[d];if(!e||!this.expandedRows.has(e))continue;const t=this.detailElements.get(e);if(t){t.previousElementSibling!==c&&c.after(t);continue}const i=ii(e,d,this.config.detailRenderer,o);"number"==typeof this.config.detailHeight&&(i.style.height=`${this.config.detailHeight}px`),c.after(i),this.detailElements.set(e,i);const n=this.rowsToAnimate.has(e);n&&this.rowsToAnimate.delete(e);n&&this.animateExpand(i,e,d)||requestAnimationFrame(()=>{this.#pt(i,e,d)})}}getExtraHeight(){let e=0;for(const t of this.expandedRows)e+=this.getDetailHeight(t);return e}getExtraHeightBefore(e){let t=0;for(const i of this.expandedRows){const n=this.rows.indexOf(i);n>=0&&n<e&&(t+=this.getDetailHeight(i))}return t}getRowHeight(e,t){if(!this.expandedRows.has(e))return;return(this.grid.defaultRowHeight??28)+this.getDetailHeight(e)}adjustVirtualStart(e,t,i){if(0===this.expandedRows.size)return e;const n=this.grid?._virtualization?.positionCache;let r=e;if(n&&n.length>0)for(const o of this.expandedRows){const i=this.rows.indexOf(o);if(i<0||i>=e)continue;n[i].offset+n[i].height>t&&i<r&&(r=i)}else{const n=[];for(const e of this.expandedRows){const t=this.rows.indexOf(e);t>=0&&n.push({index:t,row:e})}n.sort((e,t)=>e.index-t.index);let o=0;for(const{index:s,row:l}of n){const n=s*i+o,a=this.getDetailHeight(l);o+=a,s>=e||n+i+a>t&&s<r&&(r=s)}}return r}expand(e){const t=this.rows[e];t&&(this.rowsToAnimate.add(t),this.expandedRows=function(e,t){const i=new Set(e);return i.add(t),i}(this.expandedRows,t),this.requestRender())}collapse(e){const t=this.rows[e];t&&(this.expandedRows=function(e,t){const i=new Set(e);return i.delete(t),i}(this.expandedRows,t),this.requestRender())}toggle(e){const t=this.rows[e];t&&(this.expandedRows=ti(this.expandedRows,t),this.expandedRows.has(t)&&this.rowsToAnimate.add(t),this.requestRender())}isExpanded(e){const t=this.rows[e];return!!t&&function(e,t){return e.has(t)}(this.expandedRows,t)}expandAll(){for(const e of this.rows)this.rowsToAnimate.add(e),this.expandedRows.add(e);this.requestRender()}collapseAll(){this.expandedRows.clear(),this.requestRender()}getExpandedRows(){const e=[];for(const t of this.expandedRows){const i=this.rows.indexOf(t);i>=0&&e.push(i)}return e}getDetailElement(e){const t=this.rows[e];return t?this.detailElements.get(t):void 0}refreshDetailRenderer(){const e=this.config.detailRenderer;if(this.config={...this.config,detailRenderer:void 0},this.parseLightDomDetail(),!this.config.detailRenderer&&e&&(this.config={...this.config,detailRenderer:e}),this.config.detailRenderer){const e=this.grid;"function"==typeof e.refreshColumns?e.refreshColumns():this.requestRender()}}}function ri(e,t){return null==e&&null==t?0:null==e?1:null==t?-1:"number"==typeof e&&"number"==typeof t?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():"boolean"==typeof e&&"boolean"==typeof t?e===t?0:e?-1:1:String(e).localeCompare(String(t))}function oi(e,t){const i=e.findIndex(e=>e.field===t);return i>=0?i+1:void 0}function si(e,t){return e.find(e=>e.field===t)?.direction}function li(e){return e.pinned??e.sticky??e.meta?.pinned??e.meta?.sticky}function ai(e,t){return function(e,t){return"left"===e||"right"===e?e:"rtl"===t?"start"===e?"right":"left":"start"===e?"left":"right"}(e,t)}function di(e,t){const i=li(e);return!!i&&"left"===ai(i,t)}function ci(e,t){const i=li(e);return!!i&&"right"===ai(i,t)}function hi(e){return e.some(e=>null!=li(e))}function ui(e,t){const i=Array.from(e.querySelectorAll(".header-row .cell"));if(!i.length)return;const n=M(e);let r=0;for(const s of t)if(di(s,n)){const t=i.find(e=>e.getAttribute("data-field")===s.field);t&&(t.classList.add("sticky-left"),t.style.position="sticky",t.style.left=r+"px",e.querySelectorAll(`.data-grid-row .cell[data-field="${s.field}"]`).forEach(e=>{e.classList.add("sticky-left"),e.style.position="sticky",e.style.left=r+"px"}),r+=t.offsetWidth)}let o=0;for(const s of[...t].reverse())if(ci(s,n)){const t=i.find(e=>e.getAttribute("data-field")===s.field);t&&(t.classList.add("sticky-right"),t.style.position="sticky",t.style.right=o+"px",e.querySelectorAll(`.data-grid-row .cell[data-field="${s.field}"]`).forEach(e=>{e.classList.add("sticky-right"),e.style.position="sticky",e.style.right=o+"px"}),o+=t.offsetWidth)}}function gi(e){e.querySelectorAll(".sticky-left, .sticky-right").forEach(e=>{e.classList.remove("sticky-left","sticky-right"),e.style.position="",e.style.left="",e.style.right=""})}const pi="canMoveColumn";function fi(e,t){const i=document.createElement("div");i.className="tbw-pinned-rows",i.setAttribute("role","presentation"),i.setAttribute("aria-live","polite");const n=document.createElement("div");n.className="tbw-pinned-rows-left";const r=document.createElement("div");r.className="tbw-pinned-rows-center";const o=document.createElement("div");if(o.className="tbw-pinned-rows-right",!1!==e.showRowCount){const e=document.createElement("span");e.className="tbw-status-panel tbw-status-panel-row-count",e.textContent=`Total: ${t.totalRows} rows`,n.appendChild(e)}if(e.showFilteredCount&&t.filteredRows!==t.totalRows){const e=document.createElement("span");e.className="tbw-status-panel tbw-status-panel-filtered-count",e.textContent=`Filtered: ${t.filteredRows}`,n.appendChild(e)}if(e.showSelectedCount&&t.selectedRows>0){const e=document.createElement("span");e.className="tbw-status-panel tbw-status-panel-selected-count",e.textContent=`Selected: ${t.selectedRows}`,o.appendChild(e)}if(e.customPanels)for(const s of e.customPanels){const e=Ci(s,t);switch(s.position){case"left":n.appendChild(e);break;case"center":r.appendChild(e);break;case"right":o.appendChild(e)}}return i.appendChild(n),i.appendChild(r),i.appendChild(o),i}function wi(e){const t=document.createElement("div");return t.className=`tbw-aggregation-rows tbw-aggregation-rows-${e}`,t.setAttribute("role","presentation"),t}function mi(e,t,i,n,r=!1){e.innerHTML="";for(const o of t){const t=document.createElement("div");t.className="tbw-aggregation-row",t.setAttribute("role","presentation"),o.id&&t.setAttribute("data-aggregation-id",o.id);o.fullWidth??r?bi(t,o,i,n):vi(t,o,i,n),e.appendChild(t)}}function bi(e,t,i,n){const r=document.createElement("div");r.className="tbw-aggregation-cell tbw-aggregation-cell-full",r.style.gridColumn="1 / -1";const o="function"==typeof t.label?t.label(n,i):t.label;if(o){const e=document.createElement("span");e.className="tbw-aggregation-label",e.textContent=o,r.appendChild(e)}const s=function(e,t,i){const n=e.aggregators&&Object.keys(e.aggregators).length>0,r=e.cells&&Object.keys(e.cells).length>0;if(!n&&!r)return null;const o=document.createElement("span");o.className="tbw-aggregation-aggregates";for(const s of t){const{value:t,formatter:n}=yi(e,s,i);if(null!=t){const e=document.createElement("span");e.className="tbw-aggregation-aggregate",e.setAttribute("data-field",s.field);const i=s.header??s.field,r=n?n(t,s.field,s):String(t);e.textContent=`${i}: ${r}`,o.appendChild(e)}}return o.children.length>0?o:null}(t,i,n);s&&r.appendChild(s),e.appendChild(r)}function vi(e,t,i,n){for(const r of i){const i=document.createElement("div");i.className="tbw-aggregation-cell",i.setAttribute("data-field",r.field);const{value:o,formatter:s}=yi(t,r,n);i.textContent=null!=o?s?s(o,r.field,r):String(o):"",e.appendChild(i)}}function yi(e,t,i){let n,r;const o=e.aggregators?.[t.field];if(o)if("object"==typeof(s=o)&&null!==s&&"aggFunc"in s){const e=Qt(o.aggFunc);e&&(n=e(i,t.field,t)),r=o.formatter}else{const e=Qt(o);e&&(n=e(i,t.field,t))}else if(e.cells&&Object.prototype.hasOwnProperty.call(e.cells,t.field)){const r=e.cells[t.field];n="function"==typeof r?r(i,t.field,t):r}var s;return{value:n,formatter:r}}function Ci(e,t){const i=document.createElement("div");i.className="tbw-status-panel tbw-status-panel-custom",i.id=`status-panel-${e.id}`;const n=e.render(t);return"string"==typeof n?i.innerHTML=n:i.appendChild(n),i}function xi(e,t,i,n,r){return{totalRows:e.length,filteredRows:r?.cachedResult?.length??e.length,selectedRows:n?.selected?.size??0,columns:t,rows:e,grid:i}}const Ei=function(e){return Zt[e]??Zt.sum};function Ri(e,t){return[...e,t].join("|")}function Si(e,t){const i=t.rowGroupFields??[],n=t.columnGroupFields??[],r=t.valueFields??[],o=function(e,t){if(0===t.length)return["value"];const i=new Set;for(const n of e){const e=t.map(e=>String(n[e]??"")).join("|");i.add(e)}return[...i].sort()}(e,n),s=_i(e,i,n,o,r,0,""),l=function(e,t,i){const n={};function r(e){for(const o of e)if(o.isGroup&&o.children?.length)o.children&&r(o.children);else for(const e of t)for(const t of i){const i=Ri([e],t.field);n[i]=(n[i]??0)+(o.values[i]??0)}}return r(e),n}(s,o,r);return{rows:s,columnKeys:o,totals:l,grandTotal:Object.values(l).reduce((e,t)=>e+t,0)}}function _i(e,t,i,n,r,o,s){const l=[];if(0===t.length){const t=Ai(e,i,n,r),a=ki(t);return l.push({rowKey:s||"all",rowLabel:s||"All",depth:o,values:t,total:a,isGroup:!1,rowCount:e.length}),l}const a=t[0],d=t.slice(1),c=d.length>0,h=function(e,t){const i=new Map;for(const n of e){const e=String(n[t]??""),r=i.get(e);r?r.push(n):i.set(e,[n])}return i}(e,a);for(const[u,g]of h){const e=s?`${s}|${u}`:u,t=Ai(g,i,n,r),a=ki(t);let h;c&&(h=_i(g,d,i,n,r,o+1,e)),l.push({rowKey:e,rowLabel:u||"(blank)",depth:o,values:t,total:a,isGroup:c,children:h,rowCount:g.length})}return l}function Ai(e,t,i,n){const r={};for(const o of i)for(const i of n){const n=(t.length>0?e.filter(e=>t.map(t=>String(e[t]??"")).join("|")===o):e).map(e=>Number(e[i.field])||0),s=Ei(i.aggFunc),l=n.length>0?s(n):null;r[Ri([o],i.field)]=l}return r}function ki(e){let t=0;for(const i of Object.values(e))t+=i??0;return t}const Ti=["sum","avg","count","min","max","first","last"];function Li(e,t,i,n){const r=new AbortController,o={config:t,callbacks:n,signal:r.signal},s=document.createElement("div");return s.className="tbw-pivot-panel",s.appendChild(Mi("Options",()=>function(e,t){const{config:i,callbacks:n,signal:r}=t,o=document.createElement("div");return o.className="tbw-pivot-options",o.appendChild(Di("Enable Pivot View",e,e=>{n.onTogglePivot(e)},r)),o.appendChild(Di("Show Row Totals",i.showTotals??!0,e=>{n.onOptionChange("showTotals",e)},r)),o.appendChild(Di("Show Grand Total",i.showGrandTotal??!0,e=>{n.onOptionChange("showGrandTotal",e)},r)),o}(i,o))),s.appendChild(Mi("Row Groups",()=>Pi("rowGroups",o))),s.appendChild(Mi("Column Groups",()=>Pi("columnGroups",o))),s.appendChild(Mi("Values",()=>function(e){const{config:t,callbacks:i,signal:n}=e,r=document.createElement("div");r.className="tbw-pivot-drop-zone tbw-pivot-values-zone",r.setAttribute("data-zone","values");const o=t.valueFields??[];if(0===o.length){const e=document.createElement("div");e.className="tbw-pivot-placeholder",e.textContent="Drag numeric fields here for aggregation",r.appendChild(e)}else for(const s of o)r.appendChild(Ii(s,e));return r.addEventListener("dragover",e=>{e.preventDefault(),r.classList.add("drag-over")},{signal:n}),r.addEventListener("dragleave",()=>{r.classList.remove("drag-over")},{signal:n}),r.addEventListener("drop",e=>{e.preventDefault(),r.classList.remove("drag-over");const t=e.dataTransfer?.getData("text/plain");t&&i.onAddValueField(t,"sum")},{signal:n}),r}(o))),s.appendChild(Mi("Available Fields",()=>function(e){const{config:t,callbacks:i,signal:n}=e,r=document.createElement("div");r.className="tbw-pivot-available-fields";const o=i.getAvailableFields(),s=new Set([...t.rowGroupFields??[],...t.columnGroupFields??[],...t.valueFields?.map(e=>e.field)??[]]),l=o.filter(e=>!s.has(e.field));if(0===l.length){const e=document.createElement("div");e.className="tbw-pivot-placeholder",e.textContent="All fields are in use",r.appendChild(e)}else for(const a of l){const e=document.createElement("div");e.className="tbw-pivot-field-chip available",e.textContent=a.header,e.draggable=!0,e.title=`Drag to add "${a.field}" to a zone`,e.addEventListener("dragstart",t=>{t.dataTransfer?.setData("text/plain",a.field),e.classList.add("dragging")},{signal:n}),e.addEventListener("dragend",()=>{e.classList.remove("dragging")},{signal:n}),r.appendChild(e)}return r}(o))),e.appendChild(s),()=>{r.abort(),s.remove()}}function Mi(e,t){const i=document.createElement("div");i.className="tbw-pivot-section";const n=document.createElement("div");n.className="tbw-pivot-section-header",n.textContent=e;const r=document.createElement("div");return r.className="tbw-pivot-section-content",r.appendChild(t()),i.appendChild(n),i.appendChild(r),i}function Pi(e,t){const{config:i,callbacks:n,signal:r}=t,o=document.createElement("div");o.className="tbw-pivot-drop-zone",o.setAttribute("data-zone",e);const s="rowGroups"===e?i.rowGroupFields??[]:i.columnGroupFields??[];if(0===s.length){const e=document.createElement("div");e.className="tbw-pivot-placeholder",e.textContent="Drag fields here or click to add",o.appendChild(e)}else for(const l of s)o.appendChild(Hi(l,e,t));return o.addEventListener("dragover",e=>{e.preventDefault(),o.classList.add("drag-over")},{signal:r}),o.addEventListener("dragleave",()=>{o.classList.remove("drag-over")},{signal:r}),o.addEventListener("drop",t=>{t.preventDefault(),o.classList.remove("drag-over");const i=t.dataTransfer?.getData("text/plain");i&&n.onAddFieldToZone(i,e)},{signal:r}),o}function Hi(e,t,i){const{callbacks:n,signal:r}=i,o=document.createElement("div");o.className="tbw-pivot-field-chip",o.draggable=!0;const s=n.getAvailableFields().find(t=>t.field===e),l=document.createElement("span");l.className="tbw-pivot-chip-label",l.textContent=s?.header??e;const a=document.createElement("button");return a.className="tbw-pivot-chip-remove",a.innerHTML="×",a.title="Remove field",a.addEventListener("click",i=>{i.stopPropagation(),n.onRemoveFieldFromZone(e,t)},{signal:r}),o.appendChild(l),o.appendChild(a),o.addEventListener("dragstart",i=>{i.dataTransfer?.setData("text/plain",e),i.dataTransfer?.setData("source-zone",t),o.classList.add("dragging")},{signal:r}),o.addEventListener("dragend",()=>{o.classList.remove("dragging")},{signal:r}),o}function Ii(e,t){const{callbacks:i,signal:n}=t,r=document.createElement("div");r.className="tbw-pivot-field-chip tbw-pivot-value-chip";const o=i.getAvailableFields().find(t=>t.field===e.field),s=document.createElement("div");s.className="tbw-pivot-value-label-wrapper";const l=document.createElement("span");l.className="tbw-pivot-chip-label",l.textContent=o?.header??e.field;const a=document.createElement("select");a.className="tbw-pivot-agg-select",a.title="Aggregation function";for(const c of Ti){const t=document.createElement("option");t.value=c,t.textContent=c.toUpperCase(),t.selected=c===e.aggFunc,a.appendChild(t)}a.addEventListener("change",()=>{i.onUpdateValueAggFunc(e.field,a.value)},{signal:n});const d=document.createElement("button");return d.className="tbw-pivot-chip-remove",d.innerHTML="×",d.title="Remove value field",d.addEventListener("click",t=>{t.stopPropagation(),i.onRemoveValueField(e.field)},{signal:n}),s.appendChild(l),s.appendChild(a),r.appendChild(s),r.appendChild(d),r}function Di(e,t,i,n){const r=document.createElement("label");r.className="tbw-pivot-checkbox";const o=document.createElement("input");o.type="checkbox",o.checked=t,o.addEventListener("change",()=>i(o.checked),{signal:n});const s=document.createElement("span");return s.textContent=e,r.appendChild(o),r.appendChild(s),r}class zi extends rt{name="pivot";styles='@layer tbw-plugins{.pivot-group-row{display:grid;grid-template-columns:var(--tbw-column-template);font-weight:600;background:var(--tbw-pivot-group-bg, var(--tbw-color-row-alt));min-height:var(--tbw-row-height);border-bottom:var(--tbw-row-divider)}.pivot-group-row:hover{background:var(--tbw-pivot-group-hover, var(--tbw-color-row-hover))}.pivot-leaf-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-pivot-leaf-bg, var(--tbw-color-bg));min-height:var(--tbw-row-height);border-bottom:var(--tbw-row-divider)}.pivot-grand-total-row{display:grid;grid-template-columns:var(--tbw-column-template);font-weight:700;background:var(--tbw-pivot-grand-total-bg, var(--tbw-color-header-bg));min-height:var(--tbw-row-height);border-top:2px solid var(--tbw-color-border-strong)}.pivot-grand-total-row>.cell{display:flex;align-items:center;padding:var(--tbw-cell-padding);border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;min-width:0}.pivot-grand-total-row>.cell:last-child{border-right:0}.pivot-grand-total-footer{position:sticky;bottom:0;z-index:var(--tbw-z-layer-pinned-rows, 20);background:var(--tbw-pivot-grand-total-bg, var(--tbw-color-header-bg));min-width:fit-content}.pivot-group-row>.cell,.pivot-leaf-row>.cell{display:flex;align-items:center;padding:var(--tbw-cell-padding);border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;min-width:0}.pivot-group-row>.cell:last-child,.pivot-leaf-row>.cell:last-child{border-right:0}.pivot-toggle{display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-pivot-toggle-size, var(--tbw-toggle-size, 1.25em));height:var(--tbw-pivot-toggle-size, var(--tbw-toggle-size, 1.25em));margin-right:var(--tbw-spacing-sm, .375em);border:none;background:transparent;cursor:pointer;color:var(--tbw-pivot-toggle-color, var(--tbw-color-fg-muted));border-radius:var(--tbw-border-radius);transition:background var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease),color var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease)}.pivot-toggle:hover{background:var(--tbw-pivot-toggle-hover-bg, var(--tbw-color-row-hover));color:var(--tbw-pivot-toggle-hover-color, var(--tbw-color-fg))}.pivot-toggle:focus{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}.pivot-label{font-weight:inherit}.pivot-count{color:var(--tbw-pivot-count-color, var(--tbw-color-fg-muted));font-size:.9em;font-weight:400}.pivot-total-row{font-weight:700;border-top:2px solid var(--tbw-pivot-border, var(--tbw-color-border-strong))}[data-pivot-depth="1"]{--tbw-pivot-depth: 1}[data-pivot-depth="2"]{--tbw-pivot-depth: 2}[data-pivot-depth="3"]{--tbw-pivot-depth: 3}[data-pivot-depth="4"]{--tbw-pivot-depth: 4}.tbw-pivot-panel{display:flex;flex-direction:column;gap:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));padding:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));height:100%;overflow-y:auto;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-pivot-section{border:1px solid var(--tbw-pivot-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius);background:var(--tbw-pivot-section-bg, var(--tbw-color-bg))}.tbw-pivot-section-header{padding:var(--tbw-button-padding, var(--tbw-spacing-md, .5rem) var(--tbw-spacing-lg, .75rem));font-weight:600;background:var(--tbw-pivot-header-bg, var(--tbw-color-header-bg));border-bottom:1px solid var(--tbw-pivot-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius) var(--tbw-border-radius) 0 0}.tbw-pivot-section-content{padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-pivot-toggle-wrapper{display:flex;align-items:center}.tbw-pivot-toggle-label{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));cursor:pointer}.tbw-pivot-toggle-label input{width:var(--tbw-icon-size, 1rem);height:var(--tbw-icon-size, 1rem);cursor:pointer}.tbw-pivot-drop-zone{min-height:60px;padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border:2px dashed var(--tbw-pivot-drop-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius);background:var(--tbw-pivot-drop-bg, var(--tbw-color-row-alt));display:flex;flex-wrap:wrap;gap:var(--tbw-spacing-sm, .375rem);align-content:flex-start;transition:all .15s ease}.tbw-pivot-drop-zone.drag-over{border-color:var(--tbw-color-accent);background:var(--tbw-pivot-drop-active, var(--tbw-focus-background))}.tbw-pivot-placeholder{color:var(--tbw-color-fg-muted);font-style:italic;padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));text-align:center;width:100%}.tbw-pivot-field-chip{display:inline-flex;align-items:center;gap:var(--tbw-spacing-sm, .375rem);padding:var(--tbw-button-padding-sm, var(--tbw-spacing-xs, .25rem) var(--tbw-spacing-md, .5rem));background:var(--tbw-pivot-chip-bg, var(--tbw-color-header-bg));border:1px solid var(--tbw-pivot-chip-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius);cursor:grab;font-size:var(--tbw-font-size-xs, .75rem);transition:all .15s ease}.tbw-pivot-field-chip:hover{background:var(--tbw-pivot-chip-hover, var(--tbw-color-row-hover));border-color:var(--tbw-color-accent)}.tbw-pivot-field-chip.available{background:var(--tbw-color-bg)}.tbw-pivot-field-chip.dragging{opacity:.5;cursor:grabbing}.tbw-pivot-chip-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:120px}.tbw-pivot-chip-remove{display:flex;align-items:center;justify-content:center;width:var(--tbw-icon-size, 1rem);height:var(--tbw-icon-size, 1rem);padding:0;border:none;background:transparent;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-sm, .875rem);font-weight:700;cursor:pointer;border-radius:50%;transition:all .15s ease}.tbw-pivot-chip-remove:hover{background:var(--tbw-pivot-chip-remove-hover-bg, var(--tbw-color-accent));color:var(--tbw-pivot-chip-remove-hover-fg, var(--tbw-color-accent-fg))}.tbw-pivot-value-chip{padding:var(--tbw-button-padding-sm, var(--tbw-spacing-xs, .25rem) var(--tbw-spacing-md, .5rem))}.tbw-pivot-value-label-wrapper{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));flex:1;min-width:0}.tbw-pivot-agg-select{padding:var(--tbw-spacing-xs, .125rem) var(--tbw-spacing-xs, .25rem);font-size:var(--tbw-font-size-xs, .6875rem);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);background:var(--tbw-color-bg);cursor:pointer}.tbw-pivot-available-fields{display:flex;flex-wrap:wrap;gap:var(--tbw-spacing-sm, .375rem);min-height:40px}.tbw-pivot-options{display:flex;flex-direction:column;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-pivot-checkbox{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));cursor:pointer}.tbw-pivot-checkbox input{width:var(--tbw-icon-size-sm, .875rem);height:var(--tbw-icon-size-sm, .875rem);cursor:pointer}.pivot-group-row.tbw-pivot-slide-in,.pivot-leaf-row.tbw-pivot-slide-in{animation:tbw-pivot-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-pivot-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.pivot-group-row.tbw-pivot-fade-in,.pivot-leaf-row.tbw-pivot-fade-in{animation:tbw-pivot-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-pivot-fade-in{0%{opacity:0}to{opacity:1}}}';static PANEL_ID="pivot";get defaultConfig(){return{active:!0,showTotals:!0,showGrandTotal:!0,showToolPanel:!0,animation:"slide"}}isActive=!1;hasInitialized=!1;pivotResult=null;fieldHeaderMap=new Map;expandedKeys=new Set;defaultExpanded=!0;userHasToggledExpand=!1;originalColumns=[];panelContainer=null;grandTotalFooter=null;previousVisibleKeys=new Set;keysToAnimate=new Set;hasValidPivotConfig(){return(this.config.valueFields?.length??0)>0}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detach(){this.isActive=!1,this.hasInitialized=!1,this.pivotResult=null,this.fieldHeaderMap.clear(),this.originalColumns=[],this.panelContainer=null,this.cleanupGrandTotalFooter(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.userHasToggledExpand=!1}getToolPanel(){if(!1!==(this.config?.showToolPanel??this.userConfig?.showToolPanel??!0))return{id:zi.PANEL_ID,title:"Pivot",icon:"⊞",tooltip:"Configure pivot table",order:90,render:e=>this.renderPanel(e)}}processRows(e){if(!this.hasInitialized&&!1!==this.config.active&&this.hasValidPivotConfig()&&(this.hasInitialized=!0,this.isActive=!0),!this.isActive)return[...e];const t=function(e){const t=[];return e.rowGroupFields?.length||e.columnGroupFields?.length||t.push("At least one row or column group field is required"),e.valueFields?.length||t.push("At least one value field is required"),t}(this.config);if(t.length>0)return this.warn(`Config errors: ${t.join(", ")}`),[...e];this.buildFieldHeaderMap(),this.defaultExpanded=this.config.defaultExpanded??!0,this.pivotResult=Si(e,this.config),0===this.expandedKeys.size&&this.defaultExpanded&&!this.userHasToggledExpand&&this.expandAllKeys();const i=this.config.indentWidth??20,n=function(e,t,i=!0){const n=[];function r(e){n.push(e);const o=t?t.has(e.rowKey):i;if(e.children&&o)for(const t of e.children)r(t)}for(const o of e)r(o);return n}(this.pivotResult.rows,this.expandedKeys,this.defaultExpanded).map(e=>({__pivotRowKey:e.rowKey,__pivotLabel:e.rowLabel,__pivotDepth:e.depth,__pivotIsGroup:e.isGroup,__pivotHasChildren:Boolean(e.children?.length),__pivotExpanded:this.expandedKeys.has(e.rowKey),__pivotRowCount:e.rowCount??0,__pivotIndent:e.depth*i,__pivotTotal:e.total,...e.values}));this.keysToAnimate.clear();const r=new Set;for(const o of n){const e=o.__pivotRowKey;r.add(e),!this.previousVisibleKeys.has(e)&&o.__pivotDepth>0&&this.keysToAnimate.add(e)}return this.previousVisibleKeys=r,n}processColumns(e){if(!this.isActive||!this.pivotResult)return[...e];const t=[],i=(this.config.rowGroupFields??[]).map(e=>this.fieldHeaderMap.get(e)??e).join(" / ");t.push({field:"__pivotLabel",header:i||"Group",width:200});for(const n of this.pivotResult.columnKeys)for(const e of this.config.valueFields??[]){const i=Ri([n],e.field),r=e.header||this.fieldHeaderMap.get(e.field)||e.field;t.push({field:i,header:`${n} - ${r} (${e.aggFunc})`,width:120,type:"number"})}return this.config.showTotals&&t.push({field:"__pivotTotal",header:"Total",width:100,type:"number"}),t}renderRow(e,t,i){const n=e;return n.__pivotRowKey&&n.__pivotHasChildren?function(e,t,i){return t.className="data-grid-row pivot-group-row",t.setAttribute("data-pivot-depth",String(e.__pivotDepth??0)),t.setAttribute("data-pivot-key",String(e.__pivotRowKey??"")),t.setAttribute("role","row"),t.innerHTML="",i.columns.forEach((n,r)=>{const o=document.createElement("div");if(o.className="cell",o.setAttribute("data-col",String(r)),o.setAttribute("data-row",String(i.rowIndex)),o.setAttribute("role","gridcell"),0===r){const t=Number(e.__pivotIndent)||0;o.style.paddingLeft=`${t}px`;const n=String(e.__pivotRowKey),r=document.createElement("button");r.type="button",r.className="pivot-toggle",r.setAttribute("aria-label",e.__pivotExpanded?"Collapse group":"Expand group"),i.setIcon(r,i.resolveIcon(e.__pivotExpanded?"collapse":"expand")),r.addEventListener("click",e=>{e.stopPropagation(),i.onToggle(n)}),o.appendChild(r);const s=document.createElement("span");s.className="pivot-label",s.textContent=String(e.__pivotLabel??""),o.appendChild(s);const l=document.createElement("span");l.className="pivot-count",l.textContent=` (${Number(e.__pivotRowCount)||0})`,o.appendChild(l)}else{const t=e[n.field];o.textContent=null!=t?String(t):""}t.appendChild(o)}),!0}(n,t,{columns:this.gridColumns,rowIndex:i,onToggle:e=>this.toggle(e),resolveIcon:e=>this.resolveIcon(e),setIcon:(e,t)=>this.setIcon(e,t)}):void 0!==n.__pivotRowKey&&this.isActive?function(e,t,i,n){return t.className="data-grid-row pivot-leaf-row",t.setAttribute("data-pivot-depth",String(e.__pivotDepth??0)),t.setAttribute("data-pivot-key",String(e.__pivotRowKey??"")),t.innerHTML="",i.forEach((i,r)=>{const o=document.createElement("div");if(o.className="cell",o.setAttribute("data-col",String(r)),o.setAttribute("data-row",String(n)),o.setAttribute("role","gridcell"),0===r){const t=Number(e.__pivotIndent)||0;o.style.paddingLeft=`${t+20}px`;const i=document.createElement("span");i.className="pivot-label",i.textContent=String(e.__pivotLabel??""),o.appendChild(i)}else{const t=e[i.field];o.textContent=null!=t?String(t):""}t.appendChild(o)}),!0}(n,t,this.gridColumns,i):(this.cleanupPivotStyling(t),!1)}cleanupPivotStyling(e){(e.classList.contains("pivot-group-row")||e.classList.contains("pivot-leaf-row")||e.classList.contains("pivot-grand-total-row"))&&(e.classList.remove("pivot-group-row","pivot-leaf-row","pivot-grand-total-row"),e.classList.add("data-grid-row"),e.removeAttribute("data-pivot-depth"),e.innerHTML="")}onKeyDown(e){if(" "!==e.key)return;if(!this.isActive)return;const t=this.grid._focusRow,i=this.rows[t];return i?.__pivotIsGroup&&i.__pivotHasChildren?(e.preventDefault(),this.toggle(i.__pivotRowKey),this.requestRenderWithFocus(),!0):void 0}afterRender(){this.isActive&&this.config.showGrandTotal&&this.pivotResult?this.renderGrandTotalFooter():this.cleanupGrandTotalFooter();const e=this.animationStyle;if(!1===e||0===this.keysToAnimate.size)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const i="fade"===e?"tbw-pivot-fade-in":"tbw-pivot-slide-in";for(const n of t.querySelectorAll(".pivot-group-row, .pivot-leaf-row")){const e=n.dataset.pivotKey;e&&this.keysToAnimate.has(e)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}renderGrandTotalFooter(){if(!this.pivotResult)return;const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-scroll-area")??e.querySelector(".tbw-grid-content")??e.children[0];if(!t)return;this.grandTotalFooter||(this.grandTotalFooter=document.createElement("div"),this.grandTotalFooter.className="pivot-grand-total-footer",t.appendChild(this.grandTotalFooter));const i={__pivotRowKey:"__grandTotal",__pivotLabel:"Grand Total",__pivotIsGrandTotal:!0,__pivotTotal:this.pivotResult.grandTotal,...this.pivotResult.totals};var n,r,o;n=i,r=this.grandTotalFooter,o=this.gridColumns,r.className="pivot-grand-total-row",r.setAttribute("role","presentation"),r.innerHTML="",o.forEach((e,t)=>{const i=document.createElement("div");if(i.className="cell",i.setAttribute("data-col",String(t)),0===t){const e=document.createElement("span");e.className="pivot-label",e.textContent="Grand Total",i.appendChild(e)}else{const t=n[e.field];i.textContent=null!=t?String(t):""}r.appendChild(i)})}cleanupGrandTotalFooter(){this.grandTotalFooter&&(this.grandTotalFooter.remove(),this.grandTotalFooter=null)}toggle(e){this.userHasToggledExpand=!0,this.expandedKeys.has(e)?this.expandedKeys.delete(e):this.expandedKeys.add(e),this.requestRender()}expand(e){this.userHasToggledExpand=!0,this.expandedKeys.add(e),this.requestRender()}collapse(e){this.userHasToggledExpand=!0,this.expandedKeys.delete(e),this.requestRender()}expandAll(){this.userHasToggledExpand=!0,this.expandAllKeys(),this.requestRender()}collapseAll(){this.userHasToggledExpand=!0,this.expandedKeys.clear(),this.requestRender()}expandAllKeys(){if(!this.pivotResult)return;const e=function(e){const t=[];function i(e){if(e.isGroup&&t.push(e.rowKey),e.children)for(const t of e.children)i(t)}for(const n of e)i(n);return t}(this.pivotResult.rows);for(const t of e)this.expandedKeys.add(t)}isExpanded(e){return this.expandedKeys.has(e)}enablePivot(){0===this.originalColumns.length&&this.captureOriginalColumns(),this.isActive=!0,this.requestRender()}disablePivot(){this.isActive=!1,this.pivotResult=null,this.requestRender()}isPivotActive(){return this.isActive}getPivotResult(){return this.pivotResult}setRowGroupFields(e){this.config.rowGroupFields=e,this.requestRender()}setColumnGroupFields(e){this.config.columnGroupFields=e,this.requestRender()}setValueFields(e){this.config.valueFields=e,this.requestRender()}refresh(){this.pivotResult=null,this.requestRender()}showPanel(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(zi.PANEL_ID)||this.grid.toggleToolPanelSection(zi.PANEL_ID)}hidePanel(){this.grid.closeToolPanel()}togglePanel(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(zi.PANEL_ID)}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(zi.PANEL_ID)}get gridColumns(){return this.grid.columns??[]}refreshIfActive(){this.isActive&&this.refresh(),this.refreshPanel()}buildFieldHeaderMap(){const e=this.getAvailableFields();this.fieldHeaderMap.clear();for(const t of e)this.fieldHeaderMap.set(t.field,t.header)}getAvailableFields(){return this.originalColumns.length>0?this.originalColumns:this.captureOriginalColumns()}captureOriginalColumns(){try{const e=this.grid.getAllColumns?.()??this.grid.columns??[];return this.originalColumns=e.filter(e=>!e.field.startsWith("__pivot")).map(e=>({field:e.field,header:e.header??e.field})),this.originalColumns}catch{return[]}}renderPanel(e){this.panelContainer=e,0===this.originalColumns.length&&this.captureOriginalColumns();const t={onTogglePivot:e=>{e?this.enablePivot():this.disablePivot(),this.refreshPanel()},onAddFieldToZone:(e,t)=>this.addFieldToZone(e,t),onRemoveFieldFromZone:(e,t)=>this.removeFieldFromZone(e,t),onAddValueField:(e,t)=>this.addValueField(e,t),onRemoveValueField:e=>this.removeValueField(e),onUpdateValueAggFunc:(e,t)=>this.updateValueAggFunc(e,t),onOptionChange:(e,t)=>{this.config[e]=t,this.isActive&&this.refresh()},getAvailableFields:()=>this.getAvailableFields()};return Li(e,this.config,this.isActive,t)}refreshPanel(){this.panelContainer&&(this.panelContainer.innerHTML="",this.renderPanel(this.panelContainer))}addFieldToZone(e,t){if("rowGroups"===t){const t=this.config.rowGroupFields??[];t.includes(e)||(this.config.rowGroupFields=[...t,e])}else{const t=this.config.columnGroupFields??[];t.includes(e)||(this.config.columnGroupFields=[...t,e])}this.removeFromOtherZones(e,t),this.refreshIfActive()}removeFieldFromZone(e,t){"rowGroups"===t?this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(t=>t!==e):this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(t=>t!==e),this.refreshIfActive()}removeFromOtherZones(e,t){"rowGroups"!==t&&(this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(t=>t!==e)),"columnGroups"!==t&&(this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(t=>t!==e)),"values"!==t&&(this.config.valueFields=(this.config.valueFields??[]).filter(t=>t.field!==e))}addValueField(e,t){const i=this.config.valueFields??[];i.some(t=>t.field===e)||(this.config.valueFields=[...i,{field:e,aggFunc:t}]),this.removeFromOtherZones(e,"values"),this.refreshIfActive()}removeValueField(e){this.config.valueFields=(this.config.valueFields??[]).filter(t=>t.field!==e),this.refreshIfActive()}updateValueAggFunc(e,t){const i=this.config.valueFields??[],n=i.findIndex(t=>t.field===e);n>=0&&(i[n]={...i[n],aggFunc:t},this.config.valueFields=[...i]),this.isActive&&this.refresh()}}const Oi="tbw-print-isolation-style";async function Fi(e,t={}){const{orientation:i="landscape"}=t,n=e.id;document.querySelectorAll(`#${CSS.escape(n)}`).length>1&&console.warn(`[tbw-grid:print] Multiple elements found with id="${n}". Print isolation may not work correctly. Ensure each grid has a unique ID.`),document.getElementById(Oi)?.remove();const r=function(e,t){const i=document.createElement("style");return i.id=Oi,i.textContent=`\n /* Print isolation: hide everything except the target grid */\n @media print {\n /* Hide all body children by default */\n body > *:not(#${e}) {\n display: none !important;\n }\n\n /* But show the grid and ensure it's not hidden by ancestor rules */\n #${e} {\n display: block !important;\n position: static !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n width: 100% !important;\n max-height: none !important;\n margin: 0 !important;\n padding: 0 !important;\n transform: none !important;\n }\n\n /* If grid is nested, we need to show its ancestors too */\n #${e},\n #${e} * {\n visibility: visible !important;\n }\n\n /* Walk up the DOM and show all ancestors of the grid */\n body *:has(> #${e}),\n body *:has(#${e}) {\n display: block !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n position: static !important;\n transform: none !important;\n background: transparent !important;\n border: none !important;\n padding: 0 !important;\n margin: 0 !important;\n }\n\n /* Hide siblings of ancestors (everything that's not in the path to the grid) */\n body *:has(#${e}) > *:not(:has(#${e})):not(#${e}) {\n display: none !important;\n }\n\n /* Page settings */\n @page {\n size: ${t};\n margin: 1cm;\n }\n\n /* Ensure proper print styling */\n body {\n margin: 0 !important;\n padding: 0 !important;\n background: white !important;\n color-scheme: light !important;\n }\n }\n\n /* Screen: also apply isolation for print preview */\n @media screen {\n /* When this stylesheet is active, we're about to print */\n /* No screen-specific rules needed - isolation only applies to print */\n }\n `,i}(n,i);return document.head.appendChild(r),new Promise(e=>{const t=()=>{window.removeEventListener("afterprint",t),document.getElementById(Oi)?.remove(),e()};window.addEventListener("afterprint",t),window.print(),setTimeout(()=>{window.removeEventListener("afterprint",t),document.getElementById(Oi)?.remove(),e()},5e3)})}const qi={button:!1,orientation:"landscape",warnThreshold:500,maxRows:0,includeTitle:!0,includeTimestamp:!0,title:"",isolate:!1};function Ni(e,t,i){if(t===i)return e;if(t<0||t>=e.length)return e;if(i<0||i>e.length)return e;const n=[...e],[r]=n.splice(t,1);return n.splice(i,0,r),n}const Gi="__tbw_row_drag";function Vi(e){return{startRow:Math.min(e.startRow,e.endRow),startCol:Math.min(e.startCol,e.endCol),endRow:Math.max(e.startRow,e.endRow),endCol:Math.max(e.startCol,e.endCol)}}function $i(e){const t=Vi(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function Bi(e){return e.map($i)}function Wi(e,t,i){return i.some(i=>function(e,t,i){const n=Vi(i);return e>=n.startRow&&e<=n.endRow&&t>=n.startCol&&t<=n.endCol}(e,t,i))}function Ki(e){const t=[],i=Vi(e);for(let n=i.startRow;n<=i.endRow;n++)for(let e=i.startCol;e<=i.endCol;e++)t.push({row:n,col:e});return t}function Ui(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function ji(e,t){const i=Vi(e),n=Vi(t);return i.startRow===n.startRow&&i.startCol===n.startCol&&i.endRow===n.endRow&&i.endCol===n.endCol}const Yi="__tbw_checkbox";function Xi(e,t){return Math.floor(e/t)}async function Zi(e,t,i,n){const r=function(e,t){return{start:e*t,end:(e+1)*t}}(t,i);return e.getRows({startRow:r.start,endRow:r.end,sortModel:n.sortModel,filterModel:n.filterModel})}function Qi(e,t,i){const n=Xi(e,t),r=i.get(n);if(!r)return;return r[e%t]}function Ji(e,t,i){return void 0!==e.id?String(e.id):i?`${i}-${t}`:String(t)}function en(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}function tn(e,t,i=null,n=0){const r=t.childrenField??"children",o=new Set;for(let s=0;s<e.length;s++){const l=e[s],a=Ji(l,s,i),d=l[r];if(Array.isArray(d)&&d.length>0){o.add(a);const e=tn(d,t,a,n+1);for(const t of e)o.add(t)}}return o}function nn(e,t,i,n=null,r=0){const o=i.childrenField??"children";for(let s=0;s<e.length;s++){const l=e[s],a=Ji(l,s,n);if(a===t)return[a];const d=l[o];if(Array.isArray(d)&&d.length>0){const e=nn(d,t,i,a,r+1);if(e)return[a,...e]}}return null}function rn(e,t,i,n){const r=nn(e,t,i);if(!r)return n;const o=new Set(n);for(let s=0;s<r.length-1;s++)o.add(r[s]);return o}function on(e,t="children"){if(!Array.isArray(e)||0===e.length)return!1;for(const i of e){if(!i)continue;const e=i[t];if(Array.isArray(e)&&e.length>0)return!0}return!1}function sn(e){if(0===e.undoStack.length)return{newState:e,action:null};const t=[...e.undoStack],i=t.pop();return i?{newState:{undoStack:t,redoStack:[...e.redoStack,i]},action:i}:{newState:e,action:null}}function ln(e){if(0===e.redoStack.length)return{newState:e,action:null};const t=[...e.redoStack],i=t.pop();return i?{newState:{undoStack:[...e.undoStack,i],redoStack:t},action:i}:{newState:e,action:null}}function an(e){const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}class dn extends rt{static dependencies=[{name:"reorder",required:!1,reason:"Enables drag-to-reorder columns in visibility panel"}];static manifest={queries:[{type:"getContextMenuItems",description:'Contributes "Hide column" item to the header context menu'}]};name="visibility";static PANEL_ID="columns";styles='@layer tbw-plugins{.tbw-visibility-content{display:flex;flex-direction:column;height:100%}.tbw-visibility-list{flex:1;overflow-y:auto;padding:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem))}.tbw-visibility-row{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-menu-item-padding, .375rem .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);border-radius:var(--tbw-border-radius, .25rem);position:relative}.tbw-visibility-row:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-row input[type=checkbox]{cursor:pointer}.tbw-visibility-row.locked span{color:var(--tbw-color-fg-muted)}.tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-row.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-label{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));flex:1;cursor:pointer}.tbw-visibility-row.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-row.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-show-all{margin:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding, .5rem .75rem);border:1px solid var(--tbw-visibility-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius, .25rem);background:var(--tbw-visibility-btn-bg, var(--tbw-color-header-bg));color:var(--tbw-color-fg);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-visibility-show-all:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header{display:flex;align-items:center;padding:var(--tbw-menu-item-padding, .375rem .25rem);font-size:var(--tbw-font-size-sm, .8125rem);font-weight:600;color:var(--tbw-color-fg);border-bottom:1px solid var(--tbw-color-border);margin-top:var(--tbw-spacing-sm, .25rem);position:relative}.tbw-visibility-group-header:first-child{margin-top:0}.tbw-visibility-group-header .tbw-visibility-label{gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-visibility-group-header.reorderable{cursor:grab}.tbw-visibility-group-header.reorderable:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header .tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-group-header.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-group-header.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-group-header.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-group-header.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row--grouped{padding-left:calc(var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem)) + .75rem)}}';get defaultConfig(){return{allowHideAll:!1}}columnListElement=null;isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;draggedGroupId=null;draggedGroupFields=[];clearDragClasses(e){e.querySelectorAll(".tbw-visibility-row, .tbw-visibility-group-header").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-move",()=>{this.columnListElement&&requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})},{signal:this.disconnectSignal})}detach(){this.columnListElement=null,this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}handleQuery(e){if("getContextMenuItems"===e.type){const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field)return;if(i.meta?.lockVisibility)return;return[{id:"visibility/hide-column",label:"Hide Column",icon:"👁",order:30,action:()=>this.hideColumn(i.field)}]}}getToolPanel(){return{id:dn.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(dn.PANEL_ID)||this.grid.toggleToolPanelSection(dn.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(dn.PANEL_ID)}isColumnVisible(e){return this.grid.isColumnVisible(e)}setColumnVisible(e,t){this.grid.setColumnVisible(e,t)}getVisibleColumns(){return this.grid.getAllColumns().filter(e=>e.visible).map(e=>e.field)}getHiddenColumns(){return this.grid.getAllColumns().filter(e=>!e.visible).map(e=>e.field)}showAll(){this.grid.showAllColumns()}toggleColumn(e){this.grid.toggleColumnVisibility(e)}showColumn(e){this.setColumnVisible(e,!0)}hideColumn(e){this.setColumnVisible(e,!1)}getAllColumns(){return this.grid.getAllColumns()}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(dn.PANEL_ID)}renderPanelContent(e){const t=document.createElement("div");t.className="tbw-visibility-content";const i=document.createElement("div");i.className="tbw-visibility-list",t.appendChild(i);const n=document.createElement("button");return n.className="tbw-visibility-show-all",n.textContent="Show All",n.addEventListener("click",()=>{this.grid.showAllColumns(),this.rebuildToggles(i)}),t.appendChild(n),this.columnListElement=i,this.rebuildToggles(i),e.appendChild(t),()=>{this.columnListElement=null,t.remove()}}hasReorderPlugin(){const e=this.grid?.getPluginByName?.("reorder");return!(!e||"function"!=typeof e.moveColumn)}rebuildToggles(e){const t=this.hasReorderPlugin();e.innerHTML="";const i=this.grid.getAllColumns().filter(e=>!e.utility),n=this.grid.query("getColumnGrouping"),r=n?.flat().filter(e=>e&&e.fields.length>0)??[];if(0===r.length)return void this.renderFlatColumnList(i,t,e);const o=new Map;for(const l of r)for(const e of l.fields)o.set(e,l);const s=new Set;for(const l of i){const n=o.get(l.field);if(n){if(!s.has(n.id)){s.add(n.id);const r=new Set(n.fields),o=i.filter(e=>r.has(e.field));o.length>0&&this.renderGroupSection(n,o,t,e)}}else{const n=i.indexOf(l);e.appendChild(this.createColumnRow(l,n,t,e))}}}renderGroupSection(e,t,i,n){const r=document.createElement("div");r.className="tbw-visibility-group-header",r.setAttribute("data-group-id",e.id),i&&(r.draggable=!0,r.classList.add("reorderable"),this.setupGroupDragListeners(r,e,n));const o=document.createElement("label");o.className="tbw-visibility-label";const s=document.createElement("input");s.type="checkbox";const l=t.filter(e=>e.visible).length,a=t.every(e=>e.lockVisible);l===t.length?(s.checked=!0,s.indeterminate=!1):0===l?(s.checked=!1,s.indeterminate=!1):(s.checked=!1,s.indeterminate=!0),s.disabled=a,s.addEventListener("change",()=>{const e=s.checked;for(const i of t)i.lockVisible||this.grid.setColumnVisible(i.field,e);setTimeout(()=>this.rebuildToggles(n),0)});const d=document.createElement("span");if(d.textContent=e.label,o.appendChild(s),o.appendChild(d),r.appendChild(o),i){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,this.resolveIcon("dragHandle")),e.title="Drag to reorder group",r.insertBefore(e,o)}n.appendChild(r);const c=this.grid.getAllColumns().filter(e=>!e.utility);for(const h of t){const e=c.findIndex(e=>e.field===h.field),t=this.createColumnRow(h,e,i,n);t.classList.add("tbw-visibility-row--grouped"),n.appendChild(t)}}renderFlatColumnList(e,t,i){const n=this.grid.getAllColumns().filter(e=>!e.utility);for(const r of e){const e=n.findIndex(e=>e.field===r.field);i.appendChild(this.createColumnRow(r,e,t,i))}}createColumnRow(e,t,i,n){const r=e.header||e.field,o=document.createElement("div");o.className=e.lockVisible?"tbw-visibility-row locked":"tbw-visibility-row",o.setAttribute("data-field",e.field),o.setAttribute("data-index",String(t)),i&&an(e)&&(o.draggable=!0,o.classList.add("reorderable"),this.setupDragListeners(o,e.field,t,n));const s=document.createElement("label");s.className="tbw-visibility-label";const l=document.createElement("input");l.type="checkbox",l.checked=e.visible,l.disabled=e.lockVisible??!1,l.addEventListener("change",()=>{this.grid.toggleColumnVisibility(e.field),setTimeout(()=>this.rebuildToggles(n),0)});const a=document.createElement("span");if(a.textContent=r,s.appendChild(l),s.appendChild(a),i&&an(e)){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,this.resolveIcon("dragHandle")),e.title="Drag to reorder",o.appendChild(e)}return o.appendChild(s),o}setupGroupDragListeners(e,t,i){e.addEventListener("dragstart",n=>{this.isDragging=!0,this.draggedGroupId=t.id,this.draggedGroupFields=[...t.fields],this.draggedField=null,this.draggedIndex=null,n.dataTransfer&&(n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",`group:${t.id}`)),e.classList.add("dragging"),i.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&e.classList.add("dragging")})}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedGroupId=null,this.draggedGroupFields=[],this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(i)}),e.addEventListener("dragover",n=>{if(n.preventDefault(),!this.isDragging)return;if(this.draggedGroupId===t.id)return;if(!this.draggedGroupId)return;const r=e.getBoundingClientRect(),o=r.top+r.height/2,s=n.clientY<o;this.clearDragClasses(i),e.classList.add("drop-target"),e.classList.toggle("drop-before",s),e.classList.toggle("drop-after",!s)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",n=>{if(n.preventDefault(),!this.isDragging||!this.draggedGroupId||this.draggedGroupId===t.id)return;const r=e.getBoundingClientRect(),o=n.clientY<r.top+r.height/2;this.executeGroupDrop(this.draggedGroupFields,t.fields,o,i)})}executeGroupDrop(e,t,i,n){const r=this.grid.getAllColumns().map(e=>e.field),o=r.filter(t=>!e.includes(t)),s=i?t[0]:t[t.length-1],l=o.indexOf(s);if(-1===l)return;const a=i?l:l+1,d=r.filter(t=>e.includes(t));o.splice(a,0,...d),this.grid.setColumnOrder(o),requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})}setupDragListeners(e,t,i,n){e.addEventListener("dragstart",n=>{this.isDragging=!0,this.draggedField=t,this.draggedIndex=i,this.draggedGroupId=null,this.draggedGroupFields=[],n.dataTransfer&&(n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",t)),e.classList.add("dragging")}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(n)}),e.addEventListener("dragover",r=>{if(r.preventDefault(),!this.isDragging)return;if(this.draggedGroupId){if(e.classList.contains("tbw-visibility-row--grouped"))return}else if(this.draggedField===t)return;const o=e.getBoundingClientRect(),s=o.top+o.height/2;this.dropIndex=r.clientY<s?i:i+1,this.clearDragClasses(n),this.draggedGroupId?(n.querySelector(`.tbw-visibility-group-header[data-group-id="${this.draggedGroupId}"]`)?.classList.add("dragging"),n.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&e.classList.add("dragging")})):this.draggedField&&n.querySelector(`.tbw-visibility-row[data-field="${this.draggedField}"]`)?.classList.add("dragging"),e.classList.add("drop-target"),e.classList.toggle("drop-before",r.clientY<s),e.classList.toggle("drop-after",r.clientY>=s)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",i=>{if(i.preventDefault(),!this.isDragging)return;if(this.draggedGroupId&&this.draggedGroupFields.length>0){if(e.classList.contains("tbw-visibility-row--grouped"))return;const r=e.getBoundingClientRect(),o=i.clientY<r.top+r.height/2;return void this.executeGroupDrop(this.draggedGroupFields,[t],o,n)}const r=this.draggedField,o=this.draggedIndex,s=this.dropIndex;if(null===r||null===o||null===s)return;const l=s>o?s-1:s;if(l!==o){const e=this.grid.getAllColumns(),t=e.filter(e=>!e.utility),i=t[l]?.field,n={field:r,fromIndex:o,toIndex:i?e.findIndex(e=>e.field===i):e.length};this.emit("column-reorder-request",n)}})}}e.BLANK_FILTER_VALUE=Ft,e.BaseGridPlugin=rt,e.ClipboardPlugin=class extends rt{static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:"\t",newline:"\n",quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e);e.addEventListener("paste",e=>this.#wt(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#mt(e.target),!0)}#mt(e){const t=this.#bt();if(t&&0===t.ranges.length){const t=this.#vt(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()}#wt(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const i=ht(t,this.config),n=this.#bt(),r=n?.ranges?.[0],o=r?.from.row??0,s=r?.from.col??0,l=r&&("range"===n?.mode||"row"===n?.mode)&&(r.from.row!==r.to.row||r.from.col!==r.to.col)?{endRow:r.to.row,endCol:r.to.col}:null,a=l?.endCol??this.visibleColumns.length-1,d=this.visibleColumns[s],c=d?{row:o,col:s,field:d.field,bounds:l}:null,h=[],u=i[0]?.length??0;for(let p=0;p<u&&s+p<=a;p++){const e=this.visibleColumns[s+p];e&&h.push(e.field)}const g={rows:i,text:t,target:c,fields:h};this.emit("paste",g),this.#yt(g)}#yt(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??ut)(e,this.grid)}#bt(){const e=this.grid?.query("getSelection");return e?.[0]}#Ct(e){const t=this.#bt();let i,n;if(e?.columns)i=at(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],n=Math.min(e.from.col,e.to.col),r=Math.max(e.from.col,e.to.col);i=at(this.visibleColumns.slice(n,r+1))}else i=at(this.columns);if(e?.rowIndices)n=dt(this.rows,e.rowIndices);else if(t?.ranges.length){const e=t.ranges[t.ranges.length-1],i=Math.min(e.from.row,e.to.row),r=Math.max(e.from.row,e.to.row);n=[];for(let t=i;t<=r;t++){const e=this.rows[t];e&&n.push(e)}}else n=this.rows;return{columns:i,rows:n}}#xt(e,t,i){const n=i?.delimiter??this.config.delimiter??"\t",r=i?.newline??this.config.newline??"\n",o=i?.includeHeaders??this.config.includeHeaders??!1,s=i?.processCell??this.config.processCell,l=[];o&&l.push(e.map(e=>e.header||e.field).join(n));for(const a of t){const t=e.map(e=>{const t=a[e.field];return s?s(t,e.field,a):ct(t)});l.push(t.join(n))}return l.join(r)}#vt(e){const t=e.closest("[data-field-cache]");if(!t)return null;const i=t.dataset.fieldCache,n=t.dataset.row;if(!i||!n)return null;const r=parseInt(n,10);if(isNaN(r))return null;const o=this.columns.findIndex(e=>e.field===i);return-1===o?null:{row:r,col:o}}getSelectionAsText(e){const{columns:t,rows:i}=this.#Ct(e);return 0===t.length||0===i.length?"":this.#xt(t,i,e)}async copy(e){const{columns:t,rows:i}=this.#Ct(e);if(0===t.length||0===i.length)return"";const n=this.#xt(t,i,e);return await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){console.warn("[copyToClipboard] Clipboard API failed:",t);const i=document.createElement("textarea");i.value=e,i.style.position="fixed",i.style.opacity="0",i.style.pointerEvents="none",document.body.appendChild(i),i.select();const n=document.execCommand("copy");return document.body.removeChild(i),n}}(n),this.lastCopied={text:n,timestamp:Date.now()},this.emit("copy",{text:n,rowCount:i.length,columnCount:t.length}),n}async copyRows(e,t){return 0===e.length?"":this.copy({...t,rowIndices:e})}async paste(){const e=await async function(){try{return await navigator.clipboard.readText()}catch{return""}}();return e?ht(e,this.config):null}getLastCopied(){return this.lastCopied}},e.ColumnVirtualizationPlugin=class extends rt{name="columnVirtualization";get defaultConfig(){return{autoEnable:!0,threshold:30,overscan:3}}isVirtualized=!1;startCol=0;endCol=0;scrollLeft=0;totalWidth=0;columnWidths=[];columnOffsets=[];originalColumns=[];attach(e){super.attach(e);const t=this.columns;this.columnWidths=pt(t),this.columnOffsets=ft(t),this.totalWidth=wt(t),this.endCol=t.length-1}detach(){this.#Et(),this.columnWidths=[],this.columnOffsets=[],this.originalColumns=[],this.isVirtualized=!1,this.startCol=0,this.endCol=0,this.scrollLeft=0,this.totalWidth=0}#Et(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".header-row");t&&(t.style.paddingLeft="",t.style.minWidth="");e.querySelectorAll(".data-grid-row").forEach(e=>{e.style.paddingLeft=""});const i=e.querySelector(".rows-viewport .rows");i&&(i.style.width="");const n=e.querySelector(".rows-body");n&&(n.style.minWidth="")}processColumns(e){(0===this.originalColumns.length||e.length>=this.originalColumns.length)&&(this.originalColumns=e,this.columnWidths=pt(e),this.columnOffsets=ft(e),this.totalWidth=wt(e));const t=this.originalColumns,i=(n=t.length,r=this.config.threshold??30,!!(this.config.autoEnable??!0)&&n>r);var n,r;if(this.isVirtualized=i??!1,!i)return this.startCol=0,this.endCol=t.length-1,[...t];const o=this.grid.clientWidth||800,s=mt(this.scrollLeft,o,this.columnOffsets,this.columnWidths,this.config.overscan??3);return this.startCol=s.startCol,this.endCol=s.endCol,s.visibleColumns.map(e=>t[e])}afterRender(){if(!this.isVirtualized)return;const e=this.gridElement;if(!e)return;const t=this.columnOffsets[this.startCol]??0,i=e.querySelector(".header-row"),n=e.querySelectorAll(".data-grid-row");i&&(i.style.paddingLeft=`${t}px`,i.style.minWidth=`${this.totalWidth}px`),n.forEach(e=>{e.style.paddingLeft=`${t}px`});const r=e.querySelector(".rows-viewport .rows");r&&(r.style.width=`${this.totalWidth}px`);const o=e.querySelector(".rows-body");o&&(o.style.minWidth=`${this.totalWidth}px`)}onScroll(e){if(!this.isVirtualized)return;Math.abs(e.scrollLeft-this.scrollLeft)<1||(this.scrollLeft=e.scrollLeft,this.requestColumnsRender())}getIsVirtualized(){return this.isVirtualized}getVisibleColumnRange(){return{start:this.startCol,end:this.endCol}}scrollToColumn(e){const t=this.columnOffsets[e]??0;this.grid.scrollLeft=t}getColumnOffset(e){return this.columnOffsets[e]??0}getTotalWidth(){return this.totalWidth}},e.ContextMenuPlugin=Lt,e.DEFAULT_ANIMATION_CONFIG=i,e.DEFAULT_GRID_ICONS=r,e.DGEvents={CELL_CHANGE:"cell-change",CELL_COMMIT:"cell-commit",ROW_COMMIT:"row-commit",EDIT_OPEN:"edit-open",EDIT_CLOSE:"edit-close",CHANGED_ROWS_RESET:"changed-rows-reset",MOUNT_EXTERNAL_VIEW:"mount-external-view",MOUNT_EXTERNAL_EDITOR:"mount-external-editor",SORT_CHANGE:"sort-change",COLUMN_RESIZE:"column-resize",ACTIVATE_CELL:"activate-cell",CELL_ACTIVATE:"cell-activate",GROUP_TOGGLE:"group-toggle",COLUMN_STATE_CHANGE:"column-state-change"},e.DataGridElement=nt,e.EditingPlugin=class extends rt{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>!0===e},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'}],events:[{type:"cell-edit-committed",description:"Emitted when a cell edit is committed (for plugin-to-plugin coordination)"}],queries:[{type:"isEditing",description:"Returns whether any cell is currently being edited"}]};name="editing";styles="@layer tbw-plugins{tbw-grid{--tbw-editing-bg: var(--tbw-color-selection);--tbw-editing-row-bg: var(--tbw-editing-bg);--tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));--tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);--tbw-font-size-editor: inherit;--tbw-editing-row-outline-color: var(--tbw-color-accent);--tbw-editing-row-outline-width: 1px;--tbw-invalid-bg: light-dark(#fef2f2, #450a0a);--tbw-invalid-border-color: light-dark(#ef4444, #f87171)}tbw-grid:not(.tbw-grid-mode) .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:calc(var(--tbw-row-height) + 2px);align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}tbw-grid .data-grid-row>.cell[data-invalid=true]{background:var(--tbw-invalid-bg);outline:1px solid var(--tbw-invalid-border-color);outline-offset:-1px}}";get defaultConfig(){return{mode:"row",editOn:"click"}}get#Rt(){return"grid"===this.config.mode}#St=-1;#_t;#At;#kt=-1;#Tt=new Map;#Lt=new Set;#Mt=new Set;#Pt=new Map;#Ht=!1;#It=-1;#Dt=new Map;#zt=!1;#Ot=!1;#Ft=!1;attach(e){super.attach(e);const t=this.disconnectSignal,i=e;i._activeEditRows=-1,i._rowEditSnapshots=new Map,Object.defineProperty(e,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(e,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),e.resetChangedRows=e=>this.resetChangedRows(e),e.beginBulkEdit=(e,t)=>{t&&this.beginCellEdit(e,t)},document.addEventListener("keydown",e=>{if(!this.#Rt&&"Escape"===e.key&&-1!==this.#St){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}this.#qt(this.#St,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",e=>{if(this.#Rt)return;if(-1===this.#St)return;const t=i.findRenderedRowElement?.(this.#St);if(!t)return;if((e.composedPath&&e.composedPath()||[]).includes(t))return;const n=e.target;if(!n||!this.grid.containsFocus?.(n)){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}queueMicrotask(()=>{-1!==this.#St&&this.#qt(this.#St,!1)})}},{signal:t}),this.config.focusTrap&&this.gridElement.addEventListener("focusout",e=>{if(this.#Rt)return;if(-1===this.#St)return;const t=e.relatedTarget;t&&this.grid.containsFocus?.(t)||t&&this.gridElement.contains(t)||queueMicrotask(()=>{-1!==this.#St&&this.#Nt()})},{signal:t}),this.gridElement.addEventListener("cell-change",e=>{const t=e.detail;if("user"===t.source)return;const i=`${t.rowIndex}:${t.field}`,n=this.#Pt.get(i);n&&n(t.newValue)},{signal:t}),this.#Rt&&(i._isGridEditMode=!0,this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",e=>{const t=e.target;if(t.matches(D)){if(this.#Ot)return t.blur(),void this.gridElement.focus();this.#zt=!0}},{signal:t}),this.gridElement.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.gridElement.contains(t)||this.grid.containsFocus?.(t))&&t.matches(D)||(this.#zt=!1)},{signal:t}),this.gridElement.addEventListener("keydown",e=>{if("Escape"===e.key&&this.#zt){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}const t=document.activeElement;t&&this.gridElement.contains(t)&&(t.blur(),this.gridElement.focus()),this.#zt=!1,this.#Ot=!0,e.preventDefault(),e.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",e=>{e.target.matches(D)&&(this.#Ot=!1)},{signal:t}))}detach(){this.gridElement._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#St=-1,this.#_t=void 0,this.#At=void 0,this.#kt=-1,this.#Tt.clear(),this.#Lt.clear(),this.#Mt.clear(),this.#Pt.clear(),this.#zt=!1,this.#Ot=!1,this.#Ft=!1,super.detach()}handleQuery(e){if("isEditing"===e.type)return this.#Rt||-1!==this.#St}onCellClick(e){if(this.#Rt)return!1;const t=this.grid,i=this.config.editOn??t.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;if("click"!==i&&"dblclick"!==i)return!1;const n="dblclick"===e.originalEvent.type;if("click"===i&&n)return!1;if("dblclick"===i&&!n)return!1;const{rowIndex:r}=e,o=t._columns?.some(e=>e.editable);return!!o&&(e.originalEvent.stopPropagation(),this.beginBulkEdit(r),!0)}onKeyDown(e){const t=this.grid;if("Escape"===e.key){if(this.#Rt&&this.#zt){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}const t=document.activeElement;return t&&this.gridElement.contains(t)&&t.blur(),this.#zt=!1,this.requestAfterRender(),!0}if(-1!==this.#St&&!this.#Rt){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}return this.#qt(this.#St,!0),!0}}if(this.#Rt&&!this.#zt&&("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key))return!1;if(this.#Rt&&this.#zt&&("ArrowUp"===e.key||"ArrowDown"===e.key))return!0;if(("ArrowUp"===e.key||"ArrowDown"===e.key)&&-1!==this.#St&&!this.#Rt){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}const i=t._rows.length-1,n=this.#St;return this.#qt(n,!1),"ArrowDown"===e.key?t._focusRow=Math.min(i,t._focusRow+1):t._focusRow=Math.max(0,t._focusRow-1),e.preventDefault(),K(t),this.requestAfterRender(),!0}if("Tab"===e.key&&(-1!==this.#St||this.#Rt)){if(e.preventDefault(),this.#Ft)return this.#qt(this.#St,!1),!0;const t=!e.shiftKey;return this.#Gt(t),!0}if(" "===e.key||"Spacebar"===e.key){if(-1!==this.#St)return!1;const i=t._focusRow,n=t._focusCol;if(i>=0&&n>=0){const r=t._visibleColumns[n],o=t._rows[i];if(r?.editable&&"boolean"===r.type&&o){const t=r.field;if(Pt(t)){const n=!o[t];return this.#Vt(i,r,n,o),e.preventDefault(),this.requestRender(),!0}}}return!1}if(!("Enter"!==e.key||e.shiftKey||e.ctrlKey||e.altKey||e.metaKey)){if(this.#Rt&&!this.#zt)return this.#Nt(),!0;if(-1!==this.#St){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}return!1}const i=this.config.editOn??t.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;const n=t._focusRow,r=t._focusCol;if(n>=0){const i=t._columns?.some(e=>e.editable);if(i){const i=t._visibleColumns[r],o=t._rows[n],s=i?.field??"",l=s&&o?o[s]:void 0,a=this.gridElement.querySelector(`[data-row="${n}"][data-col="${r}"]`),d=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:n,colIndex:r,field:s,value:l,row:o,cellEl:a,trigger:"keyboard",originalEvent:e}});this.gridElement.dispatchEvent(d);const c=new CustomEvent("activate-cell",{cancelable:!0,bubbles:!0,detail:{row:n,col:r}});return this.gridElement.dispatchEvent(c),d.defaultPrevented||c.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(n),!0)}}return!1}if("F2"===e.key){if(-1!==this.#St||this.#Rt)return!1;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return!1;const i=t._focusRow,n=t._focusCol;if(i>=0&&n>=0){const r=t._visibleColumns[n];if(r?.editable&&r.field)return e.preventDefault(),this.beginCellEdit(i,r.field),!0}return!1}return!1}processColumns(e){const t=this.grid,i=t.effectiveConfig?.typeDefaults,n=t.__frameworkAdapter;return i||n?.getTypeDefault?e.map(e=>{if(!e.type)return e;let t;if(i?.[e.type]?.editorParams&&(t=i[e.type].editorParams),!t&&n?.getTypeDefault){const i=n.getTypeDefault(e.type);i?.editorParams&&(t=i.editorParams)}return t?{...e,editorParams:{...t,...e.editorParams}}:e}):e}afterRender(){const e=this.grid;if(this.#Ht&&(this.#Ht=!1,this.#$t(e)),-1!==this.#It){const t=this.#It;this.#It=-1,e.animateRow?.(t,"change")}if(!this.#Rt&&0!==this.#Mt.size)for(const t of this.#Mt){const[i,n]=t.split(":"),r=parseInt(i,10),o=parseInt(n,10),s=e.findRenderedRowElement?.(r);if(!s)continue;const l=s.querySelector(`.cell[data-col="${o}"]`);if(!l||l.classList.contains("editing"))continue;const a=e._rows[r],d=e._visibleColumns[o];a&&d&&this.#Bt(a,r,d,o,l,!0)}}afterCellRender(e){if(!this.#Rt)return;const{row:t,rowIndex:i,column:n,colIndex:r,cellElement:o}=e;n.editable&&(o.classList.contains("editing")||this.#Bt(t,i,n,r,o,!0))}onScrollRender(){this.afterRender()}get changedRows(){const e=[];for(const t of this.#Lt){const i=this.grid.getRow(t);i&&e.push(i)}return e}get changedRowIds(){return Array.from(this.#Lt)}get activeEditRow(){return this.#St}get activeEditCol(){return this.#kt}isRowEditing(e){return this.#St===e}isCellEditing(e,t){return this.#Mt.has(`${e}:${t}`)}isRowChanged(e){const t=this.grid,i=t._rows[e];if(!i)return!1;try{const e=t.getRowId?.(i);return!!e&&this.#Lt.has(e)}catch{return!1}}isRowChangedById(e){return this.#Lt.has(e)}setInvalid(e,t,i=""){let n=this.#Dt.get(e);n||(n=new Map,this.#Dt.set(e,n)),n.set(t,i),this.#Wt(e,t,!0)}clearInvalid(e,t){const i=this.#Dt.get(e);i&&(i.delete(t),0===i.size&&this.#Dt.delete(e)),this.#Wt(e,t,!1)}clearRowInvalid(e){const t=this.#Dt.get(e);if(t){const i=Array.from(t.keys());this.#Dt.delete(e),i.forEach(t=>this.#Wt(e,t,!1))}}clearAllInvalid(){const e=Array.from(this.#Dt.entries());this.#Dt.clear(),e.forEach(([e,t])=>{t.forEach((t,i)=>this.#Wt(e,i,!1))})}isCellInvalid(e,t){return this.#Dt.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#Dt.get(e)?.get(t)}hasInvalidCells(e){const t=this.#Dt.get(e);return!!t&&t.size>0}getInvalidFields(e){return new Map(this.#Dt.get(e)??[])}#Wt(e,t,i){const n=this.grid,r=n._visibleColumns?.findIndex(e=>e.field===t);if(-1===r||void 0===r)return;const o=n._rows,s=o?.findIndex(t=>{try{return n.getRowId?.(t)===e}catch{return!1}});if(-1===s||void 0===s)return;const l=n.findRenderedRowElement?.(s),a=l?.querySelector(`.cell[data-col="${r}"]`);if(a)if(i){a.setAttribute("data-invalid","true");const i=this.#Dt.get(e)?.get(t);i&&a.setAttribute("title",i)}else a.removeAttribute("data-invalid"),a.removeAttribute("title")}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#Lt.clear(),this.#Kt(),e||this.emit("changed-rows-reset",{rows:t,ids:i});const n=this.grid;n._rowPool?.forEach(e=>e.classList.remove("changed"))}beginCellEdit(e,t){const i=this.grid,n=i._visibleColumns.findIndex(e=>e.field===t);if(-1===n)return;const r=i._visibleColumns[n];if(!r?.editable)return;const o=i.findRenderedRowElement?.(e),s=o?.querySelector(`.cell[data-col="${n}"]`);s&&(this.#Ft=!0,this.#Ut(e,n,s))}beginBulkEdit(e){const t=this.grid;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return;const i=t._columns?.some(e=>e.editable);if(!i)return;const n=t.findRenderedRowElement?.(e);if(!n)return;this.#Ft=!1;const r=t._rows[e];this.#jt(e,r),Array.from(n.children).forEach((i,n)=>{const o=t._visibleColumns[n];if(o?.editable){const t=i;t.classList.contains("editing")||this.#Bt(r,e,o,n,t,!0)}}),setTimeout(()=>{let e=n.querySelector(`.cell[data-col="${t._focusCol}"]`);if(e?.classList.contains("editing")||(e=n.querySelector(".cell.editing")),e?.classList.contains("editing")){const t=e.querySelector(D);try{t?.focus({preventScroll:!0})}catch{}}},0)}commitActiveRowEdit(){-1!==this.#St&&this.#qt(this.#St,!1)}cancelActiveRowEdit(){-1!==this.#St&&this.#qt(this.#St,!0)}#Ut(e,t,i){const n=this.grid,r=n._rows[e],o=n._visibleColumns[t];r&&o?.editable&&(i.classList.contains("editing")||(this.#St!==e&&this.#jt(e,r),this.#kt=t,this.#Bt(r,e,o,t,i,!1)))}#Nt(){const e=this.grid,t=e._focusRow,i=e._focusCol;if(t<0||i<0)return;const n=e.findRenderedRowElement?.(t),r=n?.querySelector(`.cell[data-col="${i}"]`);if(r?.classList.contains("editing")){const e=r.querySelector(D);e&&(this.#Ot=!1,e.focus(),this.#zt=!0,e instanceof HTMLInputElement&&("text"===e.type||"number"===e.type)&&e.select())}}#Gt(e){const t=this.grid,i=t._rows,n=this.#Rt?t._focusRow:this.#St,r=t._visibleColumns.map((e,t)=>e.editable?t:-1).filter(e=>e>=0);if(0===r.length)return;const o=r.indexOf(t._focusCol)+(e?1:-1);if(o>=0&&o<r.length){t._focusCol=r[o];const e=t.findRenderedRowElement?.(n),i=e?.querySelector(`.cell[data-col="${r[o]}"]`);if(i?.classList.contains("editing")){const e=i.querySelector(D);e?.focus({preventScroll:!0})}return void K(t,{forceHorizontalScroll:!0})}const s=n+(e?1:-1);s>=0&&s<i.length&&(this.#Rt?(t._focusRow=s,t._focusCol=e?r[0]:r[r.length-1],K(t,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const e=t.findRenderedRowElement?.(s),i=e?.querySelector(`.cell[data-col="${t._focusCol}"]`);if(i?.classList.contains("editing")){const e=i.querySelector(D);e?.focus({preventScroll:!0})}},0)):(this.#qt(n,!1),t._focusRow=s,t._focusCol=e?r[0]:r[r.length-1],this.beginBulkEdit(s),K(t,{forceHorizontalScroll:!0})))}#Kt(){const e=this.grid;e._activeEditRows=this.#St,e._rowEditSnapshots=this.#Tt}#jt(e,t){if(this.#St!==e){this.#Tt.set(e,{...t}),this.#St=e,this.#At=t;const i=this.grid;try{this.#_t=i.getRowId?.(t)??void 0}catch{this.#_t=void 0}this.#Kt(),this.#Rt||this.emit("edit-open",{rowIndex:e,rowId:this.#_t??"",row:t})}}#qt(e,t){if(this.#St!==e)return;const i=this.grid,n=this.#Tt.get(e),r=i.findRenderedRowElement?.(e);let o=this.#_t;const s=o?i._getRowEntry(o):void 0,l=s?.row??this.#At??i._rows[e];if(!o&&l)try{o=i.getRowId?.(l)}catch{}if(!t&&r&&l){r.querySelectorAll(".cell.editing").forEach(t=>{const n=Number(t.getAttribute("data-col"));if(isNaN(n))return;const r=i._visibleColumns[n];if(!r)return;if(t.hasAttribute("data-editor-managed"))return;const o=t.querySelector("input,textarea,select");if(o){const t=r.field,i=l[t],n=Ht(o,r,i);i!==n&&this.#Vt(e,r,n,l)}})}if(t||this.#Rt||!l||this.emit("before-edit-close",{rowIndex:e,rowId:o??"",row:l}),t&&n&&l)Object.keys(n).forEach(e=>{l[e]=n[e]}),o&&(this.#Lt.delete(o),this.clearRowInvalid(o));else if(!t&&l){const t=this.#Yt(n,l),i=o?this.#Lt.has(o):t,r=this.emitCancelable("row-commit",{rowIndex:e,rowId:o??"",row:l,oldValue:n,newValue:l,changed:i,changedRows:this.changedRows,changedRowIds:this.changedRowIds});r&&n?(Object.keys(n).forEach(e=>{l[e]=n[e]}),o&&(this.#Lt.delete(o),this.clearRowInvalid(o))):!r&&t&&this.isAnimationEnabled&&(this.#It=e)}this.#Tt.delete(e),this.#St=-1,this.#_t=void 0,this.#At=void 0,this.#kt=-1,this.#Ft=!1,this.#Kt();for(const a of this.#Mt)a.startsWith(`${e}:`)&&this.#Mt.delete(a);for(const a of this.#Pt.keys())a.startsWith(`${e}:`)&&this.#Pt.delete(a);this.#Ht=!0,r?(r.querySelectorAll(".cell.editing").forEach(e=>{e.classList.remove("editing"),function(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing")}(e.parentElement)}),i.refreshVirtualWindow(!0)):(this.#$t(i),this.#Ht=!1),!this.#Rt&&l&&this.emit("edit-close",{rowIndex:e,rowId:o??"",row:l,reverted:t})}#Vt(e,t,i,n){const r=t.field;if(!Pt(r))return;const o=n[r];if(o===i)return;const s=this.grid;let l;try{l=this.grid.getRowId(n)}catch{}const a=!l||!this.#Lt.has(l),d=l?e=>this.grid.updateRow(l,e,"cascade"):It;let c=!1;const h=l?e=>{c=!0,this.setInvalid(l,r,e??"")}:()=>{};if(this.emitCancelable("cell-commit",{row:n,rowId:l??"",field:r,oldValue:o,value:i,rowIndex:e,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:a,updateRow:d,setInvalid:h}))return;l&&!c&&this.isCellInvalid(l,r)&&this.clearInvalid(l,r),n[r]=i,l&&this.#Lt.add(l),this.#Kt(),this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:r,oldValue:o,newValue:i});const u=s.findRenderedRowElement?.(e);u&&u.classList.add("changed")}#Bt(e,t,i,n,r,o){if(!i.editable)return;if(r.classList.contains("editing"))return;let s;try{s=this.grid.getRowId(e)}catch{}const l=s?e=>this.grid.updateRow(s,e,"cascade"):It,a=Pt(i.field)?e[i.field]:void 0;r.classList.add("editing"),this.#Mt.add(`${t}:${n}`);const d=r.parentElement;d&&function(e){const t=(e.__editingCellCount??0)+1;e.__editingCellCount=t,e.setAttribute("data-has-editing","")}(d);let c=!1;const h=n=>{if(c||!this.#Rt&&-1===this.#St)return;const r=this.grid,o=s?r._getRowEntry(s):void 0,l=o?.row??e,a=o?.index??t;this.#Vt(a,i,n,l)},u=()=>{if(c=!0,Pt(i.field)){const t=this.grid,n=s?t._getRowEntry(s):void 0;(n?.row??e)[i.field]=a}},g=document.createElement("div");g.className="tbw-editor-host",r.innerHTML="",r.appendChild(g),g.addEventListener("keydown",e=>{if("Enter"===e.key){if(this.#Rt){e.stopPropagation(),e.preventDefault();const t=g.querySelector("input,textarea,select");return void(t&&h(Ht(t,i,a)))}if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}e.stopPropagation(),e.preventDefault(),c=!0,this.#qt(t,!1)}if("Escape"===e.key){if(this.#Rt)return e.stopPropagation(),void e.preventDefault();if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}e.stopPropagation(),e.preventDefault(),u(),this.#qt(t,!0)}});const p=i,f=p.__editorTemplate,w=function(e,t){if(t.editor)return t.editor;if(t.__editorTemplate)return"template";if(!t.type)return;const i=e.effectiveConfig?.typeDefaults;if(i?.[t.type]?.editor)return i[t.type].editor;const n=e.__frameworkAdapter;if(n?.getTypeDefault){const e=n.getTypeDefault(t.type);if(e?.editor)return e.editor}}(this.grid,p)??Mt(i),m=a,b=`${t}:${i.field}`,v=[];this.#Pt.set(b,e=>{for(const t of v)t(e)});const y=e=>{v.push(e)};if("template"===w&&f)this.#Xt(g,p,e,a,h,u,o,t),y(e=>{const t=g.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if("string"==typeof w){const e=document.createElement(w);e.value=m,e.addEventListener("change",()=>h(e.value)),y(t=>{e.value=t}),g.appendChild(e),o||queueMicrotask(()=>{const e=g.querySelector(D);e?.focus({preventScroll:!0})})}else if("function"==typeof w){const t=w({row:e,rowId:s??"",value:m,field:i.field,column:i,commit:h,cancel:u,updateRow:l,onValueChange:y});if("string"==typeof t)g.innerHTML=t,function(e,t,i,n){const r=e.querySelector("input,textarea,select");r&&(r.addEventListener("blur",()=>{i(Ht(r,t,n))}),r instanceof HTMLInputElement&&"checkbox"===r.type?r.addEventListener("change",()=>i(r.checked)):r instanceof HTMLSelectElement&&r.addEventListener("change",()=>i(Ht(r,t,n))))}(g,i,h,a),y(e=>{const t=g.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if(t instanceof Node){g.appendChild(t);t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?y(e=>{t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??"")}):r.setAttribute("data-editor-managed","")}o||queueMicrotask(()=>{const e=g.querySelector(D);e?.focus({preventScroll:!0})})}else if(w&&"object"==typeof w){const t=document.createElement("div");t.setAttribute("data-external-editor",""),t.setAttribute("data-field",i.field),g.appendChild(t),r.setAttribute("data-editor-managed","");const n={row:e,rowId:s??"",value:m,field:i.field,column:i,commit:h,cancel:u,updateRow:l,onValueChange:y};if(w.mount)try{w.mount({placeholder:t,context:n,spec:w})}catch(C){console.warn(`[tbw-grid] External editor mount error for column '${i.field}':`,C)}else this.grid.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:t,spec:w,context:n}}))}}#Xt(e,t,i,n,r,o,s,l){const a=t.__editorTemplate;if(!a)return;const d=a.cloneNode(!0),c=t.__compiledEditor;c?d.innerHTML=c({row:i,value:n,field:t.field,column:t,commit:r,cancel:o}):d.querySelectorAll("*").forEach(e=>{1===e.childNodes.length&&e.firstChild?.nodeType===Node.TEXT_NODE&&(e.textContent=e.textContent?.replace(/{{\s*value\s*}}/g,null==n?"":String(n)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(e,t)=>{if(!Pt(t))return"";const n=i[t];return null==n?"":String(n)})||"")});const h=d.querySelector("input,textarea,select");if(h){h instanceof HTMLInputElement&&"checkbox"===h.type?h.checked=!!n:h.value=String(n??"");let e=!1;h.addEventListener("blur",()=>{e||r(Ht(h,t,n))}),h.addEventListener("keydown",i=>{const s=i;if("Enter"===s.key){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(s))return}s.stopPropagation(),s.preventDefault(),e=!0,r(Ht(h,t,n)),this.#qt(l,!1)}if("Escape"===s.key){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(s))return}s.stopPropagation(),s.preventDefault(),o(),this.#qt(l,!0)}}),h instanceof HTMLInputElement&&"checkbox"===h.type&&h.addEventListener("change",()=>r(h.checked)),s||setTimeout(()=>h.focus({preventScroll:!0}),0)}e.appendChild(d)}#Yt(e,t){if(!e)return!1;const i=e,n=t,r=new Set([...Object.keys(i),...Object.keys(n)]);for(const o of r)if(i[o]!==n[o])return!0;return!1}#$t(e){queueMicrotask(()=>{try{const t=e._focusRow,i=e._focusCol,n=e.findRenderedRowElement?.(t);if(n){Array.from(e._bodyEl.querySelectorAll(".cell-focus")).forEach(e=>e.classList.remove("cell-focus"));const r=n.querySelector(`.cell[data-row="${t}"][data-col="${i}"]`);r&&(r.classList.add("cell-focus"),r.setAttribute("aria-selected","true"),r.hasAttribute("tabindex")||r.setAttribute("tabindex","-1"),r.focus({preventScroll:!0}))}}catch{}})}},e.ExportPlugin=class extends rt{name="export";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;performExport(e,t){const i=this.config,n={format:e,fileName:t?.fileName??i.fileName??"export",includeHeaders:t?.includeHeaders??i.includeHeaders,processCell:t?.processCell,processHeader:t?.processHeader,columns:t?.columns,rowIndices:t?.rowIndices},r=at(this.columns,t?.columns,i.onlyVisible);let o;if(t?.rowIndices)o=dt(this.rows,t.rowIndices);else if(i.onlySelected){const e=this.getSelectionState();o=e?.selected?.size?dt(this.rows,[...e.selected]):[...this.rows]}else o=[...this.rows];this.isExportingFlag=!0;let s=n.fileName;try{switch(e){case"csv":{const e=function(e,t,i,n={}){const r=n.delimiter??",",o=n.newline??"\n",s=[],l=n.bom?"\ufeff":"";if(!1!==i.includeHeaders){const e=t.map(e=>{const t=e.header||e.field;return Dt(i.processHeader?i.processHeader(t,e.field):t)});s.push(e.join(r))}for(const a of e){const e=t.map(e=>{let t=a[e.field];return i.processCell&&(t=i.processCell(t,e.field,a)),Dt(t)});s.push(e.join(r))}return l+s.join(o)}(o,r,n,{bom:!0});s=s.endsWith(".csv")?s:`${s}.csv`,function(e,t){zt(new Blob([e],{type:"text/csv;charset=utf-8;"}),t)}(e,s);break}case"excel":{const e=function(e,t,i){let n='<?xml version="1.0" encoding="UTF-8"?>\n<?mso-application progid="Excel.Sheet"?>\n<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"\n xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">\n<Worksheet ss:Name="Sheet1">\n<Table>';if(!1!==i.includeHeaders){n+="\n<Row>";for(const e of t){const t=e.header||e.field;n+=`<Cell><Data ss:Type="String">${Ot(i.processHeader?i.processHeader(t,e.field):t)}</Data></Cell>`}n+="</Row>"}for(const r of e){n+="\n<Row>";for(const e of t){let t=r[e.field];i.processCell&&(t=i.processCell(t,e.field,r));let o="String",s="";null==t?s="":"number"!=typeof t||isNaN(t)?t instanceof Date?(o="DateTime",s=t.toISOString()):s=Ot(String(t)):(o="Number",s=String(t)),n+=`<Cell><Data ss:Type="${o}">${s}</Data></Cell>`}n+="</Row>"}return n+="\n</Table>\n</Worksheet>\n</Workbook>",n}(o,r,n);s=s.endsWith(".xls")?s:`${s}.xls`,function(e,t){const i=t.endsWith(".xls")?t:`${t}.xls`;zt(new Blob([e],{type:"application/vnd.ms-excel;charset=utf-8;"}),i)}(e,s);break}case"json":{const e=o.map(e=>{const t={};for(const i of r){let r=e[i.field];n.processCell&&(r=n.processCell(r,i.field,e)),t[i.field]=r}return t}),t=JSON.stringify(e,null,2);s=s.endsWith(".json")?s:`${s}.json`;zt(new Blob([t],{type:"application/json"}),s);break}}this.lastExportInfo={format:e,timestamp:new Date},this.emit("export-complete",{format:e,fileName:s,rowCount:o.length,columnCount:r.length})}finally{this.isExportingFlag=!1}}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}exportCsv(e){this.performExport("csv",e)}exportExcel(e){this.performExport("excel",e)}exportJson(e){this.performExport("json",e)}isExporting(){return this.isExportingFlag}getLastExport(){return this.lastExportInfo}},e.FilteringPlugin=Kt,e.FitModeEnum=t,e.GridCSSVars={COLOR_BG:"--tbw-color-bg",COLOR_FG:"--tbw-color-fg",COLOR_FG_MUTED:"--tbw-color-fg-muted",COLOR_BORDER:"--tbw-color-border",COLOR_ACCENT:"--tbw-color-accent",COLOR_HEADER_BG:"--tbw-color-header-bg",COLOR_HEADER_FG:"--tbw-color-header-fg",COLOR_SELECTION:"--tbw-color-selection",COLOR_ROW_HOVER:"--tbw-color-row-hover",COLOR_ROW_ALT:"--tbw-color-row-alt",ROW_HEIGHT:"--tbw-row-height",HEADER_HEIGHT:"--tbw-header-height",CELL_PADDING:"--tbw-cell-padding",FONT_FAMILY:"--tbw-font-family",FONT_SIZE:"--tbw-font-size",BORDER_RADIUS:"--tbw-border-radius",FOCUS_OUTLINE:"--tbw-focus-outline"},e.GridClasses=ot,e.GridDataAttrs=st,e.GridElement=nt,e.GridSelectors=lt,e.GroupingColumnsPlugin=class extends rt{static manifest={ownedProperties:[{property:"group",level:"column",description:'the "group" column property'},{property:"columnGroups",level:"config",description:'the "columnGroups" config property',isUsed:e=>Array.isArray(e)&&e.length>0}],queries:[{type:"getColumnGrouping",description:"Returns column group metadata for the visibility panel"}]};name="groupingColumns";styles="@layer tbw-plugins{.header-group-row{display:grid;grid-auto-flow:column;background:var(--tbw-grouping-columns-header-bg, var(--tbw-color-header-bg));border-bottom:1px solid var(--tbw-grouping-columns-border, var(--tbw-color-border))}.header-group-cell{display:flex;align-items:center;justify-content:center;padding:var(--tbw-button-padding-sm, .25rem .5rem);font-weight:600;font-size:var(--tbw-font-size-sm, .9em);text-transform:uppercase;letter-spacing:.5px;border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.header-group-cell:last-child{border-right:none}.header-row .cell.grouped{border-top:none}.header-row .cell.group-end{border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.header-row .cell.group-end:last-child{border-right:none}.rows .cell.group-end{border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.rows .cell.group-end:last-child{border-right:none}.header-group-row.no-borders{border-bottom:none}.header-group-row.no-borders .header-group-cell{border-right:none}.header-row.no-group-borders .cell.group-end{border-right:1px solid var(--tbw-color-border)}}";get defaultConfig(){return{showGroupBorders:!0,lockGroupOrder:!1}}groups=[];isActive=!1;#Zt=new Set;attach(e){super.attach(e),e.addEventListener("column-move",this.#Qt,{signal:this.disconnectSignal})}detach(){this.groups=[],this.isActive=!1,this.#Zt.clear()}#Qt=e=>{if(!this.isActive)return;const t=e,{field:i,columnOrder:n}=t.detail;if(this.config.lockGroupOrder)for(const r of this.groups)if(!r.id.startsWith("__implicit__")&&!this.#Jt(r,n))return t.preventDefault(),void this.#ei(i);this.#ti(n)};#ti(e){this.#Zt.clear();const t=this.#ii(e);for(const i of this.groups){const n=new Set(i.columns.map(e=>e.field));for(let i=e.length-1;i>=0;i--)if(n.has(e[i])){const n=e[i];n!==t&&this.#Zt.add(n);break}}}#ii(e){if(0===this.groups.length)return null;for(let t=e.length-1;t>=0;t--){const i=e[t];for(const t of this.groups)if(t.columns.some(e=>e.field===i)){const i=new Set(t.columns.map(e=>e.field));for(let t=e.length-1;t>=0;t--)if(i.has(e[t]))return e[t]}}return null}#Jt(e,t){const i=e.columns.map(e=>t.indexOf(e.field)).filter(e=>-1!==e).sort((e,t)=>e-t);return i.length<=1||i.length===i[i.length-1]-i[0]+1}#ei(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.#ni()}#ni(){let e;const t=this.grid?.gridConfig?.columnGroups;if(t&&Array.isArray(t)&&t.length>0)e=t.filter(e=>e.children.length>0).map(e=>({id:e.id,label:e.header,fields:[...e.children]}));else if(this.isActive&&this.groups.length>0){e=this.groups.filter(e=>!e.id.startsWith("__implicit__")).map(e=>({id:e.id,label:e.label??e.id,fields:e.columns.map(e=>e.field)}));const t=this.columns;for(const i of t)if(i.hidden&&i.group){const t="string"==typeof i.group?i.group:i.group.id,n="string"==typeof i.group?i.group:i.group.label??i.group.id,r=e.find(e=>e.id===t);r?r.fields.includes(i.field)||r.fields.push(i.field):e.push({id:t,label:n,fields:[i.field]})}}else{const t=this.columns,i=new Map;for(const e of t){if(!e.group)continue;const t="string"==typeof e.group?e.group:e.group.id,n="string"==typeof e.group?e.group:e.group.label??e.group.id,r=i.get(t);r?r.fields.includes(e.field)||r.fields.push(e.field):i.set(t,{id:t,label:n,fields:[e.field]})}e=Array.from(i.values())}const i=this.grid?.getColumnOrder();if(i&&i.length>0){const t=new Map(i.map((e,t)=>[e,t]));for(const i of e)i.fields.sort((e,i)=>(t.get(e)??1/0)-(t.get(i)??1/0))}return e}static detect(e,t){if(t?.columnGroups&&Array.isArray(t.columnGroups)&&t.columnGroups.length>0)return!0;const i=t?.columns;return!!Array.isArray(i)&&function(e){return e.some(e=>null!=e.group)}(i)}processColumns(e){const t=this.grid?.gridConfig?.columnGroups;let i;if(t&&Array.isArray(t)&&t.length>0){const n=new Map;for(const e of t)for(const t of e.children)n.set(t,{id:e.id,label:e.header});i=e.map(e=>{const t=n.get(e.field);return t&&!e.group?{...e,group:t}:e})}else i=[...e];const n=Ut(i);if(0===n.length)return this.isActive=!1,this.groups=[],i;this.isActive=!0,this.groups=n,this.#Zt.clear();for(const r of n){const e=r.columns[r.columns.length-1];e?.field&&this.#Zt.add(e.field)}return i}afterRender(){if(!this.isActive){const e=this.gridElement?.querySelector(".header"),t=e?.querySelector(".header-group-row");return void(t&&t.remove())}const e=this.gridElement?.querySelector(".header");if(!e)return;const t=e.querySelector(".header-group-row");t&&t.remove();const i=this.visibleColumns,n=Ut(i);if(0===n.length)return;this.#Zt.clear();for(let s=0;s<n.length;s++){const e=n[s],t=e.columns[e.columns.length-1];t?.field&&s<n.length-1&&this.#Zt.add(t.field)}const r=function(e,t){if(0===e.length)return null;const i=document.createElement("div");i.className="header-group-row",i.setAttribute("role","row");for(const n of e){const e=n.columns[0],r=e?t.findIndex(t=>t.field===e.field):-1;if(-1===r)continue;const o=String(n.id).startsWith("__implicit__"),s=o?"":n.label||n.id,l=document.createElement("div");l.className="cell header-group-cell",o&&l.classList.add("implicit-group"),l.setAttribute("data-group",String(n.id)),l.style.gridColumn=`${r+1} / span ${n.columns.length}`,l.textContent=s,i.appendChild(l)}return i}(n,i);if(r){r.classList.toggle("no-borders",!this.config.showGroupBorders);const t=e.querySelector(".header-row");t?e.insertBefore(r,t):e.appendChild(r)}const o=e.querySelector(".header-row");o&&(o.classList.toggle("no-group-borders",!this.config.showGroupBorders),function(e,t){if(!t.length||!e)return;const i=new Map;for(const r of t)for(const e of r.columns)e.field&&i.set(e.field,r.id);const n=Array.from(e.querySelectorAll(".cell[data-field]"));n.forEach(e=>{const t=e.getAttribute("data-field")||"",n=i.get(t);n&&(e.classList.add("grouped"),e.getAttribute("data-group")||e.setAttribute("data-group",n))});for(const r of t){const e=r.columns[r.columns.length-1],t=n.find(t=>t.getAttribute("data-field")===e.field);t&&t.classList.add("group-end")}}(o,n))}afterCellRender(e){this.isActive&&this.config.showGroupBorders&&e.cellElement.classList.toggle("group-end",this.#Zt.has(e.column.field))}isGroupingActive(){return this.isActive}getGroups(){return this.groups}getGroupColumns(e){const t=this.groups.find(t=>t.id===e);return t?t.columns:[]}refresh(){this.requestRender()}},e.GroupingRowsPlugin=class extends rt{static manifest={events:[{type:"grouping-state-change",description:"Emitted when groups are expanded/collapsed. Subscribers can react to row visibility changes."}],queries:[{type:"canMoveRow",description:"Returns false for group header rows (cannot be reordered)"}],configRules:[{id:"groupingRows/accordion-defaultExpanded",severity:"warn",message:'"accordion: true" and "defaultExpanded" (non-false) are used together.\n → In accordion mode, only one group can be open at a time.\n → Using defaultExpanded with multiple groups will collapse to one on first toggle.\n → Consider using "defaultExpanded: false" or a single group key/index with accordion mode.',check:e=>!0===e.accordion&&!1!==e.defaultExpanded&&void 0!==e.defaultExpanded&&!("number"==typeof e.defaultExpanded)&&!("string"==typeof e.defaultExpanded)&&(!0===e.defaultExpanded||Array.isArray(e.defaultExpanded)&&e.defaultExpanded.length>1)}]};name="groupingRows";styles="@layer tbw-plugins{.group-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-grouping-rows-bg, var(--tbw-color-panel-bg));font-weight:500;border-bottom:var(--tbw-row-divider);min-height:var(--tbw-row-height)}.group-row .cell{display:flex;align-items:center;padding:var(--tbw-cell-padding, .125rem .5rem)}.group-row:hover{background:var(--tbw-grouping-rows-bg-hover, var(--tbw-color-row-hover))}.group-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-toggle-size, 1.25rem);height:var(--tbw-toggle-size, 1.25rem);margin-right:.25rem;background:none;border:0;font:inherit}.group-toggle:hover{background:var(--tbw-grouping-rows-toggle-hover, var(--tbw-color-row-hover));border-radius:var(--tbw-border-radius, .125rem)}.group-label{display:inline-flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.group-count{color:var(--tbw-grouping-rows-count-color, var(--tbw-color-fg-muted));font-size:var(--tbw-font-size-xs, .85em);font-weight:400}.group-aggregates{display:inline-flex;align-items:center;gap:var(--tbw-spacing-lg, 1rem);margin-left:var(--tbw-spacing-lg, 1rem);font-weight:400;font-size:var(--tbw-font-size-sm, .875em);color:var(--tbw-grouping-rows-aggregate-color, var(--tbw-color-fg-muted))}.group-aggregate{white-space:nowrap}.group-row{padding-left:calc(var(--tbw-group-depth, 0) * var(--tbw-group-indent-width, 1.25em))}.data-grid-row.tbw-group-slide-in{animation:tbw-group-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.data-grid-row.tbw-group-fade-in{animation:tbw-group-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-fade-in{0%{opacity:0}to{opacity:1}}}";get defaultConfig(){return{defaultExpanded:!1,showRowCount:!0,indentWidth:20,aggregators:{},animation:"slide",accordion:!1}}expandedKeys=new Set;flattenedRows=[];isActive=!1;previousVisibleKeys=new Set;keysToAnimate=new Set;hasAppliedDefaultExpanded=!1;get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detach(){this.expandedKeys.clear(),this.flattenedRows=[],this.isActive=!1,this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.hasAppliedDefaultExpanded=!1}getRowHeight(e,t){if(null!=this.config.groupRowHeight)return!0===e.__isGroupRow?this.config.groupRowHeight:void 0}handleQuery(e){if("canMoveRow"===e.type){const t=e.context;if(!0===t?.__isGroupRow)return!1}}static detect(e,t){return"function"==typeof t?.groupOn||"boolean"==typeof t?.enableRowGrouping}processRows(e){const t=this.config;if("function"!=typeof t.groupOn)return this.isActive=!1,this.flattenedRows=[],[...e];const i=ei({rows:[...e],config:t,expanded:new Set});if(0===i.length)return this.isActive=!1,this.flattenedRows=[],[...e];let n;if(!this.hasAppliedDefaultExpanded&&0===this.expandedKeys.size&&!1!==t.defaultExpanded){const e=function(e){return e.filter(e=>"group"===e.kind).map(e=>e.key)}(i);n=function(e,t){if(!0===e)return new Set(t);if(!1===e||null==e)return new Set;if("number"==typeof e){const i=t[e];return i?new Set([i]):new Set}return"string"==typeof e?new Set([e]):Array.isArray(e)?new Set(e):new Set}(t.defaultExpanded??!1,e),n.size>0&&(this.expandedKeys=new Set(n),this.hasAppliedDefaultExpanded=!0)}const r=ei({rows:[...e],config:t,expanded:this.expandedKeys,initialExpanded:n});this.isActive=!0,this.flattenedRows=r,this.keysToAnimate.clear();const o=new Set;return r.forEach((e,t)=>{if("data"===e.kind){const e=`data-${t}`;o.add(e),this.previousVisibleKeys.has(e)||this.keysToAnimate.add(e)}}),this.previousVisibleKeys=o,r.map(e=>{return"group"===e.kind?{__isGroupRow:!0,__groupKey:e.key,__groupValue:e.value,__groupDepth:e.depth,__groupRows:e.rows,__groupExpanded:e.expanded,__groupRowCount:(t=e,"group"!==t.kind?0:t.rows.length),__rowCacheKey:`group:${e.key}`}:e.row;var t})}onCellClick(e){const t=e.row;if(t?.__isGroupRow){const i=e.originalEvent.target;if(i?.closest(".group-toggle"))return this.toggle(t.__groupKey),!0}}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusRow,i=this.rows[t];return i?.__isGroupRow?(e.preventDefault(),this.toggle(i.__groupKey),this.requestRenderWithFocus(),!0):void 0}renderRow(e,t,i){if(!e?.__isGroupRow)return!1;const n=this.config;if(n.groupRowRenderer){const i=()=>{this.toggle(e.__groupKey)},r=n.groupRowRenderer({key:e.__groupKey,value:e.__groupValue,depth:e.__groupDepth,rows:e.__groupRows,expanded:e.__groupExpanded,toggleExpand:i});if(r)return t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),"string"==typeof r?t.innerHTML=r:(t.innerHTML="",t.appendChild(r)),!0}const r=()=>{this.toggle(e.__groupKey)};t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),t.setAttribute("role","row"),t.setAttribute("aria-expanded",String(e.__groupExpanded)),t.style.setProperty("--tbw-group-depth",String(e.__groupDepth||0)),void 0!==n.indentWidth&&t.style.setProperty("--tbw-group-indent-width",`${n.indentWidth}px`),t.style.height="",t.innerHTML="";return!1!==n.fullWidth?this.renderFullWidthGroupRow(e,t,r):this.renderPerColumnGroupRow(e,t,r),!0}afterRender(){const e=this.animationStyle;if(!1===e||0===this.keysToAnimate.size)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const i="fade"===e?"tbw-group-fade-in":"tbw-group-slide-in";for(const n of t.querySelectorAll(".data-grid-row:not(.group-row)")){const e=n.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,r=this.flattenedRows[t],o="data"===r?.kind?`data-${t}`:void 0;o&&this.keysToAnimate.has(o)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}createToggleButton(e,t){const i=document.createElement("button");return i.type="button",i.className="group-toggle"+(e?" expanded":""),i.setAttribute("aria-label",e?"Collapse group":"Expand group"),this.setIcon(i,this.resolveIcon(e?"collapse":"expand")),i.addEventListener("click",e=>{e.stopPropagation(),t()}),i}getGroupLabelText(e,t,i){const n=this.config;return n.formatLabel?n.formatLabel(e,t,i):String(e)}renderFullWidthGroupRow(e,t,i){const n=this.config,r=n.aggregators??{},o=e.__groupRows??[],s=document.createElement("div");s.className="cell group-full",s.style.gridColumn="1 / -1",s.setAttribute("role","gridcell"),s.setAttribute("data-col","0"),s.appendChild(this.createToggleButton(e.__groupExpanded,i));const l=document.createElement("span");if(l.className="group-label",l.textContent=this.getGroupLabelText(e.__groupValue,e.__groupDepth||0,e.__groupKey),s.appendChild(l),!1!==n.showRowCount){const t=document.createElement("span");t.className="group-count",t.textContent=`(${e.__groupRowCount??e.__groupRows?.length??0})`,s.appendChild(t)}const a=Object.entries(r);if(a.length>0){const e=document.createElement("span");e.className="group-aggregates";for(const[t,i]of a){const n=this.columns.find(e=>e.field===t),r=Jt(i,o,t,n);if(null!=r){const i=document.createElement("span");i.className="group-aggregate",i.setAttribute("data-field",t);const o=n?.header??t;i.textContent=`${o}: ${r}`,e.appendChild(i)}}e.children.length>0&&s.appendChild(e)}t.appendChild(s)}renderPerColumnGroupRow(e,t,i){const n=this.config,r=n.aggregators??{},o=this.columns,s=e.__groupRows??[],l=this.gridElement?.querySelector(".body"),a=l?.style.gridTemplateColumns||"";a&&(t.style.display="grid",t.style.gridTemplateColumns=a);let d=!1;o.forEach((o,l)=>{const a=document.createElement("div");if(a.className="cell group-cell",a.setAttribute("data-col",String(l)),a.setAttribute("role","gridcell"),Bt(o))return a.setAttribute("data-field",o.field),void t.appendChild(a);if(d){const e=r[o.field];if(e){const t=Jt(e,s,o.field,o);a.textContent=null!=t?String(t):""}else a.textContent=""}else{d=!0,a.appendChild(this.createToggleButton(e.__groupExpanded,i));const t=document.createElement("span"),l=r[o.field];if(l){const i=Jt(l,s,o.field,o);t.textContent=String(null!=i?i:e.__groupValue)}else t.textContent=this.getGroupLabelText(e.__groupValue,e.__groupDepth||0,e.__groupKey);if(a.appendChild(t),!1!==n.showRowCount){const e=document.createElement("span");e.className="group-count",e.textContent=` (${s.length})`,a.appendChild(e)}}t.appendChild(a)})}expandAll(){this.expandedKeys=function(e){const t=new Set;for(const i of e)"group"===i.kind&&t.add(i.key);return t}(this.flattenedRows),this.emitPluginEvent("grouping-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("grouping-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}toggle(e){const t=!this.expandedKeys.has(e),i=this.config,n=this.flattenedRows.find(t=>"group"===t.kind&&t.key===e);if(i.accordion&&t&&n){const t=new Set;for(const i of this.expandedKeys)if(e.startsWith(i+"||")||i.startsWith(e+"||"))e.startsWith(i+"||")&&t.add(i);else{const e=this.flattenedRows.find(e=>"group"===e.kind&&e.key===i);e&&e.depth!==n.depth&&t.add(i)}t.add(e),this.expandedKeys=t}else this.expandedKeys=function(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}(this.expandedKeys,e);this.emit("group-toggle",{key:e,expanded:this.expandedKeys.has(e),value:n?.value,depth:n?.depth??0}),this.emitPluginEvent("grouping-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}expand(e){this.expandedKeys.has(e)||(this.expandedKeys=new Set([...this.expandedKeys,e]),this.requestRender())}collapse(e){if(this.expandedKeys.has(e)){const t=new Set(this.expandedKeys);t.delete(e),this.expandedKeys=t,this.requestRender()}}getGroupState(){const e=this.flattenedRows.filter(e=>"group"===e.kind);return{isActive:this.isActive,expandedCount:this.expandedKeys.size,totalGroups:e.length,expandedKeys:[...this.expandedKeys]}}getRowCount(){return this.flattenedRows.length}refreshGroups(){this.requestRender()}getExpandedGroups(){return[...this.expandedKeys]}getFlattenedRows(){return this.flattenedRows}isGroupingActive(){return this.isActive}setGroupOn(e){this.config.groupOn=e,this.requestRender()}},e.MasterDetailPlugin=ni,e.MultiSortPlugin=class extends rt{name="multiSort";styles='@layer tbw-plugins{.header-cell[data-sort=asc]:after{content:"↑";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.header-cell[data-sort=desc]:after{content:"↓";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-indicator{margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-index{font-size:var(--tbw-font-size-2xs, .7em);background:var(--tbw-multi-sort-badge-bg, var(--tbw-color-panel-bg));color:var(--tbw-multi-sort-badge-color, var(--tbw-color-fg));border-radius:50%;width:var(--tbw-multi-sort-badge-size, 1em);height:var(--tbw-multi-sort-badge-size, 1em);display:inline-flex;align-items:center;justify-content:center;margin-left:var(--tbw-spacing-xs, .125em);font-weight:600}}';get defaultConfig(){return{maxSortColumns:3,showSortIndex:!0}}sortModel=[];cachedSortResult=null;clearCoreSortState(){const e=this.gridElement;e&&(e._sortState=null)}detach(){this.sortModel=[],this.cachedSortResult=null}processRows(e){if(0===this.sortModel.length)return this.cachedSortResult=null,[...e];const t=this.gridElement;if(t&&!t._isGridEditMode&&"number"==typeof t._activeEditRows&&-1!==t._activeEditRows&&this.cachedSortResult&&this.cachedSortResult.length===e.length)return[...this.cachedSortResult];const i=function(e,t,i){return t.length?[...e].sort((e,n)=>{for(const r of t){const t=i.find(e=>e.field===r.field),o=(t?.sortComparator??ri)(e[r.field],n[r.field],e,n);if(0!==o)return"asc"===r.direction?o:-o}return 0}):[...e]}([...e],this.sortModel,[...this.columns]);return this.cachedSortResult=i,i}onHeaderClick(e){const t=this.columns.find(t=>t.field===e.field);if(!t?.sortable)return!1;const i=e.originalEvent.shiftKey,n=this.config.maxSortColumns??3;return this.sortModel=function(e,t,i,n){const r=e.find(e=>e.field===t);return i?r?"asc"===r.direction?e.map(e=>e.field===t?{...e,direction:"desc"}:e):e.filter(e=>e.field!==t):e.length<n?[...e,{field:t,direction:"asc"}]:e:"asc"===r?.direction?[{field:t,direction:"desc"}]:"desc"===r?.direction?[]:[{field:t,direction:"asc"}]}(this.sortModel,e.field,i,n),this.clearCoreSortState(),this.emit("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),this.grid?.requestStateChange?.(),!0}afterRender(){const e=this.gridElement;if(!e)return;const t=!1!==this.config.showSortIndex;e.querySelectorAll(".header-row .cell[data-field]").forEach(e=>{const i=e.getAttribute("data-field");if(!i)return;const n=oi(this.sortModel,i),r=si(this.sortModel,i),o=e.querySelector(".sort-index");if(o?.remove(),r){const i=e.querySelector('[part~="sort-indicator"], .sort-indicator');i?.remove(),e.setAttribute("data-sort",r);const o=document.createElement("span");o.className="sort-indicator",this.setIcon(o,this.resolveIcon("asc"===r?"sortAsc":"sortDesc"));const s=e.querySelector(".tbw-filter-btn"),l=e.querySelector(".resize-handle"),a=s??l;if(a?e.insertBefore(o,a):e.appendChild(o),t&&this.sortModel.length>1&&void 0!==n){const t=document.createElement("span");t.className="sort-index",t.textContent=String(n),o.nextSibling?e.insertBefore(t,o.nextSibling):e.appendChild(t)}}else{e.removeAttribute("data-sort");const t=e.querySelector('[part~="sort-indicator"], .sort-indicator');t?.remove()}})}getSortModel(){return[...this.sortModel]}setSortModel(e){this.sortModel=[...e],this.clearCoreSortState(),this.emit("sort-change",{sortModel:[...e]}),this.requestRender(),this.grid?.requestStateChange?.()}clearSort(){this.sortModel=[],this.clearCoreSortState(),this.emit("sort-change",{sortModel:[]}),this.requestRender(),this.grid?.requestStateChange?.()}getSortIndex(e){return oi(this.sortModel,e)}getSortDirection(e){return si(this.sortModel,e)}getColumnState(e){const t=this.sortModel.findIndex(t=>t.field===e);if(-1===t)return;return{sort:{direction:this.sortModel[t].direction,priority:t}}}applyColumnState(e,t){if(!t.sort)return void(this.sortModel=this.sortModel.filter(t=>t.field!==e));const i=this.sortModel.findIndex(t=>t.field===e),n={field:e,direction:t.sort.direction};-1!==i?this.sortModel[i]=n:this.sortModel.splice(t.sort.priority,0,n),this.clearCoreSortState()}},e.PLUGIN_QUERIES={CAN_MOVE_COLUMN:"canMoveColumn",GET_CONTEXT_MENU_ITEMS:"getContextMenuItems"},e.PinnedColumnsPlugin=class extends rt{static manifest={ownedProperties:[{property:"pinned",level:"column",description:'the "pinned" column property',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e},{property:"sticky",level:"column",description:'the "sticky" column property (deprecated, use "pinned")',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e}],incompatibleWith:[{name:"groupingColumns",reason:"Pinning reorders columns to the grid edges, but moving a column out of its column group is not supported. The group header layout cannot accommodate members at different positions."}],queries:[{type:pi,description:"Prevents pinned (sticky) columns from being moved/reordered"},{type:"getStickyOffsets",description:"Returns the sticky offsets for left/right pinned columns"},{type:"getContextMenuItems",description:"Contributes pin/unpin items to the header context menu"}]};name="pinnedColumns";get defaultConfig(){return{}}isApplied=!1;leftOffsets=new Map;rightOffsets=new Map;#ri=[];detach(){this.leftOffsets.clear(),this.rightOffsets.clear(),this.isApplied=!1,this.#ri=[]}static detect(e,t){const i=t?.columns;return!!Array.isArray(i)&&hi(i)}processColumns(e){const t=[...e];if(this.isApplied=hi(t),!this.isApplied)return t;const i=this.gridElement;return function(e,t="ltr"){const i=[],n=[],r=[];for(const o of e){const e=li(o);e?"left"===ai(e,t)?i.push(o):r.push(o):n.push(o)}return[...i,...n,...r]}(t,i?M(i):"ltr")}afterRender(){if(!this.isApplied)return;const e=this.grid,t=[...this.columns];if(!hi(t))return gi(e),void(this.isApplied=!1);queueMicrotask(()=>{ui(e,t)})}handleQuery(e){switch(e.type){case pi:return null==li(e.context)&&void 0;case"getStickyOffsets":return{left:Object.fromEntries(this.leftOffsets),right:Object.fromEntries(this.rightOffsets)};case"getContextMenuItems":{const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field)return;if(i.meta?.lockPinning)return;const n=this.grid?.getPluginByName("groupingColumns");if(n?.isGroupingActive())return;const r=[];return null!=li(i)?r.push({id:"pinned/unpin",label:"Unpin Column",icon:"📌",order:40,action:()=>this.setPinPosition(i.field,void 0)}):(r.push({id:"pinned/pin-left",label:"Pin Left",icon:"⬅",order:40,action:()=>this.setPinPosition(i.field,"left")}),r.push({id:"pinned/pin-right",label:"Pin Right",icon:"➡",order:41,action:()=>this.setPinPosition(i.field,"right")})),r}default:return}}setPinPosition(e,t){const i=this.columns;if(!i?.length)return;const n=i.findIndex(t=>t.field===e);if(-1===n)return;const r=this.grid;if(t){0===this.#ri.length&&(this.#ri=i.map(e=>e.field));const n=i.map(i=>{if(i.field!==e)return i;const n={...i};return n.pinned=t,delete n.sticky,n});r.columns=n}else{const t={...i[n]};delete t.pinned,delete t.sticky;const o=[...i];o.splice(n,1);const s=this.#ri.indexOf(e);if(s>=0){let e=o.length;for(let t=0;t<o.length;t++){if(li(o[t]))continue;if(this.#ri.indexOf(o[t].field)>s){e=t;break}}o.splice(e,0,t)}else o.splice(Math.min(n,o.length),0,t);o.some(e=>null!=li(e))||(this.#ri=[]),r.columns=o}}refreshStickyOffsets(){const e=[...this.columns];ui(this.grid,e)}getLeftPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>di(e,t))}([...this.columns],M(this.grid))}getRightPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>ci(e,t))}([...this.columns],M(this.grid))}clearStickyPositions(){gi(this.grid)}getHorizontalScrollOffsets(e,t){if(!this.isApplied)return;let i=0,n=0;if(e){const t=e.querySelectorAll(".sticky-left"),r=e.querySelectorAll(".sticky-right");t.forEach(e=>{i+=e.offsetWidth}),r.forEach(e=>{n+=e.offsetWidth})}else{this.grid.querySelectorAll(".header-row .cell").forEach(e=>{e.classList.contains("sticky-left")?i+=e.offsetWidth:e.classList.contains("sticky-right")&&(n+=e.offsetWidth)})}const r=t?.classList.contains("sticky-left")||t?.classList.contains("sticky-right");return{left:i,right:n,skipScroll:r}}},e.PinnedRowsPlugin=class extends rt{name="pinnedRows";styles="@layer tbw-plugins{.tbw-footer{flex-shrink:0;z-index:var(--tbw-z-layer-pinned-rows, 20);background:var(--tbw-color-panel-bg)}.tbw-pinned-rows{display:flex;align-items:center;justify-content:space-between;padding:var(--tbw-button-padding, var(--tbw-spacing-md, .5rem) var(--tbw-spacing-lg, .75rem));background:var(--tbw-pinned-rows-bg, var(--tbw-color-panel-bg));border-top:1px solid var(--tbw-pinned-rows-border, var(--tbw-color-border));font-size:var(--tbw-font-size-xs, .75rem);color:var(--tbw-pinned-rows-color, var(--tbw-color-fg-muted));min-height:32px;box-sizing:border-box;min-width:fit-content}.tbw-pinned-rows-left,.tbw-pinned-rows-center,.tbw-pinned-rows-right{display:flex;align-items:center;gap:var(--tbw-spacing-xl, 1rem)}.tbw-pinned-rows-left{justify-content:flex-start}.tbw-pinned-rows-center{justify-content:center;flex:1}.tbw-pinned-rows-right{justify-content:flex-end}.tbw-status-panel{white-space:nowrap}.tbw-aggregation-rows{min-width:fit-content;background:var(--tbw-aggregation-bg, var(--tbw-color-header-bg))}.tbw-aggregation-rows-top{border-bottom:1px solid var(--tbw-aggregation-border, var(--tbw-color-border))}.tbw-aggregation-rows-bottom{border-top:1px solid var(--tbw-aggregation-border, var(--tbw-color-border))}.tbw-aggregation-row{display:grid;grid-template-columns:var(--tbw-column-template);font-size:var(--tbw-aggregation-font-size, .8em);font-weight:var(--tbw-aggregation-font-weight, 600)}.tbw-aggregation-cell{padding:var(--tbw-cell-padding, .125rem .5rem);min-height:var(--tbw-row-height, 1.75rem);display:block;align-items:center;align-content:center;border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;text-overflow:ellipsis;white-space:var(--tbw-cell-white-space, nowrap)}.tbw-aggregation-cell:last-child{border-right:0}.tbw-aggregation-cell-full{grid-column:1 / -1;border-right:0;display:flex;align-items:center;gap:var(--tbw-spacing-lg, .75rem)}.tbw-aggregation-label{white-space:nowrap}.tbw-aggregation-aggregates{display:flex;align-items:center;gap:var(--tbw-spacing-lg, .75rem);font-weight:400;opacity:.85}.tbw-aggregation-aggregate{white-space:nowrap}}";get defaultConfig(){return{position:"bottom",showRowCount:!0,showSelectedCount:!0,showFilteredCount:!0}}infoBarElement=null;topAggregationContainer=null;bottomAggregationContainer=null;footerWrapper=null;detach(){this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null),this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null)}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-scroll-area")??e.querySelector(".tbw-grid-content")??e.children[0];if(!t)return;this.footerWrapper&&!t.contains(this.footerWrapper)&&(this.footerWrapper=null,this.bottomAggregationContainer=null,this.infoBarElement=null),this.topAggregationContainer&&!t.contains(this.topAggregationContainer)&&(this.topAggregationContainer=null),this.infoBarElement&&!t.contains(this.infoBarElement)&&(this.infoBarElement=null);const i=this.getSelectionState(),n=this.getFilterState(),r=xi(this.sourceRows,this.columns,this.grid,i,n),o=this.config.aggregationRows||[],s=o.filter(e=>"top"===e.position),l=o.filter(e=>"top"!==e.position);if(s.length>0){if(!this.topAggregationContainer){this.topAggregationContainer=wi("top");const i=e.querySelector(".header");i&&i.nextSibling?t.insertBefore(this.topAggregationContainer,i.nextSibling):t.appendChild(this.topAggregationContainer)}mi(this.topAggregationContainer,s,this.visibleColumns,this.sourceRows,this.config.fullWidth)}else this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null);const a=!1!==this.config.showRowCount||this.config.showSelectedCount&&r.selectedRows>0||this.config.showFilteredCount&&r.filteredRows!==r.totalRows||this.config.customPanels&&this.config.customPanels.length>0,d=a&&"top"!==this.config.position,c=l.length>0||d;if(a&&"top"===this.config.position)if(this.infoBarElement){const e=fi(this.config,r);this.infoBarElement.replaceWith(e),this.infoBarElement=e}else this.infoBarElement=fi(this.config,r),t.insertBefore(this.infoBarElement,t.firstChild);else"top"===this.config.position&&this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null);c?(this.footerWrapper||(this.footerWrapper=document.createElement("div"),this.footerWrapper.className="tbw-footer",t.appendChild(this.footerWrapper)),this.footerWrapper.innerHTML="",l.length>0&&(this.bottomAggregationContainer||(this.bottomAggregationContainer=wi("bottom")),this.footerWrapper.appendChild(this.bottomAggregationContainer),mi(this.bottomAggregationContainer,l,this.visibleColumns,this.sourceRows,this.config.fullWidth)),d&&(this.infoBarElement=fi(this.config,r),this.footerWrapper.appendChild(this.infoBarElement))):this.cleanupFooter()}cleanup(){this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null),this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null)}cleanupFooter(){this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.infoBarElement&&"top"!==this.config.position&&(this.infoBarElement.remove(),this.infoBarElement=null)}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}getFilterState(){try{return this.grid?.getPluginState?.("filtering")??null}catch{return null}}refresh(){this.requestRender()}getContext(){const e=this.getSelectionState(),t=this.getFilterState();return xi(this.rows,this.columns,this.grid,e,t)}addPanel(e){this.config.customPanels||(this.config.customPanels=[]),this.config.customPanels.push(e),this.requestRender()}removePanel(e){this.config.customPanels&&(this.config.customPanels=this.config.customPanels.filter(t=>t.id!==e),this.requestRender())}addAggregationRow(e){this.config.aggregationRows||(this.config.aggregationRows=[]),this.config.aggregationRows.push(e),this.requestRender()}removeAggregationRow(e){this.config.aggregationRows&&(this.config.aggregationRows=this.config.aggregationRows.filter(t=>t.id!==e),this.requestRender())}},e.PivotPlugin=zi,e.PluginEvents={SELECTION_CHANGE:"selection-change",TREE_EXPAND:"tree-expand",FILTER_CHANGE:"filter-change",SORT_MODEL_CHANGE:"sort-model-change",EXPORT_START:"export-start",EXPORT_COMPLETE:"export-complete",CLIPBOARD_COPY:"clipboard-copy",CLIPBOARD_PASTE:"clipboard-paste",CONTEXT_MENU_OPEN:"context-menu-open",CONTEXT_MENU_CLOSE:"context-menu-close",HISTORY_CHANGE:"history-change",SERVER_LOADING:"server-loading",SERVER_ERROR:"server-error",COLUMN_VISIBILITY_CHANGE:"column-visibility-change",COLUMN_REORDER:"column-reorder",DETAIL_EXPAND:"detail-expand",GROUP_EXPAND:"group-expand"},e.PluginManager=it,e.PrintPlugin=class extends rt{name="print";version="1.0.0";styles=".tbw-print-header,.tbw-print-footer{display:none}@media print{tbw-grid{overflow:visible!important;height:auto!important;border:none!important;border-radius:0!important;color-scheme:light only;-webkit-print-color-adjust:exact;print-color-adjust:exact}tbw-grid .tbw-grid-content{overflow:visible!important;height:auto!important;max-height:none!important}tbw-grid .tbw-scroll-area{overflow:visible!important;height:auto!important;max-height:none!important}tbw-grid .rows-body{overflow:visible!important;height:auto!important;max-height:none!important}tbw-grid .rows-container,tbw-grid .rows-viewport,tbw-grid .rows{overflow:visible!important;height:auto!important;max-height:none!important;transform:none!important}tbw-grid .rows-viewport .rows{position:static!important}tbw-grid .resize-handle,tbw-grid [part=sort-indicator],tbw-grid .tbw-filter-btn,tbw-grid .tool-panel,tbw-grid .tool-panel-content,tbw-grid .tbw-shell-header,tbw-grid .shell-toolbar,tbw-grid .tool-panel-toggle,tbw-grid [data-print-hide],tbw-grid .expander-cell,tbw-grid .tree-toggle,tbw-grid .context-menu,tbw-grid .faux-vscroll{display:none!important}tbw-grid .tbw-print-header{display:flex;justify-content:space-between;align-items:baseline;padding:var(--tbw-spacing-md, .5em) 0;margin-bottom:var(--tbw-spacing-md, .5em);border-bottom:2px solid var(--tbw-print-border, var(--tbw-color-border-strong));font-family:inherit}.tbw-print-header-title{font-size:1.25em;font-weight:700}.tbw-print-header-timestamp{font-size:var(--tbw-font-size-sm, .875em);color:var(--tbw-print-muted, var(--tbw-color-fg-muted))}tbw-grid .tbw-print-footer{display:block;margin-top:var(--tbw-spacing-md, .5em);padding-top:var(--tbw-spacing-md, .5em);border-top:1px solid var(--tbw-print-border, var(--tbw-color-border));font-size:var(--tbw-font-size-xs, .75em);color:var(--tbw-print-muted, var(--tbw-color-fg-muted));text-align:end}tbw-grid .data-grid-row{break-inside:avoid;page-break-inside:avoid}tbw-grid .cell{border:1px solid var(--tbw-print-cell-border, var(--tbw-color-border))!important}tbw-grid .header-row,tbw-grid .data-grid-row{padding-inline-end:1px}tbw-grid .data-grid-row:hover,tbw-grid .cell:hover{background:inherit!important}@page{margin:1cm}@page{tbw-grid.print-landscape{size:landscape}}@page{tbw-grid.print-portrait{size:portrait}}}";#oi=!1;#si=null;#li=null;#ai=null;#di=null;#ci=null;#hi=null;get#ui(){return this.grid}isPrinting(){return this.#oi}async print(e){if(this.#oi)return void console.warn("[PrintPlugin] Print already in progress");const t=this.gridElement;if(!t)return void console.warn("[PrintPlugin] Grid not available");const i={...qi,...this.config,...e},n=this.rows.length;let r=n,o=!1;if(i.warnThreshold>0&&n>i.warnThreshold){const e=i.maxRows>0?`\n\nNote: Output will be limited to ${i.maxRows.toLocaleString()} rows.`:"";if(!confirm(`This grid has ${n.toLocaleString()} rows. Printing large datasets may cause performance issues or browser slowdowns.${e}\n\nClick OK to continue, or Cancel to abort.`))return}i.maxRows>0&&n>i.maxRows&&(r=i.maxRows,o=!0),this.#oi=!0;const s=performance.now();this.emit("print-start",{rowCount:r,limitApplied:o,originalRowCount:n});try{const e=this.#ui;this.#li={bypassThreshold:e._virtualization?.bypassThreshold??24},this.#gi(),o&&(this.#ai=this.sourceRows,this.grid.rows=this.sourceRows.slice(0,r),await new Promise(e=>setTimeout(e,50))),(i.includeTitle||i.includeTimestamp)&&this.#pi(i),await this.#fi(),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.#wi(i):await this.#mi(),this.emit("print-complete",{success:!0,rowCount:r,duration:Math.round(performance.now()-s)})}catch(l){console.error("[PrintPlugin] Print failed:",l),this.emit("print-complete",{success:!1,rowCount:0,duration:Math.round(performance.now()-s)})}finally{this.#bi(),this.#oi=!1}}#pi(e){const t=this.gridElement;if(t){if(this.#di=document.createElement("div"),this.#di.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.#di.appendChild(i)}if(e.includeTimestamp){const e=document.createElement("div");e.className="tbw-print-header-timestamp",e.textContent=`Printed: ${(new Date).toLocaleString()}`,this.#di.appendChild(e)}t.insertBefore(this.#di,t.firstChild),this.#ci=document.createElement("div"),this.#ci.className="tbw-print-footer",this.#ci.textContent=`Page generated from ${window.location.hostname}`,t.appendChild(this.#ci)}}async#fi(){const e=this.#ui;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#mi(){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#wi(e){const t=this.gridElement;t&&await Fi(t,{orientation:e.orientation})}#gi(){const e=this.columns;if(e){this.#si=new Map;for(const t of e)t.printHidden&&t.field&&(this.#si.set(t.field,!t.hidden),this.grid.setColumnVisible(t.field,!1))}}#vi(){if(this.#si){for(const[e,t]of this.#si)this.grid.setColumnVisible(e,t);this.#si=null}}#bi(){const e=this.gridElement;if(!e)return;this.#vi(),e.classList.remove("print-portrait","print-landscape"),null!==this.#hi&&(e.style.transform="",e.style.transformOrigin="",e.style.width="",this.#hi=null),this.#di&&(this.#di.remove(),this.#di=null),this.#ci&&(this.#ci.remove(),this.#ci=null);const t=this.#ui;this.#li&&t._virtualization&&(t._virtualization.bypassThreshold=this.#li.bypassThreshold,t.refreshVirtualWindow(!0),this.#li=null),null!==this.#ai&&(this.grid.rows=this.#ai,this.#ai=null)}afterRender(){this.config?.button&&!this.#yi&&(this.#Ci(),this.#yi=!0)}#yi=!1;#Ci(){const e=this.#ui;e.registerToolbarContent?.({id:"print-button",order:900,render:e=>{const t=document.createElement("button");t.className="tbw-toolbar-btn tbw-print-btn",t.title="Print grid",t.type="button";const i=this.resolveIcon("print")||"🖨️";this.setIcon(t,i),t.addEventListener("click",()=>{this.print()},{signal:this.disconnectSignal}),e.appendChild(t)}})}},e.ROW_DRAG_HANDLE_FIELD=Gi,e.RenderPhase=he,e.ReorderPlugin=class extends rt{name="reorder";styles='@layer tbw-plugins{.header-row>.cell[draggable=true]{cursor:grab;position:relative}.header-row>.cell.dragging{opacity:.5;cursor:grabbing}.header-row>.cell.drop-before:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.header-row>.cell.drop-after:after{content:"";position:absolute;right:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.cell.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}@keyframes reorder-fade-in{0%{opacity:0}to{opacity:1}}.cell.fade-animating{animation:reorder-fade-in var(--tbw-animation-duration, .2s) ease-out backwards}}';get defaultConfig(){return{animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}get animationDuration(){return void 0!==this.config.animationDuration?this.config.animationDuration:super.animationDuration}isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;canMoveColumnWithPlugins(e){if(!e||!function(e){const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}(e))return!1;return!this.grid.query("canMoveColumn",e).includes(!1)}clearDragClasses(){this.gridElement?.querySelectorAll(".header-row > .cell").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-reorder-request",e=>{const t=e.detail;t?.field&&"number"==typeof t.toIndex&&this.moveColumn(t.field,t.toIndex)},{signal:this.disconnectSignal})}detach(){this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}afterRender(){const e=this.gridElement;if(!e)return;e.querySelectorAll(".header-row > .cell").forEach(e=>{const t=e,i=t.getAttribute("data-field");if(!i)return;const n=this.columns.find(e=>e.field===i);this.canMoveColumnWithPlugins(n)?(t.draggable=!0,t.getAttribute("data-dragstart-bound")||(t.setAttribute("data-dragstart-bound","true"),t.addEventListener("dragstart",e=>{const n=this.getColumnOrder().indexOf(i);this.isDragging=!0,this.draggedField=i,this.draggedIndex=n,e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",i)),t.classList.add("dragging")}),t.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses()}),t.addEventListener("dragover",e=>{if(e.preventDefault(),!this.isDragging||this.draggedField===i)return;const n=t.getBoundingClientRect(),r=n.left+n.width/2,o=this.getColumnOrder().indexOf(i);this.dropIndex=e.clientX<r?o:o+1,t.classList.add("drop-target"),t.classList.toggle("drop-before",e.clientX<r),t.classList.toggle("drop-after",e.clientX>=r)}),t.addEventListener("dragleave",()=>{t.classList.remove("drop-target","drop-before","drop-after")}),t.addEventListener("drop",e=>{e.preventDefault();const t=this.draggedField,i=this.draggedIndex,n=this.dropIndex;if(!this.isDragging||null===t||null===i||null===n)return;const r=n>i?n-1:n,o=Ni(this.getColumnOrder(),i,r),s={field:t,fromIndex:i,toIndex:r,columnOrder:o};this.emitCancelable("column-move",s)||this.updateColumnOrder(o)}))):t.draggable=!1})}onKeyDown(e){if(!e.altKey||"ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;const t=this.grid,i=t._focusCol,n=t._visibleColumns;if(i<0||i>=n.length)return;const r=n[i];if(!this.canMoveColumnWithPlugins(r))return;const o=this.getColumnOrder(),s=o.indexOf(r.field);if(-1===s)return;const l="ArrowLeft"===e.key?s-1:s+1;if(l<0||l>=o.length)return;const a=n.find(e=>e.field===o[l]);return this.canMoveColumnWithPlugins(a)?(this.moveColumn(r.field,l),t._focusCol=l,K(this.grid),e.preventDefault(),e.stopPropagation(),!0):void 0}getColumnOrder(){return this.grid.getColumnOrder()}moveColumn(e,t){const i=this.getColumnOrder(),n=i.indexOf(e);if(-1===n)return;const r=Ni(i,n,t);this.emitCancelable("column-move",{field:e,fromIndex:n,toIndex:t,columnOrder:r})||this.updateColumnOrder(r)}setColumnOrder(e){this.updateColumnOrder(e)}resetColumnOrder(){const e=this.columns.map(e=>e.field);this.updateColumnOrder(e)}captureHeaderPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const i=t.getAttribute("data-field");i&&e.set(i,t.getBoundingClientRect().left)}),e}animateFLIP(e){const t=this.gridElement;if(!t||0===e.size)return;const i=new Map;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const n=t.getAttribute("data-field");if(!n)return;const r=e.get(n);if(void 0===r)return;const o=r-t.getBoundingClientRect().left;Math.abs(o)>1&&i.set(n,o)}),0===i.size)return;const n=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=i.get(e.getAttribute("data-field")??"");if(void 0!==t){const i=e;i.style.transform=`translateX(${t}px)`,n.push(i)}}),0===n.length)return;this.gridElement.offsetHeight;const r=this.animationDuration;requestAnimationFrame(()=>{n.forEach(e=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{n.forEach(e=>{e.style.transform="",e.classList.remove("flip-animating")})},r+50)})}animateFade(e){const t=this.gridElement;if(!t)return void e();const i=this.captureHeaderPositions();e();const n=new Set;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(!t)return;const r=i.get(t);if(void 0===r)return;const o=e.getBoundingClientRect().left;Math.abs(r-o)>1&&n.add(t)}),0===n.size)return;const r=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(t&&n.has(t)){const t=e;t.classList.add("fade-animating"),r.push(t)}}),0===r.length)return;const o=this.animationDuration;setTimeout(()=>{r.forEach(e=>e.classList.remove("fade-animating"))},o+50)}updateColumnOrder(e){const t=this.animationType;if("flip"===t&&this.gridElement){const t=this.captureHeaderPositions();this.grid.setColumnOrder(e),requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(t)})}else"fade"===t?this.animateFade(()=>this.grid.setColumnOrder(e)):this.grid.setColumnOrder(e);this.grid.requestStateChange?.()}},e.ResponsivePlugin=class extends rt{name="responsive";version="1.0.0";styles='tbw-grid[data-responsive-animate] .data-grid-row,tbw-grid[data-responsive-animate] .data-grid-row>.cell{transition:opacity var(--tbw-responsive-duration, .2s) ease-out,transform var(--tbw-responsive-duration, .2s) ease-out}tbw-grid[data-responsive][data-responsive-animate] .data-grid-row{animation:responsive-card-enter var(--tbw-responsive-duration, .2s) ease-out}@keyframes responsive-card-enter{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}tbw-grid[data-responsive] .header{display:none!important}tbw-grid[data-responsive] .footer-row{display:none}tbw-grid[data-responsive] .tbw-scroll-area{overflow-x:hidden;min-width:0!important}tbw-grid[data-responsive] .rows-body-wrapper{min-width:0!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row){display:block!important;grid-template-columns:none!important;padding:var(--tbw-cell-padding);padding-inline-start:var(--tbw-spacing-xl);border-bottom:1px solid var(--tbw-color-border);min-height:auto!important;height:auto!important;contain:none!important;content-visibility:visible!important;background:var(--tbw-color-bg);position:relative}tbw-grid[data-responsive] .data-grid-row:not(.group-row):nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid[data-responsive] .data-grid-row:not(.group-row):hover{background:var(--tbw-color-row-hover)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]{background:var(--tbw-color-selection)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]:before{content:"";position:absolute;inset-inline-start:0;top:0;bottom:0;width:4px;background:var(--tbw-color-accent)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell{display:flex!important;justify-content:space-between;align-items:center;padding:var(--tbw-spacing-xs) var(--tbw-spacing-md);width:100%!important;min-width:0!important;min-height:auto!important;height:auto!important;line-height:1.5!important;position:static!important;left:auto!important;right:auto!important;border:none!important;border-bottom:none!important;border-inline-end:none!important;background:transparent!important;white-space:normal!important;overflow:visible!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:before{content:attr(data-header) ": ";font-weight:600;color:var(--tbw-color-header-fg);flex-shrink:0;margin-inline-end:var(--tbw-spacing-md);min-width:100px}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:after{content:none}tbw-grid[data-responsive] .cell[data-utility]{display:none!important}tbw-grid[data-responsive] .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .cell[data-responsive-value-only]:before{display:none!important}tbw-grid:not([data-responsive]) .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .tbw-footer,tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows{display:none!important}tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows,tbw-grid[data-responsive] .tbw-aggregation-row{min-width:0!important}tbw-grid[data-responsive] .data-grid-row.responsive-card{display:block!important;padding:var(--tbw-cell-padding);border-bottom:1px solid var(--tbw-color-border)}tbw-grid[data-responsive] .data-grid-row.responsive-card>*{width:100%}tbw-grid[data-responsive] .data-grid-row.responsive-card .cell:before{display:none}';static manifest={incompatibleWith:[{name:"groupingRows",reason:"Responsive card layout does not yet support row grouping. The variable row heights (cards vs group headers) cause scroll calculation issues."}],queries:[{type:"isCardMode",description:"Returns whether the grid is currently in responsive card mode"}]};#K;#xi=!1;#Ei;#Ri=!1;#Si=0;#_i=new Set;#Ai=new Set;#ki=null;#Ti=[];isResponsive(){return this.#xi}setResponsive(e){e!==this.#xi&&(this.#xi=e,this.#Li(),this.emit("responsive-change",{isResponsive:e,width:this.#Si,breakpoint:this.config.breakpoint??0}))}setBreakpoint(e){this.config.breakpoint=e,this.#Mi(this.#Si)}setCardRenderer(e){this.config.cardRenderer=e,this.#xi&&this.requestRender()}getWidth(){return this.#Si}getActiveBreakpoint(){return this.#ki}attach(e){super.attach(e),this.#Pi(),this.#Hi(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#Ti=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#K=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#Si=t,clearTimeout(this.#Ei),this.#Ei=setTimeout(()=>{this.#Mi(t)},this.config.debounceMs??100)}),this.#K.observe(this.gridElement)}#Pi(){const e=this.grid;if(!e||"function"!=typeof e.querySelector)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const i=e;if(i.__frameworkAdapter?.parseResponsiveCardElement){const e=i.__frameworkAdapter.parseResponsiveCardElement(t);e&&(this.config={...this.config,cardRenderer:e})}const n=t.getAttribute("breakpoint"),r=t.getAttribute("card-row-height"),o=t.getAttribute("hidden-columns"),s=t.getAttribute("hide-header"),l=t.getAttribute("debounce-ms"),a={};if(null!==n){const e=parseInt(n,10);isNaN(e)||(a.breakpoint=e)}if(null!==r&&(a.cardRowHeight="auto"===r?"auto":parseInt(r,10)),null!==o&&(a.hiddenColumns=o.split(",").map(e=>e.trim()).filter(e=>e.length>0)),null!==s&&(a.hideHeader="false"!==s),null!==l){const e=parseInt(l,10);isNaN(e)||(a.debounceMs=e)}const d=t.innerHTML.trim();!d||this.config.cardRenderer||i.__frameworkAdapter?.parseResponsiveCardElement||(a.cardRenderer=e=>{const t=y(C(d,{value:e,row:e})),i=document.createElement("div");return i.className="tbw-responsive-card-content",i.innerHTML=t,i}),Object.keys(a).length>0&&(this.config={...this.config,...a})}#Hi(e){if(this.#_i.clear(),this.#Ai.clear(),e)for(const t of e)"string"==typeof t?this.#_i.add(t):t.showValue?this.#Ai.add(t.field):this.#_i.add(t.field)}detach(){this.#K?.disconnect(),this.#K=void 0,clearTimeout(this.#Ei),this.#Ei=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#xi}afterRender(){this.#Ii();if(!(this.#Ti.length>0?null!==this.#ki:this.#xi))return;const e=this.#_i.size>0,t=this.#Ai.size>0;if(!e&&!t)return;const i=this.gridElement.querySelectorAll(".cell[data-field]");for(const n of i){const e=n.getAttribute("data-field");e&&(this.#_i.has(e)?(n.setAttribute("data-responsive-hidden",""),n.removeAttribute("data-responsive-value-only")):this.#Ai.has(e)?(n.setAttribute("data-responsive-value-only",""),n.removeAttribute("data-responsive-hidden")):(n.removeAttribute("data-responsive-hidden"),n.removeAttribute("data-responsive-value-only")))}}#Mi(e){if(this.#Ti.length>0)return void this.#Di(e);const t=this.config.breakpoint??0;0!==t||this.#Ri||(this.#Ri=!0,console.warn("[tbw-grid:ResponsivePlugin] No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count."));const i=t>0&&e<t;i!==this.#xi&&(this.#xi=i,this.#Li(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#Di(e){let t=null;for(const i of this.#Ti)e<=i.maxWidth&&(t=i);if(t!==this.#ki){this.#ki=t,t?.hiddenColumns?this.#Hi(t.hiddenColumns):this.#Hi(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#xi&&(this.#xi=i,this.#Li()),this.emit("responsive-change",{isResponsive:this.#xi,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#zi;#Li(){this.gridElement.toggleAttribute("data-responsive",this.#xi);const e=!1!==this.config.animate;this.gridElement.toggleAttribute("data-responsive-animate",e),this.config.animationDuration&&this.gridElement.style.setProperty("--tbw-responsive-duration",`${this.config.animationDuration}ms`);const t=this.grid;if(this.#xi){t._virtualization&&(this.#zi=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.#zi&&this.#zi>0&&t._virtualization&&(t._virtualization.rowHeight=this.#zi,this.#zi=void 0),this.#Oi=void 0,this.#Fi=void 0,this.#qi=void 0}}renderRow(e,t,i){if(!this.#xi||!this.config.cardRenderer)return;if(e.__isGroupRow)return;t.replaceChildren();const n=this.config.cardRenderer(e,i);t.className="data-grid-row responsive-card";const r=this.config.cardRowHeight??"auto";return t.style.height="auto"!==r?`${r}px`:"auto",t.appendChild(n),!0}onKeyDown(e){if(!this.#xi)return!1;if(this.config.cardRenderer){if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return!1}const t=this.rows.length-1,i=this.visibleColumns.length-1;switch(e.key){case"ArrowDown":if(this.grid._focusCol<i)return this.grid._focusCol+=1,e.preventDefault(),K(this.grid),!0;if(this.grid._focusRow<t)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),K(this.grid),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),K(this.grid),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=i,e.preventDefault(),K(this.grid),!0;break;case"ArrowRight":if(this.grid._focusRow<t)return this.grid._focusRow+=1,e.preventDefault(),K(this.grid),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),K(this.grid),!0}return!1}#Oi;#Fi;#qi;#Ni(){if(this.#Oi&&this.#Oi>0)return this.#Oi;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#Gi(){return this.#Fi&&this.#Fi>0?this.#Fi:this.#zi??28}#Vi(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}#$i(){let e=0,t=0;for(const i of this.rows)i.__isGroupRow?e++:t++;return{groupCount:e,cardCount:t}}getExtraHeight(){if(!this.#xi||!this.config.cardRenderer)return 0;if(!this.#Vi())return 0;const e=this.#zi??28,t=this.#Gi(),i=this.#Ni(),{groupCount:n,cardCount:r}=this.#$i();return n*Math.max(0,t-e)+r*Math.max(0,i-e)}getExtraHeightBefore(e){if(!this.#xi||!this.config.cardRenderer)return 0;if(!this.#Vi())return 0;const t=this.#zi??28,i=this.#Gi(),n=this.#Ni(),r=Math.max(0,i-t),o=Math.max(0,n-t);let s=0,l=0;const a=this.rows,d=Math.min(e,a.length);for(let c=0;c<d;c++)a[c].__isGroupRow?s++:l++;return s*r+l*o}getRowHeight(e,t){if(this.#xi&&this.config.cardRenderer)return e.__isGroupRow?this.#Gi():this.#Ni()}#Bi(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#Wi=!1;#Ii(){if(!this.#xi||!this.config.cardRenderer)return;let e=!1;const t=this.grid,i=this.#Vi(),n=this.#Bi();if(n!==this.#qi&&(this.#qi=n,e=!0),i){const t=this.gridElement.querySelector(".data-grid-row.group-row");if(t){const i=t.getBoundingClientRect().height;i>0&&i!==this.#Fi&&(this.#Fi=i,e=!0)}}const r=this.gridElement.querySelector(".data-grid-row.responsive-card");if(r){const n=r.getBoundingClientRect().height;n>0&&n!==this.#Oi&&(this.#Oi=n,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=n))}e&&!this.#Wi&&(this.#Wi=!0,queueMicrotask(()=>{this.#Wi=!1,this.grid&&this.#xi&&this.grid.refreshVirtualWindow?.(!0,!0)}))}},e.RowReorderPlugin=class extends rt{name="rowReorder";styles='@layer tbw-plugins{[data-field=__tbw_row_drag]{display:flex;align-items:center;justify-content:center}.dg-row-drag-handle{display:flex;align-items:center;justify-content:center;min-width:1em;min-height:1em;cursor:grab;-webkit-user-select:none;user-select:none;color:var(--tbw-row-reorder-handle-color, var(--tbw-color-fg-muted));transition:color var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease);font-size:var(--tbw-font-size, 1em);letter-spacing:-2px}.dg-row-drag-handle:hover{color:var(--tbw-row-reorder-handle-hover, var(--tbw-color-fg))}.dg-row-drag-handle:active{cursor:grabbing}.data-grid-row.dragging{opacity:.6}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before{content:"";position:absolute;top:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.drop-target.drop-after:after{content:"";position:absolute;bottom:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.keyboard-moving{background-color:var(--tbw-row-reorder-moving-bg, var(--tbw-focus-background));box-shadow:0 0 0 1px var(--tbw-row-reorder-moving-border, var(--tbw-color-accent)) inset}.data-grid-row.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}}';get defaultConfig(){return{enableKeyboard:!0,showDragHandle:!0,dragHandlePosition:"left",dragHandleWidth:40,debounceMs:150,animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}isDragging=!1;draggedRowIndex=null;dropRowIndex=null;pendingMove=null;debounceTimer=null;lastFocusCol=0;detach(){this.clearDebounceTimer(),this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.pendingMove=null}processColumns(e){if(!this.config.showDragHandle)return[...e];const t={field:Gi,header:"",width:this.config.dragHandleWidth??40,resizable:!1,sortable:!1,filterable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0},viewRenderer:()=>{const e=document.createElement("div");return e.className="dg-row-drag-handle",e.setAttribute("aria-label","Drag to reorder"),e.setAttribute("role","button"),e.setAttribute("tabindex","-1"),e.draggable=!0,this.setIcon(e,this.resolveIcon("dragHandle")),e}};return"right"===this.config.dragHandlePosition?[...e,t]:[t,...e]}afterRender(){if(!this.config.showDragHandle)return;const e=this.gridElement;if(!e)return;e.querySelectorAll(".dg-row-drag-handle").forEach(e=>{const t=e;if(t.getAttribute("data-drag-bound"))return;t.setAttribute("data-drag-bound","true");const i=t.closest(".data-grid-row");i&&this.setupHandleDragListeners(t,i)});e.querySelectorAll(".data-grid-row").forEach(e=>{const t=e;t.getAttribute("data-drop-bound")||(t.setAttribute("data-drop-bound","true"),this.setupRowDropListeners(t))})}onKeyDown(e){if(!this.config.enableKeyboard)return;if(!e.ctrlKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key)return;const t=this.grid,i=t._focusRow,n=t._rows??this.sourceRows;if(i<0||i>=n.length)return;const r="ArrowUp"===e.key?"up":"down",o="up"===r?i-1:i+1;if(o<0||o>=n.length)return;const s=n[i];return!this.config.canMove||this.config.canMove(s,i,o,r)?(this.handleKeyboardMove(s,i,o,r,t._focusCol),e.preventDefault(),e.stopPropagation(),!0):void 0}onCellClick(){this.flushPendingMove()}moveRow(e,t){const i=[...this.sourceRows];if(e<0||e>=i.length)return;if(t<0||t>=i.length)return;if(e===t)return;const n=t<e?"up":"down",r=i[e];this.config.canMove&&!this.config.canMove(r,e,t,n)||this.executeMove(r,e,t,"keyboard")}canMoveRow(e,t){const i=this.sourceRows;if(e<0||e>=i.length)return!1;if(t<0||t>=i.length)return!1;if(e===t)return!1;if(!this.config.canMove)return!0;const n=t<e?"up":"down";return this.config.canMove(i[e],e,t,n)}setupHandleDragListeners(e,t){e.addEventListener("dragstart",e=>{const i=this.getRowIndex(t);i<0||(this.isDragging=!0,this.draggedRowIndex=i,e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",String(i))),t.classList.add("dragging"))}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.clearDragClasses()})}setupRowDropListeners(e){e.addEventListener("dragover",t=>{if(t.preventDefault(),!this.isDragging||null===this.draggedRowIndex)return;const i=this.getRowIndex(e);if(i<0||i===this.draggedRowIndex)return;const n=e.getBoundingClientRect(),r=n.top+n.height/2,o=t.clientY<r;this.dropRowIndex=o?i:i+1,e.classList.add("drop-target"),e.classList.toggle("drop-before",o),e.classList.toggle("drop-after",!o)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",e=>{e.preventDefault();const t=this.draggedRowIndex;let i=this.dropRowIndex;if(this.isDragging&&null!==t&&null!==i&&(i>t&&i--,t!==i)){const e=this.sourceRows[t],n=i<t?"up":"down";this.config.canMove&&!this.config.canMove(e,t,i,n)||this.executeMove(e,t,i,"drag")}})}handleKeyboardMove(e,t,i,n,r){this.pendingMove?this.pendingMove.currentIndex=i:this.pendingMove={originalIndex:t,currentIndex:i,row:e},this.lastFocusCol=r;const o=this.grid,s=[...o._rows??this.sourceRows],[l]=s.splice(t,1);s.splice(i,0,l),o._rows=s,o._focusRow=i,o._focusCol=r,o.refreshVirtualWindow(!0),K(o),this.clearDebounceTimer(),this.debounceTimer=setTimeout(()=>{this.flushPendingMove()},this.config.debounceMs??300)}flushPendingMove(){if(this.clearDebounceTimer(),!this.pendingMove)return;const{originalIndex:e,currentIndex:t,row:i}=this.pendingMove;if(this.pendingMove=null,e===t)return;const n={row:i,fromIndex:e,toIndex:t,rows:[...this.sourceRows],source:"keyboard"};if(this.emitCancelable("row-move",n)){const i=[...this.sourceRows],[n]=i.splice(t,1);i.splice(e,0,n);const r=this.grid;r._rows=i,r._focusRow=e,r._focusCol=this.lastFocusCol,r.refreshVirtualWindow(!0),K(r)}}executeMove(e,t,i,n){const r=[...this.sourceRows],[o]=r.splice(t,1);r.splice(i,0,o);const s={row:e,fromIndex:t,toIndex:i,rows:r,source:n};if(!this.emitCancelable("row-move",s))if("flip"===this.animationType&&this.gridElement){const e=this.captureRowPositions();this.grid.rows=r,requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(e,t,i)})}else this.grid.rows=r}captureRowPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".data-grid-row").forEach(t=>{const i=this.getRowIndex(t);i>=0&&e.set(i,t.getBoundingClientRect().top)}),e}animateFLIP(e,t,i){const n=this.gridElement;if(!n||0===e.size)return;const r=Math.min(t,i),o=Math.max(t,i),s=[];if(n.querySelectorAll(".data-grid-row").forEach(n=>{const l=n,a=this.getRowIndex(l);if(a<0||a<r||a>o)return;let d;d=a===i?t:t<i?a+1:a-1;const c=e.get(d);if(void 0===c)return;const h=c-l.getBoundingClientRect().top;Math.abs(h)>1&&s.push({el:l,deltaY:h})}),0===s.length)return;s.forEach(({el:e,deltaY:t})=>{e.style.transform=`translateY(${t}px)`}),n.offsetHeight;const l=this.animationDuration;requestAnimationFrame(()=>{s.forEach(({el:e})=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{s.forEach(({el:e})=>{e.style.transform="",e.classList.remove("flip-animating")})},l+50)})}getRowIndex(e){const t=e.querySelector(".cell[data-row]");return t?parseInt(t.getAttribute("data-row")??"-1",10):-1}clearDragClasses(){this.gridElement?.querySelectorAll(".data-grid-row").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}},e.SelectionPlugin=class extends rt{static manifest={queries:[{type:"getSelection",description:"Get the current selection state"},{type:"selectRows",description:"Select specific rows by index (row mode only)"},{type:"getSelectedRowIndices",description:"Get sorted array of selected row indices"},{type:"getSelectedRows",description:"Get actual row objects for the current selection (works in all modes)"}],configRules:[{id:"selection/range-dblclick",severity:"warn",message:'"triggerOn: \'dblclick\'" has no effect when mode is "range".\n → Range selection uses drag interaction (mousedown → mousemove), not click events.\n → The "triggerOn" option only affects "cell" and "row" selection modes.',check:e=>"range"===e.mode&&"dblclick"===e.triggerOn}]};name="selection";styles='@layer tbw-plugins{tbw-grid.selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}tbw-grid:has(.selection){-webkit-user-select:none;user-select:none}tbw-grid .data-grid-row.row-focus{background-color:var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%));outline:none;position:relative}tbw-grid .data-grid-row.row-focus:after{content:"";position:absolute;inset:0;pointer-events:none;border-width:0;border-style:var(--tbw-selection-border-style, var(--tbw-border-style));border-color:var(--tbw-range-border-color, var(--tbw-color-accent));border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width));border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width));z-index:1}tbw-grid .data-grid-row.row-focus+.data-grid-row.row-focus:after{border-top-width:0}tbw-grid .data-grid-row.row-focus:has(+.data-grid-row.row-focus):after{border-bottom-width:0}tbw-grid[data-selection-mode=row] .cell-focus,tbw-grid[data-selection-mode=row] .row-focus,tbw-grid[data-selection-mode=range] .cell-focus{outline:none}tbw-grid .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg);position:relative}tbw-grid .data-grid-row>.cell.selected:after{content:"";position:absolute;inset:0;pointer-events:none;border:0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1}tbw-grid .data-grid-row>.cell.selected.top:after{border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.bottom:after{border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.first:after{border-left-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.last:after{border-right-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row[data-selectable=false].row-focus{background-color:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row>.cell[data-selectable=false].selected{background-color:var(--tbw-selection-warning-bg, rgba(from var(--tbw-color-error) r g b / 50%))}tbw-grid .tbw-selection-summary{font-size:var(--tbw-font-size-sm, .8125rem);color:var(--tbw-color-fg-muted);white-space:nowrap}tbw-grid .data-grid-row>.cell[data-field=__tbw_checkbox],tbw-grid .header-row>.cell[data-field=__tbw_checkbox]{text-align:center;cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .tbw-select-row-checkbox{pointer-events:none;margin:0;cursor:pointer}tbw-grid .tbw-checkbox-header{display:flex;justify-content:center;align-items:center;height:100%}tbw-grid .tbw-select-all-checkbox{margin:0;cursor:pointer}}';get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0}}selected=new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;selectedCell=null;lastSyncedFocusRow=-1;lastSyncedFocusCol=-1;explicitSelection=!1;isSelectionEnabled(){return!1!==this.config.enabled&&!1!==this.grid.effectiveConfig?.selectable}checkSelectable(e,t){const{isSelectable:i}=this.config;if(!i)return!0;const n=this.rows[e];if(!n)return!1;return i(n,e,void 0!==t?this.visibleColumns[t]:void 0,t)}isRowSelectable(e){return this.checkSelectable(e)}isCellSelectable(e,t){return this.checkSelectable(e,t)}attach(e){super.attach(e),this.on("filter-applied",()=>this.clearSelectionSilent()),this.on("grouping-state-change",()=>this.clearSelectionSilent()),this.on("tree-state-change",()=>this.clearSelectionSilent())}handleQuery(e){return"getSelection"===e.type?this.getSelection():"getSelectedRowIndices"===e.type?this.getSelectedRowIndices():"getSelectedRows"===e.type?this.getSelectedRows():"selectRows"===e.type?(this.selectRows(e.context),!0):void 0}detach(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.pendingKeyboardUpdate=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1}clearSelectionSilent(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedCell=null,this.lastSelected=null,this.anchor=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,this.requestAfterRender()}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{rowIndex:t,colIndex:i,originalEvent:n}=e,{mode:r,triggerOn:o="click"}=this.config;if(n.type!==o)return!1;const s=e.column,l=s&&Wt(s);if("cell"===r){if(l)return!1;if(!this.isCellSelectable(t,i))return!1;const e=this.selectedCell;return e&&e.row===t&&e.col===i||(this.selectedCell={row:t,col:i},this.emit("selection-change",this.#Ki()),this.requestAfterRender()),!1}if("row"===r){if(!this.isRowSelectable(t))return!1;const e=!1!==this.config.multiSelect,i=n.shiftKey&&e,r=(n.ctrlKey||n.metaKey)&&e,o=!0===s?.meta?.checkboxColumn;if(i&&null!==this.anchor){const e=Math.min(this.anchor,t),i=Math.max(this.anchor,t);r||this.selected.clear();for(let t=e;t<=i;t++)this.isRowSelectable(t)&&this.selected.add(t)}else if(r||o&&e)this.selected.has(t)?this.selected.delete(t):this.selected.add(t),this.anchor=t;else{if(1===this.selected.size&&this.selected.has(t))return!1;this.selected.clear(),this.selected.add(t),this.anchor=t}return this.lastSelected=t,this.explicitSelection=!0,this.emit("selection-change",this.#Ki()),this.requestAfterRender(),!1}if("range"===r){if(l)return!1;if(!this.isCellSelectable(t,i))return!1;const e=n.shiftKey,r=(n.ctrlKey||n.metaKey)&&!1!==this.config.multiSelect;if(e&&this.cellAnchor){const e=Ui(this.cellAnchor,{row:t,col:i}),n=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(n&&ji(n,e))return!1;r?this.ranges.length>0?this.ranges[this.ranges.length-1]=e:this.ranges.push(e):this.ranges=[e],this.activeRange=e}else if(r){const e={startRow:t,startCol:i,endRow:t,endCol:i};this.ranges.push(e),this.activeRange=e,this.cellAnchor={row:t,col:i}}else{const e={startRow:t,startCol:i,endRow:t,endCol:i};if(1===this.ranges.length&&ji(this.ranges[0],e))return!1;this.ranges=[e],this.activeRange=e,this.cellAnchor={row:t,col:i}}return this.emit("selection-change",this.#Ki()),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.#Ki()),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.#Ki()),this.requestAfterRender()}),!1;if("row"===t){const t=!1!==this.config.multiSelect;if("ArrowUp"===e.key||"ArrowDown"===e.key){const i=e.shiftKey&&t;return i&&null===this.anchor&&(this.anchor=this.grid._focusRow),queueMicrotask(()=>{const e=this.grid._focusRow;if(i&&null!==this.anchor){this.selected.clear();const t=Math.min(this.anchor,e),i=Math.max(this.anchor,e);for(let e=t;e<=i;e++)this.isRowSelectable(e)&&this.selected.add(e)}else this.isRowSelectable(e)?(this.selected.clear(),this.selected.add(e),this.anchor=e):this.selected.clear();this.lastSelected=e,this.explicitSelection=!0,this.emit("selection-change",this.#Ki()),this.requestAfterRender()}),!1}if(t&&"a"===e.key&&(e.ctrlKey||e.metaKey)){return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}}if("range"===t&&i){const t="Tab"===e.key,i=e.shiftKey&&!t;return i&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:i},queueMicrotask(()=>this.requestAfterRender()),!1}if("range"===t&&!1!==this.config.multiSelect&&"a"===e.key&&(e.ctrlKey||e.metaKey)){return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}return!1}onCellMouseDown(e){if(!this.isSelectionEnabled())return;if("range"!==this.config.mode)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;if(e.column&&Wt(e.column))return;if(!this.isCellSelectable(e.rowIndex,e.colIndex))return;if(e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const t=e.rowIndex,i=e.colIndex,n=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&!1!==this.config.multiSelect,r={startRow:t,startCol:i,endRow:t,endCol:i};return!n&&1===this.ranges.length&&ji(this.ranges[0],r)?(this.cellAnchor={row:t,col:i},!0):(this.cellAnchor={row:t,col:i},n||(this.ranges=[]),this.ranges.push(r),this.activeRange=r,this.emit("selection-change",this.#Ki()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled())return;if("range"!==this.config.mode)return;if(!this.isDragging||!this.cellAnchor)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;let t=e.colIndex;const i=this.visibleColumns[t];if(i&&Wt(i)){const e=this.visibleColumns.findIndex(e=>!Wt(e));e>=0&&(t=e)}const n=Ui(this.cellAnchor,{row:e.rowIndex,col:t}),r=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return r&&ji(r,n)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=n:this.ranges.push(n),this.activeRange=n,this.emit("selection-change",this.#Ki()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&"range"===this.config.mode)return this.isDragging?(this.isDragging=!1,!0):void 0}processColumns(e){if(this.config.checkbox&&"row"===this.config.mode){if(e.some(e=>e.field===Yi))return e;const t=this.#Ui(),i=e.findIndex(Bt),n=i>=0?i+1:0;return[...e.slice(0,n),t,...e.slice(n)]}return e}#Ui(){return{field:Yi,header:"",width:32,resizable:!1,sortable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0,checkboxColumn:!0},headerRenderer:()=>{const e=document.createElement("div");if(e.className="tbw-checkbox-header",!1===this.config.multiSelect)return e;const t=document.createElement("input");return t.type="checkbox",t.className="tbw-select-all-checkbox",t.addEventListener("click",e=>{e.stopPropagation(),e.target.checked?this.selectAll():this.clearSelection()}),e.appendChild(t),e},renderer:e=>{const t=document.createElement("input");t.type="checkbox",t.className="tbw-select-row-checkbox";const i=e.cellEl;if(i){const e=parseInt(i.getAttribute("data-row")??"-1",10);e>=0&&(t.checked=this.selected.has(e))}return t}}}#ji(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const t=e.closest(".cell"),i=t?T(t):-1;i>=0&&(e.checked=this.selected.has(i))});const t=e.querySelector(".tbw-select-all-checkbox");if(t){const e=this.rows.length;let i=0;if(this.config.isSelectable)for(let t=0;t<e;t++)this.isRowSelectable(t)&&i++;else i=e;const n=i>0&&this.selected.size>=i,r=this.selected.size>0;t.checked=n,t.indeterminate=r&&!n}}#Yi(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.#Ki()))))}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.#Ki()))}}}#Xi(){const e=this.gridElement;if(!e)return;const{mode:t}=this.config,i=!!this.config.isSelectable;e.querySelectorAll(".cell").forEach(e=>{e.classList.remove("selected","top","bottom","first","last"),i&&e.removeAttribute("data-selectable")});const n=e.querySelectorAll(".data-grid-row");if(n.forEach(e=>{e.classList.remove("selected","row-focus"),i&&e.removeAttribute("data-selectable")}),"row"===t&&(L(e),n.forEach(e=>{const t=T(e.querySelector(".cell[data-row]"));t>=0&&(i&&!this.isRowSelectable(t)&&e.setAttribute("data-selectable","false"),this.selected.has(t)&&e.classList.add("selected","row-focus"))}),this.config.checkbox&&this.#ji(e)),("cell"===t||"range"===t)&&i){e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),i=parseInt(e.getAttribute("data-col")??"-1",10);t>=0&&i>=0&&(this.isCellSelectable(t,i)||e.setAttribute("data-selectable","false"))})}if("range"===t&&this.ranges.length>0){L(e);const t=this.ranges.map(Vi),i=(e,i)=>{for(const n of t)if(e>=n.startRow&&e<=n.endRow&&i>=n.startCol&&i<=n.endCol)return!0;return!1};e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),n=parseInt(e.getAttribute("data-col")??"-1",10);if(t>=0&&n>=0){const r=this.visibleColumns[n];if(r&&Wt(r))return;i(t,n)&&(e.classList.add("selected"),i(t-1,n)||e.classList.add("top"),i(t+1,n)||e.classList.add("bottom"),i(t,n-1)||e.classList.add("first"),i(t,n+1)||e.classList.add("last"))}})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.children[0],{mode:i}=this.config;if(this.pendingKeyboardUpdate&&"range"===i){const{shiftKey:e}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const t=this.grid._focusRow,i=this.grid._focusCol;if(e&&this.cellAnchor){const e=Ui(this.cellAnchor,{row:t,col:i});this.ranges=[e],this.activeRange=e}else e||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:t,col:i});this.emit("selection-change",this.#Ki())}this.#Yi(i),this.grid.setAttribute("data-selection-mode",i),t&&t.classList.toggle("selecting",this.isDragging),this.#Xi()}onScrollRender(){this.isSelectionEnabled()&&this.#Xi()}getSelection(){return{mode:this.config.mode,ranges:this.#Ki().ranges,anchor:this.cellAnchor}}getSelectedCells(){return function(e){const t=new Map;for(const i of e)for(const e of Ki(i))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return Wi(e,t,this.ranges)}selectAll(){const{mode:e,multiSelect:t}=this.config;if(!1!==t)if("row"===e){this.selected.clear();for(let e=0;e<this.rows.length;e++)this.isRowSelectable(e)&&this.selected.add(e);this.explicitSelection=!0,this.emit("selection-change",this.#Ki()),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.#Ki()),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.#Ki()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const{mode:e}=this.config,t=this.rows;if("row"===e)return this.getSelectedRowIndices().filter(e=>e>=0&&e<t.length).map(e=>t[e]);if("cell"===e&&this.selectedCell){const{row:e}=this.selectedCell;return e>=0&&e<t.length?[t[e]]:[]}if("range"===e&&this.ranges.length>0){const e=new Set;for(const i of this.ranges){const n=Math.max(0,Math.min(i.startRow,i.endRow)),r=Math.min(t.length-1,Math.max(i.startRow,i.endRow));for(let t=n;t<=r;t++)e.add(t)}return[...e].sort((e,t)=>e-t).map(e=>t[e])}return[]}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.emit("selection-change",{mode:this.config.mode,ranges:[]}),this.requestAfterRender()}setRanges(e){this.ranges=e.map(e=>({startRow:e.from.row,startCol:e.from.col,endRow:e.to.row,endCol:e.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",{mode:this.config.mode,ranges:Bi(this.ranges)}),this.requestAfterRender()}#Ki(){return function(e,t,i){if("cell"===e&&t.selectedCell)return{mode:e,ranges:[{from:{row:t.selectedCell.row,col:t.selectedCell.col},to:{row:t.selectedCell.row,col:t.selectedCell.col}}]};if("row"===e&&t.selected.size>0){const n=[...t.selected].sort((e,t)=>e-t),r=[];let o=n[0],s=o;for(let e=1;e<n.length;e++)n[e]===s+1?s=n[e]:(r.push({from:{row:o,col:0},to:{row:s,col:i-1}}),o=n[e],s=o);return r.push({from:{row:o,col:0},to:{row:s,col:i-1}}),{mode:e,ranges:r}}return"range"===e&&t.ranges.length>0?{mode:e,ranges:Bi(t.ranges)}:{mode:e,ranges:[]}}(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}},e.ServerSidePlugin=class extends rt{name="serverSide";get defaultConfig(){return{pageSize:100,cacheBlockSize:100,maxConcurrentRequests:2}}dataSource=null;totalRowCount=0;loadedBlocks=new Map;loadingBlocks=new Set;lastRequestId=0;scrollDebounceTimer;detach(){this.dataSource=null,this.totalRowCount=0,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.lastRequestId=0,this.scrollDebounceTimer&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=void 0)}loadRequiredBlocks(){if(!this.dataSource)return;const e=this.grid,t=this.config.cacheBlockSize??100,i={startRow:e._virtualization.start,endRow:e._virtualization.end},n=function(e,t,i){const n=Xi(e,i),r=Xi(t-1,i),o=[];for(let s=n;s<=r;s++)o.push(s);return o}(i.startRow,i.endRow,t);for(const r of n)if(!this.loadedBlocks.has(r)&&!this.loadingBlocks.has(r)){if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2))break;this.loadingBlocks.add(r),Zi(this.dataSource,r,t,{}).then(e=>{this.loadedBlocks.set(r,e.rows),this.totalRowCount=e.totalRowCount,this.loadingBlocks.delete(r),this.requestRender(),this.loadRequiredBlocks()}).catch(()=>{this.loadingBlocks.delete(r)})}}processRows(e){if(!this.dataSource)return[...e];const t=[];for(let i=0;i<this.totalRowCount;i++){const e=Qi(i,this.config.cacheBlockSize??100,this.loadedBlocks);t.push(e??{__loading:!0,__index:i})}return t}onScroll(e){this.dataSource&&(this.loadRequiredBlocks(),this.scrollDebounceTimer&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.loadRequiredBlocks()},100))}setDataSource(e){this.dataSource=e,this.loadedBlocks.clear(),this.loadingBlocks.clear();Zi(e,0,this.config.cacheBlockSize??100,{}).then(e=>{this.loadedBlocks.set(0,e.rows),this.totalRowCount=e.totalRowCount,this.requestRender()})}refresh(){this.dataSource&&(this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.requestRender())}purgeCache(){this.loadedBlocks.clear()}getTotalRowCount(){return this.totalRowCount}isRowLoaded(e){const t=Xi(e,this.config.cacheBlockSize??100);return this.loadedBlocks.has(t)}getLoadedBlockCount(){return this.loadedBlocks.size}},e.TreePlugin=class extends rt{static manifest={events:[{type:"tree-state-change",description:"Emitted when tree expansion state changes (toggle, expand all, collapse all)"}],queries:[{type:"canMoveRow",description:"Returns false for rows with children (parent nodes cannot be reordered)"}]};name="tree";styles="@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-inline-end:none!important;padding:0;display:flex;align-items:center;justify-content:flex-start}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1 / 3}tbw-grid .tree-cell-wrapper{display:inline-flex;align-items:center;padding-inline-start:calc(var(--tbw-tree-depth, 0) * var(--tbw-tree-indent-width, var(--tbw-tree-toggle-size, 1.25em)))}tbw-grid .tree-expander{display:flex;align-items:center;justify-content:flex-start;width:100%;height:100%;box-sizing:border-box}tbw-grid .tree-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-tree-toggle-size, 1.25em);height:var(--tbw-tree-toggle-size, 1.25em);flex-shrink:0}tbw-grid .tree-toggle:hover{color:var(--tbw-tree-accent, var(--tbw-color-accent))}tbw-grid .tree-spacer{width:var(--tbw-tree-toggle-size, 1.25em);display:inline-block;flex-shrink:0}tbw-grid .data-grid-row.tbw-tree-slide-in{animation:tbw-tree-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .data-grid-row.tbw-tree-fade-in{animation:tbw-tree-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-tree-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}@keyframes tbw-tree-fade-in{0%{opacity:0}to{opacity:1}}}";get defaultConfig(){return{childrenField:"children",autoDetect:!0,defaultExpanded:!1,indentWidth:20,showExpandIcons:!0,animation:"slide"}}expandedKeys=new Set;initialExpansionDone=!1;flattenedRows=[];rowKeyMap=new Map;previousVisibleKeys=new Set;keysToAnimate=new Set;sortState=null;detach(){this.expandedKeys.clear(),this.initialExpansionDone=!1,this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.sortState=null}handleQuery(e){if("canMoveRow"===e.type){const t=e.context,i=this.config.childrenField??"children",n=t?.[i];if(Array.isArray(n)&&n.length>0)return!1}}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detect(e){if(!this.config.autoDetect)return!1;const t=e,i=this.config.childrenField??function(e){if(!Array.isArray(e)||0===e.length)return null;const t=["children","items","nodes","subRows","nested"];for(const i of e)if(i&&"object"==typeof i)for(const e of t){const t=i[e];if(Array.isArray(t)&&t.length>0)return e}return null}(t)??"children";return on(t,i)}processRows(e){const t=e;if(!on(t,this.config.childrenField??"children"))return this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),[...e];let i=this.withStableKeys(t);this.sortState&&(i=this.sortTree(i,this.sortState.field,this.sortState.direction)),this.config.defaultExpanded&&!this.initialExpansionDone&&(this.expandedKeys=tn(i,this.config),this.initialExpansionDone=!0),this.flattenedRows=this.flattenTree(i,this.expandedKeys),this.rowKeyMap.clear(),this.keysToAnimate.clear();const n=new Set;for(const r of this.flattenedRows)this.rowKeyMap.set(r.key,r),n.add(r.key),!this.previousVisibleKeys.has(r.key)&&r.depth>0&&this.keysToAnimate.add(r.key);return this.previousVisibleKeys=n,this.flattenedRows.map(e=>({...e.data,__treeKey:e.key,__treeDepth:e.depth,__treeHasChildren:e.hasChildren,__treeExpanded:e.isExpanded}))}withStableKeys(e,t=null){const i=this.config.childrenField??"children";return e.map((e,n)=>{const r=e.__stableKey,o=void 0!==e.id?String(e.id):r??(t?`${t}-${n}`:String(n)),s=e[i],l=Array.isArray(s)&&s.length>0;return{...e,__stableKey:o,...l?{[i]:this.withStableKeys(s,o)}:{}}})}flattenTree(e,t,i=0){const n=this.config.childrenField??"children",r=[];for(const o of e){const e=o.__stableKey??String(o.id??"?"),s=o[n],l=Array.isArray(s)&&s.length>0,a=t.has(e);r.push({key:e,data:o,depth:i,hasChildren:l,isExpanded:a,parentKey:i>0&&e.substring(0,e.lastIndexOf("-"))||null}),l&&a&&r.push(...this.flattenTree(s,t,i+1))}return r}sortTree(e,t,i){const n=this.config.childrenField??"children";return[...e].sort((e,n)=>{const r=e[t],o=n[t];return null==r&&null==o?0:null==r?-1:null==o?1:r>o?i:r<o?-i:0}).map(e=>{const r=e[n];return Array.isArray(r)&&r.length>0?{...e,[n]:this.sortTree(r,t,i)}:e})}processColumns(e){if(0===this.flattenedRows.length)return[...e];const t=[...e];if(0===t.length)return t;const i=t[0],n=i.viewRenderer,r=()=>this.config,o=this.setIcon.bind(this),s=this.resolveIcon.bind(this);return t[0]={...i,viewRenderer:e=>{const{row:t,value:i}=e,{showExpandIcons:l=!0,indentWidth:a}=r(),d=t,c=d.__treeDepth??0,h=document.createElement("span");if(h.className="tree-cell-wrapper",h.style.setProperty("--tbw-tree-depth",String(c)),void 0!==a&&h.style.setProperty("--tbw-tree-indent-width",`${a}px`),l)if(d.__treeHasChildren){const e=document.createElement("span");e.className="tree-toggle"+(d.__treeExpanded?" expanded":""),o(e,s(d.__treeExpanded?"collapse":"expand")),e.setAttribute("data-tree-key",String(d.__treeKey??"")),h.appendChild(e)}else{const e=document.createElement("span");e.className="tree-spacer",h.appendChild(e)}const u=document.createElement("span");if(u.className="tree-content",n){const t=n(e);t instanceof Node?u.appendChild(t):"string"==typeof t&&(u.innerHTML=t)}else u.textContent=null!=i?String(i):"";return h.appendChild(u),h}},t}onCellClick(e){const t=e.originalEvent?.target;if(!t?.classList.contains("tree-toggle"))return!1;const i=t.getAttribute("data-tree-key");if(!i)return!1;const n=this.rowKeyMap.get(i);return!!n&&(this.expandedKeys=en(this.expandedKeys,i),this.emit("tree-expand",{key:i,row:n.data,expanded:this.expandedKeys.has(i),depth:n.depth}),this.requestRender(),!0)}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusRow,i=this.flattenedRows[t];return i?.hasChildren?(e.preventDefault(),this.expandedKeys=en(this.expandedKeys,i.key),this.emit("tree-expand",{key:i.key,row:i.data,expanded:this.expandedKeys.has(i.key),depth:i.depth}),this.requestRenderWithFocus(),!0):void 0}onHeaderClick(e){if(0===this.flattenedRows.length||!e.column.sortable)return!1;const{field:t}=e.column;this.sortState&&this.sortState.field===t?1===this.sortState.direction?this.sortState={field:t,direction:-1}:this.sortState=null:this.sortState={field:t,direction:1};const i=this.grid;return void 0!==i._sortState&&(i._sortState=this.sortState?{...this.sortState}:null),this.emit("sort-change",{field:t,direction:this.sortState?.direction??0}),this.requestRender(),!0}afterRender(){const e=this.animationStyle;if(!1===e||0===this.keysToAnimate.size)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const i="fade"===e?"tbw-tree-fade-in":"tbw-tree-slide-in";for(const n of t.querySelectorAll(".data-grid-row")){const e=n.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,r=this.flattenedRows[t]?.key;r&&this.keysToAnimate.has(r)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}expand(e){this.expandedKeys.add(e),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}toggle(e){this.expandedKeys=en(this.expandedKeys,e),this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}expandAll(){this.expandedKeys=tn(this.rows,this.config),this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}getExpandedKeys(){return[...this.expandedKeys]}getFlattenedRows(){return[...this.flattenedRows]}getRowByKey(e){return this.rowKeyMap.get(e)?.data}expandToKey(e){this.expandedKeys=rn(this.rows,e,this.config,this.expandedKeys),this.requestRender()}},e.UndoRedoPlugin=class extends rt{static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];attach(e){super.attach(e),this.on("cell-edit-committed",e=>{this.recordEdit(e.rowIndex,e.field,e.oldValue,e.newValue)})}detach(){this.undoStack=[],this.redoStack=[]}onKeyDown(e){const t=(e.ctrlKey||e.metaKey)&&"z"===e.key&&!e.shiftKey,i=(e.ctrlKey||e.metaKey)&&("y"===e.key||"z"===e.key&&e.shiftKey);if(t){const e=sn({undoStack:this.undoStack,redoStack:this.redoStack});if(e.action){const t=this.rows;t[e.action.rowIndex]&&(t[e.action.rowIndex][e.action.field]=e.action.oldValue),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.emit("undo",{action:e.action,type:"undo"}),this.requestRender()}return!0}if(i){const e=ln({undoStack:this.undoStack,redoStack:this.redoStack});if(e.action){const t=this.rows;t[e.action.rowIndex]&&(t[e.action.rowIndex][e.action.field]=e.action.newValue),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.emit("redo",{action:e.action,type:"redo"}),this.requestRender()}return!0}return!1}recordEdit(e,t,i,n){const r=function(e,t,i,n){return{type:"cell-edit",rowIndex:e,field:t,oldValue:i,newValue:n,timestamp:Date.now()}}(e,t,i,n),o=function(e,t,i){const n=[...e.undoStack,t];for(;n.length>i;)n.shift();return{undoStack:n,redoStack:[]}}({undoStack:this.undoStack,redoStack:this.redoStack},r,this.config.maxHistorySize??100);this.undoStack=o.undoStack,this.redoStack=o.redoStack}undo(){const e=sn({undoStack:this.undoStack,redoStack:this.redoStack});if(e.action){const t=this.rows;t[e.action.rowIndex]&&(t[e.action.rowIndex][e.action.field]=e.action.oldValue),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.requestRender()}return e.action}redo(){const e=ln({undoStack:this.undoStack,redoStack:this.redoStack});if(e.action){const t=this.rows;t[e.action.rowIndex]&&(t[e.action.rowIndex][e.action.field]=e.action.newValue),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.requestRender()}return e.action}canUndo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.undoStack.length>0}canRedo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.redoStack.length>0}clearHistory(){const e={undoStack:[],redoStack:[]};this.undoStack=e.undoStack,this.redoStack=e.redoStack}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}},e.VisibilityPlugin=dn,e.builtInSort=Q,e.createGrid=function(e){const t=document.createElement("tbw-grid");return e&&(t.gridConfig=e),t},e.defaultComparator=Z,e.defaultEditorFor=Mt,e.defaultPasteHandler=ut,e.getUniqueValuesBatch=Vt,e.printGridIsolated=Fi,e.queryGrid=function(e,t=document){return t.querySelector(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={mode:"reduced-motion",duration:200,easing:"ease-out"},n='<svg viewBox="0 0 16 16" width="12" height="12"><path fill="currentColor" d="M6 10.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/></svg>',r={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:n,filterActive:n,print:"🖨️"};function o(e,t){if(!(e&&e.length||t&&t.length))return[];if(!e||!e.length)return t||[];if(!t||!t.length)return e;const i={};t.forEach(e=>{const t=i[e.field];if(t){e.header&&!t.header&&(t.header=e.header),e.type&&!t.type&&(t.type=e.type),e.sortable&&(t.sortable=!0),e.editable&&(t.editable=!0),e.resizable&&(t.resizable=!0),null!=e.width&&null==t.width&&(t.width=e.width),null!=e.minWidth&&null==t.minWidth&&(t.minWidth=e.minWidth),e.__viewTemplate&&(t.__viewTemplate=e.__viewTemplate),e.__editorTemplate&&(t.__editorTemplate=e.__editorTemplate),e.__headerTemplate&&(t.__headerTemplate=e.__headerTemplate);const i=e.renderer||e.viewRenderer,n=t.renderer||t.viewRenderer;i&&!n&&(t.viewRenderer=i,e.renderer&&(t.renderer=i)),e.editor&&!t.editor&&(t.editor=e.editor)}else i[e.field]={...e}});const n=e.map(e=>{const t=i[e.field];if(!t)return e;const n={...e};t.header&&!n.header&&(n.header=t.header),t.type&&!n.type&&(n.type=t.type),n.sortable=e.sortable||t.sortable,!0!==e.resizable&&!0!==t.resizable||(n.resizable=!0),n.editable=e.editable||t.editable,null!=t.width&&null==n.width&&(n.width=t.width),null!=t.minWidth&&null==n.minWidth&&(n.minWidth=t.minWidth),t.__viewTemplate&&(n.__viewTemplate=t.__viewTemplate),t.__editorTemplate&&(n.__editorTemplate=t.__editorTemplate),t.__headerTemplate&&(n.__headerTemplate=t.__headerTemplate);const r=t.renderer||t.viewRenderer,o=n.renderer||n.viewRenderer;return r&&!o&&(n.viewRenderer=r,t.renderer&&(n.renderer=r)),t.editor&&!n.editor&&(n.editor=t.editor),delete i[e.field],n});return Object.keys(i).forEach(e=>n.push(i[e])),n}function s(e,t){try{e.part?.add?.(t)}catch{}const i=e.getAttribute("part");i?i.split(/\s+/).includes(t)||e.setAttribute("part",i+" "+t):e.setAttribute("part",t)}function l(e){const i=e.effectiveConfig?.fitMode||e.fitMode||t.STRETCH;if(i!==t.STRETCH&&i!==t.FIXED)return;if(e.__didInitialAutoSize)return;if(!e.isConnected)return;const n=Array.from(e._headerRowEl?.children||[]);if(!n.length)return;let r=!1;e._visibleColumns.forEach((t,i)=>{if(t.width)return;const o=n[i];let s=o?o.scrollWidth:0;for(const n of e._rowPool){const e=n.children[i];if(e){const t=e.scrollWidth;t>s&&(s=t)}}s>0&&(t.width=s+2,t.__autoSized=!0,r=!0)}),r&&c(e),e.__didInitialAutoSize=!0}const a=/^(?:\d+(?:\.\d+)?(?:px|%|fr|em|rem|ch|vw|vh|vmin|vmax)|calc\(.+\)|min-content|max-content|minmax\(.+\)|fit-content\(.+\)|auto)$/i;function d(e,t){return"number"==typeof e?`${e}px`:(a.test(e)||console.warn(`[tbw-grid] Column '${t??"?"}' has an invalid CSS width value: '${e}'. Expected a number (px) or a valid CSS unit string (e.g. '30%', '2fr', 'calc(...)').`),e)}function c(e){const i=e.effectiveConfig?.fitMode||e.fitMode||t.STRETCH;e._gridTemplate=i===t.STRETCH?e._visibleColumns.map(e=>{if(null!=e.width)return d(e.width,e.field);const t=e.minWidth;return null!=t?`minmax(${t}px, 1fr)`:"1fr"}).join(" ").trim():e._visibleColumns.map(e=>null!=e.width?d(e.width,e.field):"max-content").join(" "),e.style.setProperty("--tbw-column-template",e._gridTemplate)}function h(e,t){const i=e[0]||{},n=Object.keys(i).map(e=>{const t=i[e],n=null==(r=t)?"string":"number"==typeof r?"number":"boolean"==typeof r?"boolean":r instanceof Date||"string"==typeof r&&/\d{4}-\d{2}-\d{2}/.test(r)&&!isNaN(Date.parse(r))?"date":"string";var r;return{field:e,header:e.charAt(0).toUpperCase()+e.slice(1),type:n}}),r={};return n.forEach(e=>{r[e.field]=e.type||"string"}),{columns:n,typeMap:r}}const u=/{{\s*([^}]+)\s*}}/g,g="__DG_EMPTY__",p=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,f=/__(proto|defineGetter|defineSetter)|constructor|window|globalThis|global|process|Function|import|eval|Reflect|Proxy|Error|arguments|document|location|cookie|localStorage|sessionStorage|indexedDB|fetch|XMLHttpRequest|WebSocket|Worker|SharedWorker|ServiceWorker|opener|parent|top|frames|self|this\b/;const w=new Set(["script","iframe","object","embed","form","input","button","textarea","select","link","meta","base","style","template","slot","portal","frame","frameset","applet","noscript","noembed","plaintext","xmp","listing"]),m=/^on\w+$/i,b=new Set(["href","src","action","formaction","data","srcdoc","xlink:href","poster","srcset"]),v=/^\s*(javascript|vbscript|data|blob):/i;function y(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],i=e.querySelectorAll("*");for(const n of i){const e=n.tagName.toLowerCase();if(w.has(e)){t.push(n);continue}if("svg"===e||"http://www.w3.org/2000/svg"===n.namespaceURI){if(Array.from(n.attributes).some(e=>m.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(n);continue}}const i=[];for(const t of n.attributes){const e=t.name.toLowerCase();m.test(e)?i.push(t.name):(b.has(e)&&v.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&i.push(t.name)}i.forEach(e=>n.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}function C(e,t){if(!e||-1===e.indexOf("{{"))return e;const i=[],n=e.replace(u,(e,n)=>{const r=function(e,t){if(e=(e||"").trim(),!e)return g;if(x.test(e))return g;if("value"===e)return null==t.value?g:String(t.value);if(e.startsWith("row.")&&!/[()?]/.test(e)&&!e.includes(":")){const i=e.slice(4),n=t.row?t.row[i]:void 0;return null==n?g:String(n)}if(e.length>80)return g;if(!p.test(e)||f.test(e))return g;const i=e.match(/\./g);if(i&&i.length>1)return g;try{const i=new Function("value","row",`return (${e});`)(t.value,t.row),n=null==i?"":String(i);return x.test(n)?g:n||g}catch{return g}}(n,t);return i.push({expr:n.trim(),result:r}),r}),r=(o=n)?o.replace(new RegExp(g,"g"),"").replace(/Reflect\.[^<>{}\s]+|\bProxy\b|ownKeys\([^)]*\)/g,""):o;var o;const s=i.length&&i.every(e=>""===e.result||e.result===g);return x.test(e)||s?"":r}const x=/Reflect|Proxy|ownKeys/;function E(e){if(x.test(e.textContent||"")){for(const t of e.childNodes)t.nodeType===Node.TEXT_NODE&&x.test(t.textContent||"")&&(t.textContent="");x.test(e.textContent||"")&&(e.textContent="")}}function R(e){const t=x.test(e),i=i=>{if(t)return"";return C(e,i)};return i.__blocked=t,i}class S{#e;#t;#i;#n;#r;#o={};#s={};#l=!0;#a=[];#d;#c;#h;#u;#g;constructor(e){this.#u=e}get original(){return this.#o}get effective(){return this.#s}get columns(){return this.#s.columns??[]}set columns(e){this.#s.columns=e}get lightDomColumnsCache(){return this.#n}set lightDomColumnsCache(e){this.#n=e}get originalColumnNodes(){return this.#r}set originalColumnNodes(e){this.#r=e}get lightDomTitle(){return this.#g}set lightDomTitle(e){this.#g=e}get initialColumnState(){return this.#h}set initialColumnState(e){this.#h=e}get sourcesChanged(){return this.#l}markSourcesChanged(){this.#l=!0}setGridConfig(e){this.#e=e,this.#l=!0,this.#n=void 0}getGridConfig(){return this.#e}setColumns(e){this.#t=e,this.#l=!0}getColumns(){return this.#t}setFitMode(e){this.#i=e,this.#l=!0}getFitMode(){return this.#i}merge(){const e=(this.#s.columns?.length??0)>0;if(!this.#l&&e)return;const t=this.#p();this.#l=!1,this.#o=t,Object.freeze(this.#o),this.#o.columns&&Object.freeze(this.#o.columns),this.#s=this.#f(this.#o),this.#w()}#f(e){const t={...e};return e.columns&&(t.columns=e.columns.map(e=>({...e}))),e.shell&&(t.shell={...e.shell,header:e.shell.header?{...e.shell.header}:void 0,toolPanel:e.shell.toolPanel?{...e.shell.toolPanel}:void 0,toolPanels:e.shell.toolPanels?.map(e=>({...e})),headerContents:e.shell.headerContents?.map(e=>({...e}))}),t}#w(){const e=this.#s;if(this.#m(),"number"==typeof e.rowHeight&&e.rowHeight>0&&this.#u.setRowHeight(e.rowHeight),"fixed"===e.fitMode){this.columns.forEach(e=>{null==e.width&&(e.width=80)})}this.#u.applyAnimationConfig(e)}#m(){const e=this.#s.typeDefaults;if(!e)return;const t=this.columns;for(const i of t){if(!i.type)continue;const t=e[i.type];t&&(i.renderer||i.viewRenderer||!t.renderer||(i.renderer=t.renderer),!i.format&&t.format&&(i.format=t.format),!i.editor&&t.editor&&(i.editor=t.editor),!i.editorParams&&t.editorParams&&(i.editorParams=t.editorParams))}}#p(){const e=this.#e?{...this.#e}:{},t=Array.isArray(e.columns)?[...e.columns]:[],i=(this.#n??[]).map(e=>({...e}));let n=o(t,i);this.#t&&this.#t.length&&(n=o(this.#t,i));const r=this.#u.getRows();if(0===n.length&&r.length){n=h(r).columns}return n.length&&(n.forEach(e=>{void 0===e.sortable&&(e.sortable=!0),void 0===e.resizable&&(e.resizable=!0),void 0===e.__originalWidth&&"number"==typeof e.width&&(e.__originalWidth=e.width)}),n.forEach(e=>{e.__viewTemplate&&!e.__compiledView&&(e.__compiledView=R(e.__viewTemplate.innerHTML)),e.__editorTemplate&&!e.__compiledEditor&&(e.__compiledEditor=R(e.__editorTemplate.innerHTML))}),e.columns=n),this.#i&&(e.fitMode=this.#i),e.fitMode||(e.fitMode="stretch"),this.#b(e),e.columnState&&!this.#h&&(this.#h=e.columnState),e}#b(e){e.shell=e.shell?{...e.shell}:{},e.shell.header=e.shell.header?{...e.shell.header}:{};const t=this.#u.getShellLightDomTitle();t&&(this.#g=t),this.#g&&!e.shell.header.title&&(e.shell.header.title=this.#g);const i=this.#u.getShellLightDomHeaderContent();i?.length>0&&(e.shell.header.lightDomContent=i),this.#u.getShellHasToolButtonsContainer()&&(e.shell.header.hasToolButtonsContainer=!0);const n=this.#u.getShellToolPanels();if(n.size>0){const t=Array.from(n.values());t.sort((e,t)=>(e.order??100)-(t.order??100)),e.shell.toolPanels=t}const r=this.#u.getShellHeaderContents();if(r.size>0){const t=Array.from(r.values());t.sort((e,t)=>(e.order??100)-(t.order??100)),e.shell.headerContents=t}const o=this.#u.getShellToolbarContents(),s=Array.from(o.values()),l=this.#e?.shell?.header?.toolbarContents??[],a=new Set(l.map(e=>e.id)),d=[...l];for(const c of s)a.has(c.id)||d.push(c);d.sort((e,t)=>(e.order??0)-(t.order??0)),e.shell.header.toolbarContents=d}collectState(e){const t=this.columns,i=this.#v();return{columns:t.map((t,n)=>{const r={field:t.field,order:n,visible:!t.hidden},o=t;void 0!==o.__renderedWidth?r.width=o.__renderedWidth:void 0!==t.width&&(r.width="string"==typeof t.width?parseFloat(t.width):t.width);const s=i.get(t.field);s&&(r.sort=s);for(const i of e)if(i.getColumnState){const e=i.getColumnState(t.field);e&&Object.assign(r,e)}return r})}}applyState(e,t){if(!e.columns||0===e.columns.length)return;const i=this.columns,n=new Map(e.columns.map(e=>[e.field,e])),r=i.map(e=>{const t=n.get(e.field);if(!t)return e;const i={...e};return void 0!==t.width&&(i.width=t.width,i.__renderedWidth=t.width),void 0!==t.visible&&(i.hidden=!t.visible),i});r.sort((e,t)=>(n.get(e.field)?.order??1/0)-(n.get(t.field)?.order??1/0)),this.columns=r;const o=e.columns.filter(e=>void 0!==e.sort).sort((e,t)=>(e.sort?.priority??0)-(t.sort?.priority??0));if(o.length>0){const e=o[0];e.sort&&this.#u.setSortState({field:e.field,direction:"asc"===e.sort.direction?1:-1})}else this.#u.setSortState(null);for(const s of t)if(s.applyColumnState)for(const t of e.columns)s.applyColumnState(t.field,t)}resetState(e){this.#h=void 0,this.#u.setSortState(null),this.#s=this.#f(this.#o),this.#w();for(const t of e)if(t.applyColumnState)for(const e of this.columns)t.applyColumnState(e.field,{field:e.field,order:0,visible:!0});this.requestStateChange(e)}#v(){const e=new Map,t=this.#u.getSortState();return t&&e.set(t.field,{direction:1===t.direction?"asc":"desc",priority:0}),e}requestStateChange(e){this.#c&&clearTimeout(this.#c),this.#c=setTimeout(()=>{this.#c=void 0;const t=this.collectState(e);this.#u.emit("column-state-change",t)},100)}setColumnVisible(e,t){const i=this.columns,n=i.find(t=>t.field===e);if(!n)return!1;if(!t&&n.lockVisible)return!1;if(!t){if(0===i.filter(t=>!t.hidden&&t.field!==e).length)return!1}return!!n.hidden!=!t&&(n.hidden=!t,this.#u.emit("column-visibility",{field:e,visible:t,visibleColumns:i.filter(e=>!e.hidden).map(e=>e.field)}),this.#u.clearRowPool(),this.#u.setup(),!0)}toggleColumnVisibility(e){const t=this.columns.find(t=>t.field===e);return!!t&&this.setColumnVisible(e,!!t.hidden)}isColumnVisible(e){const t=this.columns.find(t=>t.field===e);return!!t&&!t.hidden}showAllColumns(){const e=this.columns;e.some(e=>e.hidden)&&(e.forEach(e=>e.hidden=!1),this.#u.emit("column-visibility",{visibleColumns:e.map(e=>e.field)}),this.#u.clearRowPool(),this.#u.setup())}getAllColumns(){return this.columns.map(e=>({field:e.field,header:e.header||e.field,visible:!e.hidden,lockVisible:e.lockVisible,utility:!0===e.meta?.utility}))}getColumnOrder(){return this.columns.map(e=>e.field)}setColumnOrder(e){if(!e.length)return;const t=new Map(this.columns.map(e=>[e.field,e])),i=[];for(const n of e){const e=t.get(n);e&&(i.push(e),t.delete(n))}for(const n of t.values())i.push(n);this.columns=i,this.#u.renderHeader(),this.#u.updateTemplate(),this.#u.refreshVirtualWindow()}parseLightDomColumns(e){this.#n||(this.#r=Array.from(e.querySelectorAll("tbw-grid-column")),this.#n=this.#r.length?function(e){return Array.from(e.querySelectorAll("tbw-grid-column")).map(e=>{const t=e.getAttribute("field")||"";if(!t)return null;const i=e.getAttribute("type")||void 0,n={field:t,type:i&&new Set(["number","string","date","boolean","select"]).has(i)?i:void 0,header:e.getAttribute("header")||void 0,sortable:e.hasAttribute("sortable"),editable:e.hasAttribute("editable")},r=e.getAttribute("width");if(r){const e=parseFloat(r);!isNaN(e)&&/^\d+(\.\d+)?$/.test(r.trim())?n.width=e:n.width=r}const o=e.getAttribute("minWidth")||e.getAttribute("min-width");if(o){const e=parseFloat(o);isNaN(e)||(n.minWidth=e)}e.hasAttribute("resizable")&&(n.resizable=!0),e.hasAttribute("sizable")&&(n.resizable=!0);const s=e.getAttribute("editor"),l=e.getAttribute("renderer");s&&(n.__editorName=s),l&&(n.__rendererName=l);const a=e.getAttribute("options");a&&(n.options=a.split(",").map(e=>{const[t,i]=e.includes(":")?e.split(":"):[e.trim(),e.trim()];return{value:t.trim(),label:i?.trim()||t.trim()}}));const d=e.querySelector("tbw-grid-column-view"),c=e.querySelector("tbw-grid-column-editor"),h=e.querySelector("tbw-grid-column-header");d&&(n.__viewTemplate=d),c&&(n.__editorTemplate=c),h&&(n.__headerTemplate=h);const u=globalThis.DataGridElement,g=u?.getAdapters?.()??[],p=d??e,f=g.find(e=>e.canHandle(p));if(f){const e=f.createRenderer(p);e&&(n.viewRenderer=e)}const w=c??e,m=g.find(e=>e.canHandle(w));if(m){const e=m.createEditor(w);e&&(n.editor=e)}return n}).filter(e=>!!e)}(e):[])}clearLightDomCache(){this.#n=void 0}#y=new Map;registerLightDomHandler(e,t){this.#y.set(e.toLowerCase(),t)}unregisterLightDomHandler(e){this.#y.delete(e.toLowerCase())}observeLightDOM(e){this.#d&&this.#d.disconnect();const t=new Set;let i=null;const n=()=>{i=null;for(const e of t){const t=this.#y.get(e);t?.()}t.clear()};this.#d=new MutationObserver(e=>{for(const i of e){for(const e of i.addedNodes){if(e.nodeType!==Node.ELEMENT_NODE)continue;const i=e.tagName.toLowerCase();this.#y.has(i)&&t.add(i)}if("attributes"===i.type&&i.target.nodeType===Node.ELEMENT_NODE){const e=i.target.tagName.toLowerCase();this.#y.has(e)&&t.add(e)}}t.size>0&&!i&&(i=setTimeout(n,0))}),this.#d.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["title","field","header","width","hidden","id","icon","tooltip","order"]})}onChange(e){this.#a.push(e)}notifyChange(){for(const e of this.#a)e()}dispose(){this.#d?.disconnect(),this.#a=[],this.#c&&clearTimeout(this.#c)}}function _(){if("undefined"!=typeof window&&window.location){const e=window.location.hostname;if("localhost"===e||"127.0.0.1"===e||"::1"===e)return!0}return"undefined"!=typeof process&&"production"!==process.env?.NODE_ENV}function A(e){return`<span role="checkbox" aria-checked="${e}" aria-label="${e}">${e?"&#x1F5F9;":"&#9744;"}</span>`}function k(e){if(null==e||""===e)return"";if(e instanceof Date)return isNaN(e.getTime())?"":e.toLocaleDateString();if("number"==typeof e||"string"==typeof e){const t=new Date(e);return isNaN(t.getTime())?"":t.toLocaleDateString()}return""}function T(e){if(!e)return-1;const t=e.getAttribute("data-row");if(t)return parseInt(t,10);const i=e.closest(".data-grid-row");if(!i)return-1;const n=i.parentElement;if(!n)return-1;const r=n.querySelectorAll(":scope > .data-grid-row");for(let o=0;o<r.length;o++)if(r[o]===i)return o;return-1}function L(e){e&&e.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function M(e){try{if("rtl"===getComputedStyle(e).direction)return"rtl"}catch{}try{const t=e.closest?.("[dir]")?.getAttribute("dir");if("rtl"===t)return"rtl"}catch{}return"ltr"}function I(e){return"rtl"===M(e)}function P(e,t){const i=t.renderer||t.viewRenderer;if(i)return i;if(!t.type)return;const n=e.__frameworkAdapter;if(n?.getTypeDefault){const e=n.getTypeDefault(t.type);if(e?.renderer)return e.renderer}}function H(e,t){if(t.format)return t.format;if(!t.type)return;const i=e.__frameworkAdapter;if(i?.getTypeDefault){const e=i.getTypeDefault(t.type);if(e?.format)return e.format}}const D='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function z(e){return(e.__editingCellCount??0)>0}function O(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing");e.querySelectorAll(".cell.editing").forEach(e=>e.classList.remove("editing"))}const F=document.createElement("template");F.innerHTML='<div class="cell" role="gridcell" part="cell"></div>';const q=document.createElement("template");function N(){return F.content.firstElementChild.cloneNode(!0)}function G(){return q.content.firstElementChild.cloneNode(!0)}function B(e){e.__cellDisplayCache=void 0,e.__cellCacheEpoch=void 0,e.__hasSpecialColumns=void 0}function V(e,t,i,n){const r=t.children,o=e._visibleColumns,s=o.length,l=r.length,a=s<l?s:l,d=e._focusRow,c=e._focusCol,h=e._hasAfterCellRenderHook?.()??!1;let u=e.__hasSpecialColumns;if(void 0===u){u=!1;const t=e.__frameworkAdapter;for(let e=0;e<s;e++){const i=o[e];if(i.__viewTemplate||i.__compiledView||i.renderer||i.viewRenderer||i.externalView||i.format||"date"===i.type||"boolean"===i.type||i.type&&t?.getTypeDefault?.(i.type)?.renderer||i.type&&t?.getTypeDefault?.(i.type)?.format){u=!0;break}}e.__hasSpecialColumns=u}const g=String(n);if(u){for(let s=0;s<a;s++){if(o[s].externalView){if(!r[s].querySelector("[data-external-view]"))return void $(e,t,i,n)}}for(let s=0;s<a;s++){const l=o[s],a=r[s];a.getAttribute("data-row")!==g&&a.setAttribute("data-row",g);const u=a.classList.contains("editing");if(!u){const e=d===n&&c===s;e!==a.classList.contains("cell-focus")&&(a.classList.toggle("cell-focus",e),a.setAttribute("aria-selected",String(e)))}const f=l.cellClass;if(f){const e=a.getAttribute("data-dynamic-classes");e&&e.split(" ").forEach(e=>e&&a.classList.remove(e));try{const e=f(i[l.field],i,l);if(e&&e.length>0){const t=e.filter(e=>e&&"string"==typeof e);t.forEach(e=>a.classList.add(e)),a.setAttribute("data-dynamic-classes",t.join(" "))}else a.removeAttribute("data-dynamic-classes")}catch(p){console.warn(`[tbw-grid] cellClass callback error for column '${l.field}':`,p),a.removeAttribute("data-dynamic-classes")}}if(u)continue;const w=P(e,l);if(w){const r=i[l.field],o=w({row:i,value:r,field:l.field,column:l,cellEl:a});"string"==typeof o?(e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=y(o)):o instanceof Node?o.parentElement!==a&&(e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML="",a.appendChild(o)):null==o&&(e.__frameworkAdapter?.releaseCell?.(a),a.textContent=null==r?"":String(r)),h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:r,cellElement:a,rowElement:t});continue}if(l.__compiledView){const r=i[l.field],o=l.__compiledView({row:i,value:r,field:l.field,column:l});l.__compiledView.__blocked?a.textContent="":(a.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=y(o),E(a)),h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:r,cellElement:a,rowElement:t});continue}if(l.__viewTemplate){const r=i[l.field],o=l.__viewTemplate.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(o)?a.textContent="":(a.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(a),a.innerHTML=y(C(o,{row:i,value:r})),E(a)),h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:r,cellElement:a,rowElement:t});continue}if(l.externalView)continue;const m=i[l.field];let b;const v=H(e,l);if(v){try{const e=v(m,i);b=null==e?"":String(e)}catch(p){console.warn(`[tbw-grid] Format error in column '${l.field}':`,p),b=null==m?"":String(m)}a.textContent=b}else"date"===l.type?(b=k(m),a.textContent=b):"boolean"===l.type?a.innerHTML=A(!!m):(b=null==m?"":String(m),a.textContent=b);h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:s,value:m,cellElement:a,rowElement:t})}}else for(let f=0;f<a;f++){const s=r[f];if(s.classList.contains("editing"))continue;s.firstElementChild&&e.__frameworkAdapter?.releaseCell?.(s);const l=o[f],a=i[l.field];s.textContent=null==a?"":String(a),s.getAttribute("data-row")!==g&&s.setAttribute("data-row",g);const u=d===n&&c===f;u!==s.classList.contains("cell-focus")&&(s.classList.toggle("cell-focus",u),s.setAttribute("aria-selected",String(u))),h&&e._afterCellRender?.({row:i,rowIndex:n,column:l,colIndex:f,value:a,cellElement:s,rowElement:t})}}function $(e,t,i,n){t.classList.remove("tbw-row-loading"),t.removeAttribute("aria-busy");const r=e.__frameworkAdapter;if(r?.releaseCell){const e=t.children;for(let t=e.length-1;t>=0;t--)r.releaseCell(e[t])}t.innerHTML="";const o=e._visibleColumns,s=o.length,l=e._focusRow,a=e._focusCol,d=e,c=e._hasAfterCellRenderHook?.()??!1,h=document.createDocumentFragment();for(let g=0;g<s;g++){const r=o[g],s=N();s.setAttribute("aria-colindex",String(g+1)),s.setAttribute("data-col",String(g)),s.setAttribute("data-row",String(n)),s.setAttribute("data-field",r.field),s.setAttribute("data-header",r.header??r.field),r.type&&s.setAttribute("data-type",r.type);let p=i[r.field];const f=H(e,r);if(f)try{p=f(p,i)}catch(u){console.warn(`[tbw-grid] Format error in column '${r.field}':`,u)}const w=r.__compiledView,m=r.__viewTemplate,b=P(e,r),v=r.externalView;let x=!1;if(b){const e=b({row:i,value:p,field:r.field,column:r,cellEl:s});"string"==typeof e?(s.innerHTML=y(e),x=!0):e instanceof Node?e.parentElement!==s&&(s.textContent="",s.appendChild(e)):null==e&&(s.textContent=null==p?"":String(p))}else if(v){const e=v,t=document.createElement("div");t.setAttribute("data-external-view",""),t.setAttribute("data-field",r.field),s.appendChild(t);const n={row:i,value:p,field:r.field,column:r};if(e.mount)try{e.mount({placeholder:t,context:n,spec:e})}catch(u){console.warn(`[tbw-grid] External view mount error for column '${r.field}':`,u)}else queueMicrotask(()=>{try{d.dispatchEvent(new CustomEvent("mount-external-view",{bubbles:!0,composed:!0,detail:{placeholder:t,spec:e,context:n}}))}catch(u){console.warn(`[tbw-grid] External view event dispatch error for column '${r.field}':`,u)}});t.setAttribute("data-mounted","")}else if(w){const e=w({row:i,value:p,field:r.field,column:r}),t=w.__blocked;s.innerHTML=t?"":y(e),x=!0,t&&(s.textContent="",s.setAttribute("data-blocked-template",""))}else if(m){const e=m.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(e)?(s.textContent="",s.setAttribute("data-blocked-template","")):(s.innerHTML=y(C(e,{row:i,value:p})),x=!0)}else f?s.textContent=null==p?"":String(p):"date"===r.type?s.textContent=k(p):"boolean"===r.type?s.innerHTML=A(!!p):s.textContent=null==p?"":String(p);if(x){E(s);const e=s.textContent||"";/Proxy|Reflect\.ownKeys/.test(e)&&(s.textContent=e.replace(/Proxy|Reflect\.ownKeys/g,"").trim(),/Proxy|Reflect\.ownKeys/.test(s.textContent||"")&&(s.textContent=""))}s.hasAttribute("data-blocked-template")&&(s.textContent||"").trim().length&&(s.textContent=""),r.editable?s.tabIndex=0:"boolean"===r.type&&(s.hasAttribute("tabindex")||(s.tabIndex=0)),l===n&&a===g?(s.classList.add("cell-focus"),s.setAttribute("aria-selected","true")):s.setAttribute("aria-selected","false");const R=r.cellClass;if(R)try{const e=R(i[r.field],i,r);if(e&&e.length>0){const t=e.filter(e=>e&&"string"==typeof e);t.forEach(e=>s.classList.add(e)),s.setAttribute("data-dynamic-classes",t.join(" "))}}catch(u){console.warn(`[tbw-grid] cellClass callback error for column '${r.field}':`,u)}c&&e._afterCellRender?.({row:i,rowIndex:n,column:r,colIndex:g,value:p,cellElement:s,rowElement:t}),h.appendChild(s)}t.appendChild(h)}function W(e,t,i){if(t.target?.closest(".resize-handle"))return;const n=T(i.querySelector(".cell[data-row]"));if(n<0)return;const r=e._rows[n];if(!r)return;if(e._dispatchRowClick?.(t,n,r,i))return;const o=t.target?.closest(".cell[data-col]");if(o){const i=Number(o.getAttribute("data-col"));if(!isNaN(i)){if(e._dispatchCellClick?.(t,n,i,o))return;const r=e._focusRow!==n||e._focusCol!==i;if(e._focusRow=n,e._focusCol=i,o.classList.contains("editing")){r&&(L(e._bodyEl??e),o.classList.add("cell-focus"));const t=o.querySelector(D);try{t?.focus({preventScroll:!0})}catch{}return}K(e)}}}function K(e,t){if(e._virtualization?.enabled){const{rowHeight:t,container:i,viewportEl:n}=e._virtualization,r=i,o=n?.clientHeight??r?.clientHeight??0;if(r&&o>0){const i=e._focusRow*t;i<r.scrollTop?r.scrollTop=i:i+t>r.scrollTop+o&&(r.scrollTop=i-o+t)}}const i=void 0!==e._activeEditRows&&-1!==e._activeEditRows;i||e.refreshVirtualWindow(!1),L(e._bodyEl),Array.from(e._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(e=>{e.setAttribute("aria-selected","false")});const n=e._focusRow,r=e._virtualization.start??0,o=e._virtualization.end??e._rows.length;if(n>=r&&n<o){const o=e._bodyEl.querySelectorAll(".data-grid-row")[n-r];let s=o?.children[e._focusCol];if(s&&s.classList?.contains("cell")||(s=o?.querySelector(`.cell[data-col="${e._focusCol}"]`)??o?.querySelector(".cell[data-col]")),s){s.classList.add("cell-focus"),s.setAttribute("aria-selected","true");const n=e.querySelector(".tbw-scroll-area");if(n&&s&&(!i||t?.forceHorizontalScroll))if(t?.forceScrollLeft)n.scrollLeft=0;else if(t?.forceScrollRight)n.scrollLeft=n.scrollWidth-n.clientWidth;else{const t=e._getHorizontalScrollOffsets?.(o??void 0,s)??{left:0,right:0};if(!t.skipScroll){const e=s.getBoundingClientRect(),i=n.getBoundingClientRect(),r=e.left-i.left+n.scrollLeft,o=r+e.width,l=n.scrollLeft+t.left,a=n.scrollLeft+n.clientWidth-t.right;r<l?n.scrollLeft=r-t.left:o>a&&(n.scrollLeft=o-n.clientWidth+t.right)}}if(i&&s.classList.contains("editing")){const e=s.querySelector(D);if(e&&document.activeElement!==e)try{e.focus({preventScroll:!0})}catch{}}else if(i&&!s.contains(document.activeElement)){s.hasAttribute("tabindex")||s.setAttribute("tabindex","-1");try{s.focus({preventScroll:!0})}catch{}}else if(!i){const t=e;document.activeElement!==t&&t.focus({preventScroll:!0})}}}}q.innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const U=new WeakMap;function j(e,t){const i=T(t),n=function(e){if(!e)return-1;const t=e.getAttribute("data-col");return t?parseInt(t,10):-1}(t);if(i<0||n<0)return;e._focusRow=i,e._focusCol=n,L(e._bodyEl),t.classList.add("cell-focus"),t.setAttribute("aria-selected","true");const r=t.closest("tbw-grid");r&&document.activeElement!==r&&r.focus({preventScroll:!0})}function Y(e,t,i,n){let r=null;const o=i.composedPath?.();if(r=o&&o.length>0?o[0]:i.target,r&&!t.contains(r)){const e=document.elementFromPoint(i.clientX,i.clientY);e&&(r=e)}const s=r?.closest?.("[data-col]"),l=r?.closest?.(".data-grid-row"),a=r?.closest?.(".header-row");let d,c,h,u,g,p;return s&&(d=parseInt(s.getAttribute("data-row")??"-1",10),c=parseInt(s.getAttribute("data-col")??"-1",10),d>=0&&c>=0&&(h=e._rows[d],p=e._visibleColumns[c],u=p?.field,g=h&&u?h[u]:void 0)),{type:n,row:h,rowIndex:void 0!==d&&d>=0?d:void 0,colIndex:void 0!==c&&c>=0?c:void 0,field:u,value:g,column:p,originalEvent:i,cellElement:s??void 0,rowElement:l??void 0,isHeader:!!a,cell:void 0!==d&&void 0!==c&&d>=0&&c>=0?{row:d,col:c}:void 0}}function X(e,t,i,n){t.addEventListener("keydown",t=>function(e,t){if(e._dispatchKeyDown?.(t))return;const i=e._rows.length-1,n=e._visibleColumns.length-1,r=void 0!==e._activeEditRows&&-1!==e._activeEditRows,o=e._visibleColumns[e._focusCol],s=o?.type,l=t.composedPath?.()??[],a=l.length?l[0]:t.target,d=e=>{if(!e)return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t||!!e.isContentEditable};if((!d(a)||"Home"!==t.key&&"End"!==t.key)&&!(d(a)&&("ArrowUp"===t.key||"ArrowDown"===t.key)&&"INPUT"===a.tagName&&"number"===a.type||d(a)&&("ArrowLeft"===t.key||"ArrowRight"===t.key)||d(a)&&("Enter"===t.key||"Escape"===t.key)||r&&"select"===s&&("ArrowDown"===t.key||"ArrowUp"===t.key))){switch(t.key){case"Tab":return t.preventDefault(),t.shiftKey?e._focusCol>0?e._focusCol-=1:e._focusRow>0&&("function"==typeof e.commitActiveRowEdit&&e._activeEditRows===e._focusRow&&e.commitActiveRowEdit(),e._focusRow-=1,e._focusCol=n):e._focusCol<n?e._focusCol+=1:("function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow<i&&(e._focusRow+=1,e._focusCol=0)),void K(e);case"ArrowDown":r&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=Math.min(i,e._focusRow+1),t.preventDefault();break;case"ArrowUp":r&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=Math.max(0,e._focusRow-1),t.preventDefault();break;case"ArrowRight":{const i=I(e);e._focusCol=i?Math.max(0,e._focusCol-1):Math.min(n,e._focusCol+1),t.preventDefault();break}case"ArrowLeft":{const i=I(e);e._focusCol=i?Math.min(n,e._focusCol+1):Math.max(0,e._focusCol-1),t.preventDefault();break}case"Home":return t.ctrlKey||t.metaKey?(r&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=0,e._focusCol=0):e._focusCol=0,t.preventDefault(),void K(e,{forceScrollLeft:!0});case"End":return t.ctrlKey||t.metaKey?(r&&"function"==typeof e.commitActiveRowEdit&&e.commitActiveRowEdit(),e._focusRow=i,e._focusCol=n):e._focusCol=n,t.preventDefault(),void K(e,{forceScrollRight:!0});case"PageDown":e._focusRow=Math.min(i,e._focusRow+20),t.preventDefault();break;case"PageUp":e._focusRow=Math.max(0,e._focusRow-20),t.preventDefault();break;case"Enter":{const i=e._focusRow,n=e._focusCol,r=e._visibleColumns[n],o=e._rows[i],s=r?.field??"",l=s&&o?o[s]:void 0,a=e.querySelector(`[data-row="${i}"][data-col="${n}"]`),d=new CustomEvent("cell-activate",{cancelable:!0,detail:{rowIndex:i,colIndex:n,column:r,field:s,value:l,row:o,cellEl:a,trigger:"keyboard",originalEvent:t}});e.dispatchEvent(d);const c=new CustomEvent("activate-cell",{cancelable:!0,detail:{row:i,col:n}});if(e.dispatchEvent(c),d.defaultPrevented||c.defaultPrevented)return void t.preventDefault();break}default:return}K(e)}}(e,t),{signal:n}),i.addEventListener("mousedown",t=>function(e,t,i){const n=Y(e,t,i,"mousedown");e._dispatchCellMouseDown?.(n)&&U.set(e,!0)}(e,i,t),{signal:n}),document.addEventListener("mousemove",t=>function(e,t,i){if(!U.get(e))return;const n=Y(e,t,i,"mousemove");e._dispatchCellMouseMove?.(n)}(e,i,t),{signal:n}),document.addEventListener("mouseup",t=>function(e,t,i){if(!U.get(e))return;const n=Y(e,t,i,"mouseup");e._dispatchCellMouseUp?.(n),U.set(e,!1)}(e,i,t),{signal:n})}function Z(e,t){return null==e&&null==t?0:null==e?-1:null==t||e>t?1:e<t?-1:0}function Q(e,t,i){const n=i.find(e=>e.field===t.field),r=n?.sortComparator??Z,{field:o,direction:s}=t;return[...e].sort((e,t)=>r(e[o],t[o],e,t)*s)}function J(e,t,i,n){e._rows=t,e.__rowRenderEpoch++,e._rowPool.forEach(e=>e.__epoch=-1),le(e),e.refreshVirtualWindow(!0),e.dispatchEvent(new CustomEvent("sort-change",{detail:{field:i.field,direction:n}})),e.requestStateChange?.()}function ee(e,t){if(e._sortState&&e._sortState.field===t.field)if(1===e._sortState.direction)te(e,t,-1);else{e._sortState=null,e.__rowRenderEpoch++,e._rowPool.forEach(e=>e.__epoch=-1),e._rows=e.__originalOrder.slice(),le(e);const i=e._headerRowEl?.querySelectorAll('[role="columnheader"].sortable');i?.forEach(t=>{t.getAttribute("aria-sort")&&("ascending"!==t.getAttribute("aria-sort")&&"descending"!==t.getAttribute("aria-sort")||e._sortState)||t.setAttribute("aria-sort","none")}),e.refreshVirtualWindow(!0),e.dispatchEvent(new CustomEvent("sort-change",{detail:{field:t.field,direction:0}})),e.requestStateChange?.()}else e._sortState||(e.__originalOrder=e._rows.slice()),te(e,t,1)}function te(e,t,i){e._sortState={field:t.field,direction:i};const n={field:t.field,direction:i},r=e._columns,o=(e.effectiveConfig?.sortHandler??Q)(e._rows,n,r);o&&"function"==typeof o.then?o.then(n=>{J(e,n,t,i)}):J(e,o,t,i)}function ie(e,t){return!1!==e.effectiveConfig?.sortable&&!0===t.sortable}function ne(e,t){return!1!==e.effectiveConfig?.resizable&&!1!==t.resizable}function re(e,t){const i=document.createElement("span");s(i,"sort-indicator");const n=e._sortState?.field===t.field?e._sortState.direction:0,o={...r,...e.icons};return function(e,t){"string"==typeof t?e.textContent=t:t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}(i,1===n?o.sortAsc:-1===n?o.sortDesc:o.sortNone),i}function oe(e,t,i){const n=document.createElement("div");return n.className="resize-handle",n.setAttribute("aria-hidden","true"),n.addEventListener("mousedown",n=>{n.stopPropagation(),n.preventDefault(),e._resizeController.start(n,t,i)}),n.addEventListener("dblclick",i=>{i.stopPropagation(),i.preventDefault(),e._resizeController.resetColumn(t)}),n}function se(e,t,i,n){n.classList.add("sortable"),n.tabIndex=0;const r=e._sortState?.field===t.field?e._sortState.direction:0;n.setAttribute("aria-sort",0===r?"none":1===r?"ascending":"descending"),n.addEventListener("click",i=>{e._resizeController?.isResizing||e._dispatchHeaderClick?.(i,t,n)||ee(e,t)}),n.addEventListener("keydown",i=>{if("Enter"===i.key||" "===i.key){if(i.preventDefault(),e._dispatchHeaderClick?.(i,t,n))return;ee(e,t)}})}function le(e){e._headerRowEl=e.findHeaderRow();const t=e._headerRowEl;t&&(t.innerHTML="",e._visibleColumns.forEach((i,n)=>{const r=document.createElement("div");r.className="cell",s(r,"header-cell"),r.setAttribute("role","columnheader"),r.setAttribute("aria-colindex",String(n+1)),r.setAttribute("data-field",i.field),r.setAttribute("data-col",String(n)),i.type&&r.setAttribute("data-type",i.type);const o=i.header??i.field,l=e._sortState?.field===i.field?e._sortState.direction:0,a=1===l?"asc":-1===l?"desc":null;if(i.headerRenderer){const t={column:i,value:o,sortState:a,filterActive:!1,cellEl:r,renderSortIcon:()=>ie(e,i)?re(e,i):null,renderFilterButton:()=>null},s=i.headerRenderer(t);!function(e,t){if(null!=t)if("string"==typeof t){const i=document.createElement("span");for(i.innerHTML=y(t);i.firstChild;)e.appendChild(i.firstChild)}else t instanceof Node&&e.appendChild(t)}(r,s),ie(e,i)&&se(e,i,0,r),ne(e,i)&&(r.classList.add("resizable"),r.appendChild(oe(e,n,r)))}else if(i.headerLabelRenderer){const t={column:i,value:o},s=i.headerLabelRenderer(t),l=document.createElement("span");null==s?l.textContent=o:"string"==typeof s?l.innerHTML=y(s):s instanceof Node&&l.appendChild(s),r.appendChild(l),ie(e,i)&&(se(e,i,0,r),r.appendChild(re(e,i))),ne(e,i)&&(r.classList.add("resizable"),r.appendChild(oe(e,n,r)))}else if(i.__headerTemplate)Array.from(i.__headerTemplate.childNodes).forEach(e=>r.appendChild(e.cloneNode(!0))),ie(e,i)&&(se(e,i,0,r),r.appendChild(re(e,i))),ne(e,i)&&(r.classList.add("resizable"),r.appendChild(oe(e,n,r)));else{const t=document.createElement("span");t.textContent=o,r.appendChild(t),ie(e,i)&&(se(e,i,0,r),r.appendChild(re(e,i))),ne(e,i)&&(r.classList.add("resizable"),r.appendChild(oe(e,n,r)))}t.appendChild(r)}),t.querySelectorAll(".cell.sortable").forEach(e=>{e.getAttribute("aria-sort")||e.setAttribute("aria-sort","none")}),t.children.length>0?(t.setAttribute("role","row"),t.setAttribute("aria-rowindex","1")):(t.removeAttribute("role"),t.removeAttribute("aria-rowindex")))}const ae="function"==typeof requestIdleCallback;function de(e){ae?cancelIdleCallback(e):clearTimeout(e)}function ce(e,t){if(t){const i=t({size:e});if("string"==typeof i){const e=document.createElement("div");return e.innerHTML=i,e}return i}return function(e){const t=document.createElement("div");return t.className=`tbw-spinner tbw-spinner--${e}`,t.setAttribute("role","progressbar"),t.setAttribute("aria-label","Loading"),t}(e)}var he=(e=>(e[e.STYLE=1]="STYLE",e[e.VIRTUALIZATION=2]="VIRTUALIZATION",e[e.HEADER=3]="HEADER",e[e.ROWS=4]="ROWS",e[e.COLUMNS=5]="COLUMNS",e[e.FULL=6]="FULL",e))(he||{});class ue{#u;#C=0;#x=0;#E=null;#R=null;#S=null;#_=!1;constructor(e){this.#u=e}requestPhase(e,t){e>this.#C&&(this.#C=e),0===this.#x&&(this.#A(),this.#x=requestAnimationFrame(()=>this.#k()))}whenReady(){return this.#E?this.#E:Promise.resolve()}setInitialReadyResolver(e){this.#S=e}cancel(){0!==this.#x&&(cancelAnimationFrame(this.#x),this.#x=0),this.#C=0,this.#R&&(this.#R(),this.#R=null,this.#E=null)}get isPending(){return 0!==this.#C}get pendingPhase(){return this.#C}#A(){this.#E||(this.#E=new Promise(e=>{this.#R=e}))}#k(){if(this.#x=0,!this.#u.isConnected())return this.#C=0,void(this.#R&&(this.#R(),this.#R=null,this.#E=null));const e=this.#C;this.#C=0,e>=5&&this.#u.mergeConfig(),e>=4&&this.#u.processRows(),e>=5&&(this.#u.processColumns(),this.#u.updateTemplate()),e>=3&&this.#u.renderHeader(),e>=2&&this.#u.renderVirtualWindow(),e>=1&&this.#u.afterRender(),!this.#_&&this.#S&&(this.#_=!0,this.#S()),this.#R&&(this.#R(),this.#R=null,this.#E=null)}}function ge(e){let t=null,i=null,n=null,r=null;const o=n=>{if(!t)return;const r=n.clientX-t.startX,o=Math.max(40,t.startWidth+r),s=e._visibleColumns[t.colIndex];s.width=o,s.__userResized=!0,s.__renderedWidth=o,null==i&&(i=requestAnimationFrame(()=>{i=null,e.updateTemplate?.()})),e.dispatchEvent(new CustomEvent("column-resize",{detail:{field:s.field,width:o}}))};let s=!1;const l=()=>{const i=null!==t;i&&(s=!0,requestAnimationFrame(()=>{s=!1})),window.removeEventListener("mousemove",o),window.removeEventListener("mouseup",l),null!==n&&(document.documentElement.style.cursor=n,n=null),null!==r&&(document.body.style.userSelect=r,r=null),t=null,i&&e.requestStateChange&&e.requestStateChange()};return{get isResizing(){return null!==t||s},start(i,s,a){i.preventDefault();const d=e._visibleColumns[s],c="number"==typeof d?.width?d.width:void 0,h=d?.__renderedWidth??c??a.getBoundingClientRect().width;t={startX:i.clientX,colIndex:s,startWidth:h},window.addEventListener("mousemove",o),window.addEventListener("mouseup",l),null===n&&(n=document.documentElement.style.cursor),document.documentElement.style.cursor="e-resize",null===r&&(r=document.body.style.userSelect),document.body.style.userSelect="none"},resetColumn(t){const i=e._visibleColumns[t];i&&(i.__userResized=!1,i.__renderedWidth=void 0,i.width=i.__originalWidth,e.updateTemplate?.(),e.requestStateChange?.(),e.dispatchEvent(new CustomEvent("column-resize-reset",{detail:{field:i.field,width:i.width}})))},dispose(){l()}}}const pe="data-animating",fe={change:"--tbw-row-change-duration",insert:"--tbw-row-insert-duration",remove:"--tbw-row-remove-duration"},we={change:500,insert:300,remove:200};function me(e,t){const i=fe[t],n=getComputedStyle(e).getPropertyValue(i);if(n){const e=function(e){const t=e.trim().toLowerCase();return t.endsWith("ms")?parseFloat(t):t.endsWith("s")?1e3*parseFloat(t):parseFloat(t)}(n);if(!isNaN(e)&&e>0)return e}return we[t]}function be(e,t,i){if(t<0)return Promise.resolve(!1);const n=e.findRenderedRowElement?.(t);return n?new Promise(e=>{!function(e,t,i){e.removeAttribute(pe),e.offsetWidth,e.setAttribute(pe,t);const n=me(e,t);setTimeout(()=>{"remove"!==t&&e.removeAttribute(pe),i?.()},n)}(n,i,()=>e(!0))}):Promise.resolve(!1)}function ve(e,t,i){const n=document.createElement(e);if(t)for(const r in t){const e=t[r];null!=e&&n.setAttribute(r,e)}return n}function ye(e,t){const i=document.createElement("div");if(e&&(i.className=e),t)for(const n in t){const e=t[n];null!=e&&i.setAttribute(n,e)}return i}function Ce(e,t,i){const n=document.createElement("button");if(e&&(n.className=e),t)for(const r in t){const e=t[r];null!=e&&n.setAttribute(r,e)}return n}const xe=document.createElement("template");function Ee(){return xe.content.cloneNode(!0)}function Re(e){const t=document.createDocumentFragment(),i=ye(e.hasShell?"tbw-grid-root has-shell":"tbw-grid-root");if(e.hasShell&&e.shellHeader&&e.shellBody)i.appendChild(e.shellHeader),i.appendChild(e.shellBody);else{const e=ye("tbw-grid-content");e.appendChild(Ee()),i.appendChild(e)}return t.appendChild(i),t}function Se(e){return e?"string"==typeof e?e:e.outerHTML:""}function _e(e){return!!e?.header?.title||(!!e?.header?.toolbarContents?.length||(!!e?.toolPanels?.length||(!!e?.headerContents?.length||(!!e?.header?.lightDomContent?.length||!!e?.header?.hasToolButtonsContainer))))}function Ae(e,t){const i=e.querySelector("tbw-grid-header");if(!i)return;if(!t.lightDomTitle){const e=i.getAttribute("title");e&&(t.lightDomTitle=e)}const n=i.querySelectorAll("tbw-grid-header-content");n.length>0&&0===t.lightDomHeaderContent.length&&(t.lightDomHeaderContent=Array.from(n)),i.style.display="none"}function ke(e,t,i){const n=e.querySelector(":scope > tbw-grid-tool-buttons");if(!n)return;t.hasToolButtonsContainer=!0;const r="light-dom-toolbar-content";if(t.lightDomToolbarContentIds.has(r))return;const o={id:r,order:0,render:e=>{for(;n.firstChild;)e.appendChild(n.firstChild);return()=>{for(;e.firstChild;)n.appendChild(e.firstChild)}}};t.toolbarContents.set(r,o),t.lightDomToolbarContentIds.add(r),n.style.display="none"}function Te(e,t,i){e.querySelectorAll(":scope > tbw-grid-tool-panel").forEach(e=>{const n=e,r=n.getAttribute("id"),o=n.getAttribute("title");if(!r||!o)return void console.warn(`[parseLightDomToolPanels] Tool panel missing required id or title attribute: id="${r??""}", title="${o??""}"`);const s=n.getAttribute("icon")??void 0,l=n.getAttribute("tooltip")??void 0,a=parseInt(n.getAttribute("order")??"100",10);let d;const c=i?.(n);if(c)d=c;else{const e=n.innerHTML.trim();d=t=>{const i=document.createElement("div");return i.innerHTML=e,t.appendChild(i),()=>i.remove()}}const h=t.toolPanels.get(r);if(h){if(c){h.render=d,h.order=a,h.icon=s,h.tooltip=l;const e=t.panelCleanups.get(r);e&&(e(),t.panelCleanups.delete(r))}return}const u={id:r,title:o,icon:s,tooltip:l,order:a,render:d};t.toolPanels.set(r,u),t.lightDomToolPanelIds.add(r),n.style.display="none"})}function Le(e,t,i){const n=t?.header?.toolbarContents??[],r=[...i.toolbarContents.values()],o=new Set(n.map(e=>e.id)),s=[...n];for(const l of r)o.has(l.id)||s.push(l);for(const l of s){if(i.toolbarContentCleanups.has(l.id))continue;if(!l.render)continue;const t=e.querySelector(`[data-toolbar-content="${l.id}"]`);if(!t)continue;const n=l.render(t);n&&i.toolbarContentCleanups.set(l.id,n)}}function Me(e,t){const i=t.lightDomHeaderContent.length>0&&!t.lightDomContentMoved,n=t.headerContents.size>0;if(!i&&!n)return;const r=e.querySelector(".tbw-shell-content");if(!r)return;if(i){for(const e of t.lightDomHeaderContent)e.style.display="",r.appendChild(e);t.lightDomContentMoved=!0}const o=[...t.headerContents.values()].sort((e,t)=>(e.order??100)-(t.order??100));for(const s of o){const e=t.headerContentCleanups.get(s.id);e&&(e(),t.headerContentCleanups.delete(s.id));let i=r.querySelector(`[data-header-content="${s.id}"]`);i||(i=document.createElement("div"),i.setAttribute("data-header-content",s.id),r.appendChild(i));const n=s.render(i);n&&t.headerContentCleanups.set(s.id,n)}}function Ie(e,t){const i=e.querySelector("[data-panel-toggle]");i&&(i.classList.toggle("active",t.isPanelOpen),i.setAttribute("aria-pressed",String(t.isPanelOpen)))}function Pe(e,t){const i=e.querySelector(".tbw-tool-panel");i&&(i.classList.toggle("open",t.isPanelOpen),t.isPanelOpen||(i.style.width=""))}function He(e){for(const t of e.toolbarContentCleanups.values())t();e.toolbarContentCleanups.clear()}function De(e,t){let i=!1;const n={get isInitialized(){return i},setInitialized(e){i=e},get isPanelOpen(){return e.isPanelOpen},get activePanel(){return e.isPanelOpen&&e.expandedSections.size>0?[...e.expandedSections][0]:null},get expandedSections(){return[...e.expandedSections]},openToolPanel(){if(e.isPanelOpen)return;if(0===e.toolPanels.size)return void console.warn("[tbw-grid] No tool panels registered");if(e.isPanelOpen=!0,0===e.expandedSections.size&&e.toolPanels.size>0){const t=[...e.toolPanels.values()].sort((e,t)=>(e.order??100)-(t.order??100))[0];t&&e.expandedSections.add(t.id)}const i=t.getShadow();Ie(i,e),Pe(i,e),function(e,t,i){if(!t.isPanelOpen)return;const n=Se(i?.expand??r.expand),o=Se(i?.collapse??r.collapse);for(const[r,s]of t.toolPanels){const i=t.expandedSections.has(r),l=e.querySelector(`[data-section="${r}"]`),a=l?.querySelector(".tbw-accordion-content");if(!l||!a)continue;l.classList.toggle("expanded",i);const d=l.querySelector(".tbw-accordion-header");d&&d.setAttribute("aria-expanded",String(i));const c=l.querySelector(".tbw-accordion-chevron");if(c&&(c.innerHTML=i?o:n),i){if(0===a.children.length){const e=s.render(a);e&&t.panelCleanups.set(r,e)}}else{const e=t.panelCleanups.get(r);e&&(e(),t.panelCleanups.delete(r)),a.innerHTML=""}}}(i,e,t.getAccordionIcons()),t.emit("tool-panel-open",{sections:n.expandedSections})},closeToolPanel(){if(!e.isPanelOpen)return;for(const t of e.panelCleanups.values())t();e.panelCleanups.clear();for(const t of e.toolPanels.values())t.onClose?.();e.isPanelOpen=!1;const i=t.getShadow();Ie(i,e),Pe(i,e),t.emit("tool-panel-close",{})},toggleToolPanel(){e.isPanelOpen?n.closeToolPanel():n.openToolPanel()},toggleToolPanelSection(i){const n=e.toolPanels.get(i);if(!n)return void console.warn(`[tbw-grid] Tool panel section "${i}" not found`);if(1===e.toolPanels.size)return;const r=t.getShadow(),o=e.expandedSections.has(i);if(o){const t=e.panelCleanups.get(i);t&&(t(),e.panelCleanups.delete(i)),n.onClose?.(),e.expandedSections.delete(i),ze(r,i,!1)}else{for(const[t,n]of e.toolPanels)if(t!==i&&e.expandedSections.has(t)){const i=e.panelCleanups.get(t);i&&(i(),e.panelCleanups.delete(t)),n.onClose?.(),e.expandedSections.delete(t),ze(r,t,!1);const o=r.querySelector(`[data-section="${t}"] .tbw-accordion-content`);o&&(o.innerHTML="")}e.expandedSections.add(i),ze(r,i,!0),function(e,t,i){const n=t.toolPanels.get(i);if(!n?.render)return;const r=e.querySelector(`[data-section="${i}"] .tbw-accordion-content`);if(!r)return;const o=n.render(r);o&&t.panelCleanups.set(i,o)}(r,e,i)}t.emit("tool-panel-section-toggle",{id:i,expanded:!o})},getToolPanels:()=>[...e.toolPanels.values()],registerToolPanel(n){e.toolPanels.has(n.id)?console.warn(`[tbw-grid] Tool panel "${n.id}" already registered`):(e.toolPanels.set(n.id,n),i&&t.refreshShellHeader())},unregisterToolPanel(n){if(e.expandedSections.has(n)){const t=e.panelCleanups.get(n);t&&(t(),e.panelCleanups.delete(n)),e.expandedSections.delete(n)}e.toolPanels.delete(n),i&&t.refreshShellHeader()},getHeaderContents:()=>[...e.headerContents.values()],registerHeaderContent(n){e.headerContents.has(n.id)?console.warn(`[tbw-grid] Header content "${n.id}" already registered`):(e.headerContents.set(n.id,n),i&&Me(t.getShadow(),e))},unregisterHeaderContent(i){const n=e.headerContentCleanups.get(i);n&&(n(),e.headerContentCleanups.delete(i));const r=e.headerContents.get(i);r?.onDestroy?.(),e.headerContents.delete(i);const o=t.getShadow().querySelector(`[data-header-content="${i}"]`);o?.remove()},getToolbarContents:()=>[...e.toolbarContents.values()].sort((e,t)=>(e.order??0)-(t.order??0)),registerToolbarContent(n){e.toolbarContents.has(n.id)?console.warn(`[tbw-grid] Toolbar content "${n.id}" already registered`):(e.toolbarContents.set(n.id,n),i&&t.refreshShellHeader())},unregisterToolbarContent(n){const r=e.toolbarContentCleanups.get(n);r&&(r(),e.toolbarContentCleanups.delete(n));const o=e.toolbarContents.get(n);o?.onDestroy&&o.onDestroy(),e.toolbarContents.delete(n),i&&t.refreshShellHeader()}};return n}function ze(e,t,i){const n=e.querySelector(`[data-section="${t}"]`);n&&n.classList.toggle("expanded",i)}function Oe(e,t,i,n){const o=_e(t),s=[],l=["tbw-grid-header","tbw-grid-tool-buttons","tbw-grid-tool-panel","tbw-grid-column","tbw-grid-detail","tbw-grid-responsive-card"];for(const r of l){e.querySelectorAll(`:scope > ${r}`).forEach(e=>s.push(e))}e.replaceChildren();for(const r of s)e.appendChild(r);if(o){const o=Se(n?.toolPanel??r.toolPanel),s=Se(n?.expand??r.expand),l=Se(n?.collapse??r.collapse),a=[...t?.header?.toolbarContents??[]].sort((e,t)=>(e.order??0)-(t.order??0)),d=[...t?.toolPanels??[]].sort((e,t)=>(e.order??100)-(t.order??100)),c={title:t?.header?.title??void 0,hasPanels:d.length>0,isPanelOpen:i.isPanelOpen,toolPanelIcon:o,configButtons:a.map(e=>({id:e.id,hasElement:!1,hasRender:!!e.render})),apiButtons:[]},h={position:t?.toolPanel?.position??"right",isPanelOpen:i.isPanelOpen,expandIcon:s,collapseIcon:l,panels:d.map(e=>({id:e.id,title:e.title,icon:Se(e.icon),isExpanded:i.expandedSections.has(e.id)}))},u=Re({hasShell:!0,shellHeader:function(e){const t=ye("tbw-shell-header",{part:"shell-header",role:"presentation"});if(e.title){const i=ye("tbw-shell-title");i.textContent=e.title,t.appendChild(i)}const i=ye("tbw-shell-content",{part:"shell-content",role:"presentation","data-light-dom-header-content":""});t.appendChild(i);const n=ye("tbw-shell-toolbar",{part:"shell-toolbar",role:"presentation"});for(const r of e.configButtons)r.hasRender&&n.appendChild(ye("tbw-toolbar-content-slot",{"data-toolbar-content":r.id}));for(const r of e.apiButtons)r.hasRender&&n.appendChild(ye("tbw-toolbar-content-slot",{"data-toolbar-content":r.id}));if((e.configButtons.some(e=>e.hasRender)||e.apiButtons.some(e=>e.hasRender))&&e.hasPanels&&n.appendChild(ye("tbw-toolbar-separator")),e.hasPanels){const t=Ce(e.isPanelOpen?"tbw-toolbar-btn active":"tbw-toolbar-btn",{"data-panel-toggle":"",title:"Settings","aria-label":"Toggle settings panel","aria-pressed":String(e.isPanelOpen),"aria-controls":"tbw-tool-panel"});t.innerHTML=e.toolPanelIcon,n.appendChild(t)}return t.appendChild(n),t}(c),shellBody:function(e){const t=ye("tbw-shell-body"),i=e.panels.length>0,n=1===e.panels.length,r=ye("tbw-grid-content");r.appendChild(Ee());let o=null;if(i){o=ve("aside",{class:e.isPanelOpen?"tbw-tool-panel open":"tbw-tool-panel",part:"tool-panel","data-position":e.position,role:"presentation",id:"tbw-tool-panel"});const t="left"===e.position?"right":"left";o.appendChild(ye("tbw-tool-panel-resize",{"data-resize-handle":"","data-handle-position":t,"aria-hidden":"true"}));const i=ye("tbw-tool-panel-content",{role:"presentation"}),r=ye("tbw-accordion");for(const o of e.panels){const t=ye(`tbw-accordion-section${o.isExpanded?" expanded":""}${n?" single":""}`,{"data-section":o.id}),i=Ce("tbw-accordion-header",{"aria-expanded":String(o.isExpanded),"aria-controls":`tbw-section-${o.id}`});if(n&&i.setAttribute("aria-disabled","true"),o.icon){const e=ve("span",{class:"tbw-accordion-icon"});e.innerHTML=o.icon,i.appendChild(e)}const s=ve("span",{class:"tbw-accordion-title"});if(s.textContent=o.title,i.appendChild(s),!n){const t=ve("span",{class:"tbw-accordion-chevron"});t.innerHTML=o.isExpanded?e.collapseIcon:e.expandIcon,i.appendChild(t)}t.appendChild(i),t.appendChild(ye("tbw-accordion-content",{id:`tbw-section-${o.id}`,role:"presentation"})),r.appendChild(t)}i.appendChild(r),o.appendChild(i)}return"left"===e.position&&o?(t.appendChild(o),t.appendChild(r)):(t.appendChild(r),o&&t.appendChild(o)),t}(h)});e.appendChild(u)}else{const t=Re({hasShell:!1});e.appendChild(t)}return o}xe.innerHTML='\n <div class="tbw-scroll-area">\n <div class="rows-body-wrapper">\n <div class="rows-body" role="grid">\n <div class="header" role="rowgroup">\n <div class="header-row" role="row" part="header-row"></div>\n </div>\n <div class="rows-container" role="presentation">\n <div class="rows-viewport" role="presentation">\n <div class="rows"></div>\n </div>\n </div>\n </div>\n </div>\n </div>\n <div class="faux-vscroll">\n <div class="faux-vscroll-spacer"></div>\n </div>\n';const Fe="tbw-grid-styles";let qe="";const Ne=new Map;function Ge(){const e=function(){let e=document.getElementById(Fe);return e||(e=document.createElement("style"),e.id=Fe,e.setAttribute("data-tbw-grid","true"),document.head.appendChild(e)),e}(),t=Array.from(Ne.values()).join("\n");e.textContent=`${qe}\n\n/* Plugin Styles */\n${t}`}async function Be(e){if(qe)return;if("string"==typeof e&&e.length>0)return qe=e,void Ge();await new Promise(e=>setTimeout(e,50));const t=function(){try{for(const e of Array.from(document.styleSheets))try{const t=Array.from(e.cssRules||[]).map(e=>e.cssText).join("\n");if(t.includes(".tbw-grid-root")&&t.includes("tbw-grid"))return t}catch{continue}}catch(e){console.warn("[tbw-grid] Failed to extract grid.css from document stylesheets:",e)}return null}();t?(qe=t,Ge()):"undefined"!=typeof process&&"test"===process.env?.NODE_ENV||console.warn("[tbw-grid] Could not find grid.css in document.styleSheets. Grid styling will not work.","Available stylesheets:",Array.from(document.styleSheets).map(e=>e.href||"(inline)"))}function Ve(e){e.momentumRaf&&(cancelAnimationFrame(e.momentumRaf),e.momentumRaf=0)}function $e(e,t){(Math.abs(e.velocityY)>.1||Math.abs(e.velocityX)>.1)&&function(e,t){const i=.95,n=.01,r=()=>{e.velocityY*=i,e.velocityX*=i;const o=16*e.velocityY,s=16*e.velocityX;Math.abs(e.velocityY)>n&&(t.fauxScrollbar.scrollTop+=o),Math.abs(e.velocityX)>n&&t.scrollArea&&(t.scrollArea.scrollLeft+=s),Math.abs(e.velocityY)>n||Math.abs(e.velocityX)>n?e.momentumRaf=requestAnimationFrame(r):e.momentumRaf=0};e.momentumRaf=requestAnimationFrame(r)}(e,t),function(e){e.startY=null,e.startX=null,e.scrollTop=null,e.scrollLeft=null,e.lastY=null,e.lastX=null,e.lastTime=null}(e)}function We(e,t,i,n){e.addEventListener("touchstart",e=>function(e,t,i){if(1!==e.touches.length)return;Ve(t);const n=e.touches[0];t.startY=n.clientY,t.startX=n.clientX,t.lastY=n.clientY,t.lastX=n.clientX,t.lastTime=performance.now(),t.scrollTop=i.fauxScrollbar.scrollTop,t.scrollLeft=i.scrollArea?.scrollLeft??0,t.velocityY=0,t.velocityX=0}(e,t,i),{passive:!0,signal:n}),e.addEventListener("touchmove",e=>{const n=function(e,t,i){if(1!==e.touches.length||null===t.startY||null===t.startX||null===t.scrollTop||null===t.scrollLeft)return!1;const n=e.touches[0],r=n.clientY,o=n.clientX,s=performance.now(),l=t.startY-r,a=t.startX-o;if(null!==t.lastTime&&null!==t.lastY&&null!==t.lastX){const e=s-t.lastTime;e>0&&(t.velocityY=(t.lastY-r)/e,t.velocityX=(t.lastX-o)/e)}t.lastY=r,t.lastX=o,t.lastTime=s;const{scrollTop:d,scrollHeight:c,clientHeight:h}=i.fauxScrollbar,u=l>0&&d<c-h||l<0&&d>0;let g=!1;if(i.scrollArea){const{scrollLeft:e,scrollWidth:t,clientWidth:n}=i.scrollArea;g=a>0&&e<t-n||a<0&&e>0}return u&&(i.fauxScrollbar.scrollTop=t.scrollTop+l),g&&i.scrollArea&&(i.scrollArea.scrollLeft=t.scrollLeft+a),u||g}(e,t,i);n&&e.preventDefault()},{passive:!1,signal:n}),e.addEventListener("touchend",()=>$e(t,i),{passive:!0,signal:n})}const Ke=[{property:"editable",pluginName:"editing",level:"column",description:'the "editable" column property',isUsed:e=>!0===e},{property:"editor",pluginName:"editing",level:"column",description:'the "editor" column property'},{property:"editorParams",pluginName:"editing",level:"column",description:'the "editorParams" column property'},{property:"group",pluginName:"groupingColumns",level:"column",description:'the "group" column property'},{property:"pinned",pluginName:"pinnedColumns",level:"column",description:'the "pinned" column property',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e},{property:"sticky",pluginName:"pinnedColumns",level:"column",description:'the "sticky" column property (deprecated, use "pinned")',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e}],Ue=[{property:"columnGroups",pluginName:"groupingColumns",level:"config",description:'the "columnGroups" config property',isUsed:e=>Array.isArray(e)&&e.length>0}];function je(e){return`import { ${Ye(e)}Plugin } from '@toolbox-web/grid/plugins/${t=e,t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}';`;var t}function Ye(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Xe(e,t){return e.some(e=>e.name===t)}function Ze(e,t){return e&&"object"==typeof e?"__rowCacheKey"in e?e.__rowCacheKey:"rowId"in e&&null!=e.rowId?`id:${e.rowId}`:t?`id:${t(e)}`:e:e}function Qe(e,t,i){const n=Ze(t,i);return"string"==typeof n?e.byKey.get(n):n&&"object"==typeof n?e.byRef.get(n):void 0}function Je(e,t,i){if(t<0||t>=e.length)return;const n=e[t],r=i-n.height;if(0!==r){n.height=i,n.measured=!0;for(let i=t+1;i<e.length;i++)e[i].offset+=r}}function et(e,t){if(0===e.length)return-1;if(t<=0)return 0;let i=0,n=e.length-1;for(;i<=n;){const r=Math.floor((i+n)/2),o=e[r],s=o.offset+o.height;if(t<o.offset)n=r-1;else{if(!(t>=s))return r;i=r+1}}return Math.max(0,Math.min(i,e.length-1))}function tt(e,t){const{positionCache:i,heightCache:n,rows:r,start:o,end:s,getPluginHeight:l,getRowId:a}=e;let d=!1;t.forEach(e=>{const t=e.dataset.rowIndex;if(!t)return;const c=parseInt(t,10);if(c<o||c>=s||c>=r.length)return;const h=r[c],u=l?.(h,c);if(void 0!==u){const e=i[c];return void((!e.measured||Math.abs(e.height-u)>1)&&(Je(i,c,u),d=!0))}const g=e.offsetHeight;if(g>0){const e=i[c];(!e.measured||Math.abs(e.height-g)>1)&&(Je(i,c,g),function(e,t,i,n){const r=Ze(t,n);"string"==typeof r?e.byKey.set(r,i):r&&"object"==typeof r&&e.byRef.set(r,i)}(n,h,g,a),d=!0)}});const c=d?function(e){let t=0;for(const i of e)i.measured&&t++;return t}(i):0,h=d?function(e,t){let i=0,n=0;for(const r of e)r.measured&&(i+=r.height,n++);return n>0?i/n:t}(i,e.defaultHeight):0;return{hasChanges:d,measuredCount:c,averageHeight:h}}class it{constructor(e){this.grid=e}plugins=[];getPlugins(){return this.plugins}pluginMap=new Map;cellRenderers=new Map;headerRenderers=new Map;cellEditors=new Map;eventListeners=new Map;queryHandlers=new Map;static deprecationWarned=new WeakSet;attachAll(e){for(const t of e)this.attach(t)}attach(e){if(function(e,t){const i=e.name,n=e.constructor.dependencies??[];for(const r of n){const e=r.name,n=r.required??!0,o=r.reason;if(!t.some(t=>t.name===e)){const t=o??`${Ye(i)}Plugin requires ${Ye(e)}Plugin`,r=je(e);if(n)throw new Error(`[tbw-grid] Plugin dependency error:\n\n${t}.\n\n → Add the plugin to your gridConfig.plugins array BEFORE ${Ye(i)}Plugin:\n ${r}\n plugins: [new ${Ye(e)}Plugin(), new ${Ye(i)}Plugin()]`);console.info(`[tbw-grid] ${Ye(i)}Plugin: Optional "${e}" plugin not found. Some features may be unavailable.`)}}}(e,this.plugins),this.pluginMap.set(e.constructor,e),this.plugins.push(e),e.cellRenderers)for(const[t,i]of Object.entries(e.cellRenderers))this.cellRenderers.set(t,i);if(e.headerRenderers)for(const[t,i]of Object.entries(e.headerRenderers))this.headerRenderers.set(t,i);if(e.cellEditors)for(const[t,i]of Object.entries(e.cellEditors))this.cellEditors.set(t,i);this.registerQueryHandlers(e),this.warnDeprecatedHooks(e),e.attach(this.grid);for(const t of this.plugins)t!==e&&t.onPluginAttached&&t.onPluginAttached(e.name,e)}registerQueryHandlers(e){const t=e.constructor.manifest;if(t?.queries)for(const i of t.queries){let t=this.queryHandlers.get(i.type);t||(t=new Set,this.queryHandlers.set(i.type,t)),t.add(e)}}warnDeprecatedHooks(e){const t=e.constructor;if(it.deprecationWarned.has(t))return;if(!_())return;const i="function"==typeof e.getExtraHeight||"function"==typeof e.getExtraHeightBefore,n="function"==typeof e.getRowHeight;i&&!n&&(it.deprecationWarned.add(t),console.warn(`[tbw-grid] Deprecation warning: "${e.name}" uses getExtraHeight() / getExtraHeightBefore() which are deprecated and will be removed in v3.0.\n → Migrate to getRowHeight(row, index) for better variable row height support.\n → See: https://toolbox-web.dev/docs/grid/plugins/migration#row-height-hooks`))}unregisterQueryHandlers(e){for(const[t,i]of this.queryHandlers)i.delete(e),0===i.size&&this.queryHandlers.delete(t)}detachAll(){for(const e of this.plugins)for(const t of this.plugins)t!==e&&t.onPluginDetached&&t.onPluginDetached(e.name);for(let e=this.plugins.length-1;e>=0;e--){const t=this.plugins[e];this.unsubscribeAll(t),this.unregisterQueryHandlers(t),t.detach()}this.plugins=[],this.pluginMap.clear(),this.cellRenderers.clear(),this.headerRenderers.clear(),this.cellEditors.clear(),this.eventListeners.clear(),this.queryHandlers.clear()}getPlugin(e){return this.pluginMap.get(e)}getPluginByName(e){return this.plugins.find(t=>t.name===e)}hasPlugin(e){return this.pluginMap.has(e)}getAll(){return this.plugins}getRegisteredPluginNames(){return this.plugins.map(e=>e.name)}getCellRenderer(e){return this.cellRenderers.get(e)}getHeaderRenderer(e){return this.headerRenderers.get(e)}getCellEditor(e){return this.cellEditors.get(e)}getPluginStyles(){return this.plugins.filter(e=>e.styles).map(e=>({name:e.name,styles:e.styles}))}processRows(e){let t=[...e];for(const i of this.plugins)i.processRows&&(t=i.processRows(t));return t}processColumns(e){let t=[...e];for(const i of this.plugins)i.processColumns&&(t=i.processColumns(t));return t}beforeRender(){for(const e of this.plugins)e.beforeRender?.()}afterRender(){for(const e of this.plugins)e.afterRender?.()}afterCellRender(e){for(const t of this.plugins)t.afterCellRender?.(e)}hasAfterCellRenderHook(){return this.plugins.some(e=>"function"==typeof e.afterCellRender)}afterRowRender(e){for(const t of this.plugins)t.afterRowRender?.(e)}hasAfterRowRenderHook(){return this.plugins.some(e=>"function"==typeof e.afterRowRender)}onScrollRender(){for(const e of this.plugins)e.onScrollRender?.()}getExtraHeight(){let e=0;for(const t of this.plugins)"function"==typeof t.getExtraHeight&&(e+=t.getExtraHeight());return e}hasExtraHeight(){for(const e of this.plugins)if("function"==typeof e.getExtraHeight&&e.getExtraHeight()>0)return!0;return!1}getExtraHeightBefore(e){let t=0;for(const i of this.plugins)"function"==typeof i.getExtraHeightBefore&&(t+=i.getExtraHeightBefore(e));return t}getRowHeight(e,t){for(const i of this.plugins)if("function"==typeof i.getRowHeight){const n=i.getRowHeight(e,t);if(void 0!==n)return n}}hasRowHeightPlugin(){for(const e of this.plugins)if("function"==typeof e.getRowHeight)return!0;return!1}adjustVirtualStart(e,t,i){let n=e;for(const r of this.plugins)if("function"==typeof r.adjustVirtualStart){const o=r.adjustVirtualStart(e,t,i);o<n&&(n=o)}return n}renderRow(e,t,i){for(const n of this.plugins)if(n.renderRow?.(e,t,i))return!0;return!1}queryPlugins(e){const t=[],i=this.queryHandlers.get(e.type);if(i&&i.size>0){for(const n of i){const i=n.handleQuery?.(e)??n.onPluginQuery?.(e);void 0!==i&&t.push(i)}return t}for(const n of this.plugins){const i=n.handleQuery?.(e)??n.onPluginQuery?.(e);void 0!==i&&t.push(i)}return t}subscribe(e,t,i){let n=this.eventListeners.get(t);n||(n=new Map,this.eventListeners.set(t,n)),n.set(e,i)}unsubscribe(e,t){const i=this.eventListeners.get(t);i&&(i.delete(e),0===i.size&&this.eventListeners.delete(t))}unsubscribeAll(e){for(const[t,i]of this.eventListeners)i.delete(e),0===i.size&&this.eventListeners.delete(t)}emitPluginEvent(e,t){const i=this.eventListeners.get(e);if(i)for(const r of i.values())try{r(t)}catch(n){console.error(`[tbw-grid] Error in plugin event handler for "${e}":`,n)}}onKeyDown(e){for(const t of this.plugins)if(t.onKeyDown?.(e))return!0;return!1}onCellClick(e){for(const t of this.plugins)if(t.onCellClick?.(e))return!0;return!1}onRowClick(e){for(const t of this.plugins)if(t.onRowClick?.(e))return!0;return!1}onHeaderClick(e){for(const t of this.plugins)if(t.onHeaderClick?.(e))return!0;return!1}onScroll(e){for(const t of this.plugins)t.onScroll?.(e)}onCellMouseDown(e){for(const t of this.plugins)if(t.onCellMouseDown?.(e))return!0;return!1}onCellMouseMove(e){for(const t of this.plugins)if(t.onCellMouseMove?.(e))return!0;return!1}onCellMouseUp(e){for(const t of this.plugins)if(t.onCellMouseUp?.(e))return!0;return!1}getHorizontalScrollOffsets(e,t){let i=0,n=0,r=!1;for(const o of this.plugins){const s=o.getHorizontalScrollOffsets?.(e,t);s&&(i+=s.left,n+=s.right,s.skipScroll&&(r=!0))}return{left:i,right:n,skipScroll:r}}getToolPanels(){const e=[];for(const t of this.plugins){const i=t.getToolPanel?.();i&&e.push({plugin:t,panel:i})}return e.sort((e,t)=>(e.panel.order??0)-(t.panel.order??0))}getHeaderContents(){const e=[];for(const t of this.plugins){const i=t.getHeaderContent?.();i&&e.push({plugin:t,content:i})}return e.sort((e,t)=>(e.content.order??0)-(t.content.order??0))}}class nt extends HTMLElement{static tagName="tbw-grid";static version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";static#T=0;static adapters=[];static registerAdapter(e){this.adapters.push(e)}static getAdapters(){return this.adapters}static clearAdapters(){this.adapters=[]}static get observedAttributes(){return["rows","columns","grid-config","fit-mode","loading"]}get#L(){return this}#M=!1;#E;#R;#I=[];get#s(){return this.#P?.effective??{}}#H=!1;#D=!1;#z={rows:!1,columns:!1,gridConfig:!1,fitMode:!1};#O;#F=0;#q=null;#N=!1;#G=!1;#B=0;#V;#$={startY:null,startX:null,scrollTop:null,scrollLeft:null,lastY:null,lastX:null,lastTime:null,velocityY:0,velocityX:0,momentumRaf:0};#W;#K;#U;#j;#Y={scrollTop:0,scrollLeft:0,scrollHeight:0,scrollWidth:0,clientHeight:0,clientWidth:0};#X;#Z;get _pluginManager(){return this.#X}#Q=!1;#J;#ee;#h;#P;#te=function(){return{toolPanels:new Map,headerContents:new Map,toolbarContents:new Map,hasToolButtonsContainer:!1,lightDomHeaderContent:[],lightDomTitle:null,lightDomToolPanelIds:new Set,lightDomToolbarContentIds:new Set,apiToolPanelIds:new Set,isPanelOpen:!1,expandedSections:new Set,headerContentCleanups:new Map,panelCleanups:new Map,toolbarContentCleanups:new Map,lightDomContentMoved:!1}}();#ie;#ne;#re;#oe=!1;#se=new Set;#le=new Map;#ae;#de=new Map;_rows=[];#ce=[];get _columns(){return this.#s.columns??[]}set _columns(e){this.#s.columns=e}get _visibleColumns(){return this._columns.filter(e=>!e.hidden)}_headerRowEl;_bodyEl;_rowPool=[];_resizeController;_virtualization={enabled:!0,rowHeight:28,bypassThreshold:24,start:0,end:0,container:null,viewportEl:null,totalHeightEl:null,positionCache:null,heightCache:{byKey:new Map,byRef:new WeakMap},averageHeight:28,measuredCount:0,variableHeights:!1,cachedViewportHeight:0,cachedFauxHeight:0,cachedScrollAreaHeight:0,scrollAreaEl:null};_focusRow=0;_focusCol=0;_restoreFocusAfterRender=!1;_sortState=null;_gridTemplate="";__rowRenderEpoch=0;__didInitialAutoSize=!1;get __lightDomColumnsCache(){return this.#P?.lightDomColumnsCache}set __lightDomColumnsCache(e){this.#P&&(this.#P.lightDomColumnsCache=e)}get __originalColumnNodes(){return this.#P?.originalColumnNodes}set __originalColumnNodes(e){this.#P&&(this.#P.originalColumnNodes=e)}__originalOrder=[];__frameworkAdapter;__rowsBodyEl=null;get rows(){return this._rows}set rows(e){const t=this.#I;this.#I=e,t!==e&&this.#he("rows")}get sourceRows(){return this.#I}get columns(){return[...this._columns]}set columns(e){const t=this.#P?.getColumns();this.#P?.setColumns(e),t!==e&&this.#he("columns")}get gridConfig(){return this.#s}set gridConfig(e){const t=this.#P?.getGridConfig();this.#P?.setGridConfig(e),t!==e&&(this.#P.clearLightDomCache(),this.#he("gridConfig"))}get fitMode(){return this.#s.fitMode??"stretch"}set fitMode(e){const t=this.#P?.getFitMode();this.#P?.setFitMode(e),t!==e&&this.#he("fitMode")}get loading(){return this.#oe}set loading(e){const t=this.#oe;this.#oe=e,e?this.setAttribute("loading",""):this.removeAttribute("loading"),t!==e&&this.#ue()}setRowLoading(e,t){const i=this.#se.has(e);t?this.#se.add(e):this.#se.delete(e),i!==t&&this.#ge(e,t)}setCellLoading(e,t,i){let n=this.#le.get(e);const r=n?.has(t)??!1;i?(n||(n=new Set,this.#le.set(e,n)),n.add(t)):(n?.delete(t),0===n?.size&&this.#le.delete(e)),r!==i&&this.#pe(e,t,i)}isRowLoading(e){return this.#se.has(e)}isCellLoading(e,t){return this.#le.get(e)?.has(t)??!1}clearAllLoading(){this.loading=!1;for(const e of this.#se)this.#ge(e,!1);this.#se.clear();for(const[e,t]of this.#le)for(const i of t)this.#pe(e,i,!1);this.#le.clear()}get effectiveConfig(){return this.#s}get disconnectSignal(){return this.#W||(this.#W=new AbortController),this.#W.signal}constructor(){super(),this.#fe(),this.#E=new Promise(e=>this.#R=e),this.#O=new ue({mergeConfig:()=>{this.#P.parseLightDomColumns(this),this.#P.merge(),this.#we(),function(e,t){const i=Ke,n=Ue,r=new Map;function o(e,t,i,n,o=!1){r.has(e)||r.set(e,{description:t,importHint:i,fields:[],isConfigProperty:o});const s=r.get(e);s.fields.includes(n)||s.fields.push(n)}for(const l of n){const i=e[l.property];(l.isUsed?l.isUsed(i):void 0!==i)&&!Xe(t,l.pluginName)&&o(l.pluginName,l.description,je(l.pluginName),l.property,!0)}const s=e.columns;if(s&&s.length>0)for(const l of s)for(const e of i){const i=l[e.property];if((e.isUsed?e.isUsed(i):void 0!==i)&&!Xe(t,e.pluginName)){const t=l.field||"<unknown>";o(e.pluginName,e.description,je(e.pluginName),t)}}if(r.size>0){const e=[];for(const[t,{description:i,importHint:n,fields:o,isConfigProperty:s}]of r)if(s)e.push(`Config uses ${i}, but the required plugin is not loaded.\n → Add the plugin to your gridConfig.plugins array:\n ${n}\n plugins: [new ${Ye(t)}Plugin(), ...]`);else{const r=o.slice(0,3).join(", ")+(o.length>3?`, ... (${o.length} total)`:"");e.push(`Column(s) [${r}] use ${i}, but the required plugin is not loaded.\n → Add the plugin to your gridConfig.plugins array:\n ${n}\n plugins: [new ${Ye(t)}Plugin(), ...]`)}throw new Error(`[tbw-grid] Configuration error:\n\n${e.join("\n\n")}\n\nThis validation helps catch misconfigurations early. The properties listed above require their respective plugins to function.`)}}(this.#s,this.#X?.getPlugins()??[]),function(e){const t=[],i=[];for(const n of e){const e=n.constructor.manifest;if(e?.configRules)for(const r of e.configRules){const e=n.config;if(r.check(e)){const e=`[tbw-grid:${Ye(n.name)}Plugin] Configuration warning: ${r.message}`;"error"===r.severity?t.push(e):i.push(e)}}}if(i.length>0&&_())for(const n of i)console.warn(n);if(t.length>0)throw new Error(`[tbw-grid] Configuration error:\n\n${t.join("\n\n")}`)}(this.#X?.getPlugins()??[]),function(e){if(!_())return;const t=new Set(e.map(e=>e.name)),i=new Set;for(const n of e){const e=n.constructor.manifest;if(e?.incompatibleWith)for(const r of e.incompatibleWith)if(t.has(r.name)){const e=[n.name,r.name].sort().join("↔");if(i.has(e))continue;i.add(e),console.warn(`[tbw-grid] Plugin incompatibility warning:\n\n${Ye(n.name)}Plugin and ${Ye(r.name)}Plugin are both loaded, but they are currently incompatible.\n\n → ${r.reason}\n\n Consider removing one of these plugins to avoid unexpected behavior.`)}}}(this.#X?.getPlugins()??[]),this.#me(),this.#ce=[...this._columns]},processColumns:()=>this.#be(),processRows:()=>this.#ve(),renderHeader:()=>le(this),updateTemplate:()=>c(this),renderVirtualWindow:()=>this.refreshVirtualWindow(!0,!0),afterRender:()=>{this.#X?.afterRender(),this._virtualization.enabled&&this._virtualization.totalHeightEl&&queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const e=this.#ye(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`});"fixed"!==this.#s.fitMode||this.__didInitialAutoSize||(this.__didInitialAutoSize=!0,l(this)),this._restoreFocusAfterRender&&(this._restoreFocusAfterRender=!1,K(this)),this._virtualization.enabled&&!this.#Ce&&this.#xe(),this.#G&&(this.#G=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.#Ee()})})),this.#oe&&this.#ue()},isConnected:()=>this.isConnected&&this.#H}),this.#O.setInitialReadyResolver(()=>this.#R?.()),this.#ie=De(this.#te,{getShadow:()=>this.#L,getShellConfig:()=>this.#s?.shell,getAccordionIcons:()=>({expand:this.#s?.icons?.expand??r.expand,collapse:this.#s?.icons?.collapse??r.collapse}),emit:(e,t)=>this.#Re(e,t),refreshShellHeader:()=>this.refreshShellHeader()}),this.#P=new S({getRows:()=>this.#I,getSortState:()=>this._sortState,setSortState:e=>{this._sortState=e},onConfigChange:()=>{this.#O.requestPhase(he.FULL,"configChange")},emit:(e,t)=>this.#Re(e,t),clearRowPool:()=>{this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++},setup:()=>this.#Se(),renderHeader:()=>le(this),updateTemplate:()=>c(this),refreshVirtualWindow:()=>this.#O.requestPhase(he.VIRTUALIZATION,"configManager"),getVirtualization:()=>this._virtualization,setRowHeight:e=>{this._virtualization.rowHeight=e},applyAnimationConfig:e=>this.#_e(e),getShellLightDomTitle:()=>this.#te.lightDomTitle,getShellToolPanels:()=>this.#te.toolPanels,getShellHeaderContents:()=>this.#te.headerContents,getShellToolbarContents:()=>this.#te.toolbarContents,getShellLightDomHeaderContent:()=>this.#te.lightDomHeaderContent,getShellHasToolButtonsContainer:()=>this.#te.hasToolButtonsContainer})}async#fe(){await Be('@layer tbw-base, tbw-plugins, tbw-theme;\n\n@layer tbw-base{tbw-grid{--tbw-base-icon-size: 1em;--tbw-base-radius: .25em;--tbw-font-size: 1em;--tbw-font-size-sm: .9285em;--tbw-font-size-xs: .7857em;--tbw-font-size-2xs: .7142em;--tbw-spacing-xs: .25em;--tbw-spacing-sm: .375em;--tbw-spacing-md: .5em;--tbw-spacing-lg: .75em;--tbw-spacing-xl: 1em;--tbw-icon-size: var(--tbw-base-icon-size);--tbw-icon-size-sm: .875em;--tbw-checkbox-size: var(--tbw-base-icon-size);--tbw-toggle-size: 1.25em;--tbw-border-radius: var(--tbw-base-radius);--tbw-color-bg: transparent;--tbw-color-panel-bg: light-dark(#eeeeee, #222222);--tbw-color-fg: light-dark(#222222, #eeeeee);--tbw-color-fg-muted: light-dark(#555555, #aaaaaa);--tbw-color-accent: light-dark(#3b82f6, #3b82f6);--tbw-color-accent-fg: light-dark(#ffffff, #000000);--tbw-color-success: light-dark(hsl(122, 39%, 40%), hsl(122, 39%, 49%));--tbw-color-warning: light-dark(hsl(38, 92%, 50%), hsl(38, 92%, 50%));--tbw-color-error: light-dark(hsl(0, 65%, 51%), hsl(0, 65%, 55%));--tbw-color-danger: var(--tbw-color-error);--tbw-color-selection: light-dark(#fff7d6, #333333);--tbw-color-row-alt: var(--tbw-color-bg);--tbw-color-row-hover: light-dark(#f0f6ff, #1c1c1c);--tbw-color-header-bg: color-mix(in hsl, var(--tbw-color-panel-bg) 85%, var(--tbw-color-fg));--tbw-color-header-fg: color-mix(in hsl, var(--tbw-color-fg) 75%, var(--tbw-color-panel-bg));--tbw-color-border: light-dark(#d0d0d4, #454545);--tbw-color-border-strong: light-dark(#777777, #666666);--tbw-color-border-cell: var(--tbw-color-border);--tbw-color-border-header: var(--tbw-color-border);--tbw-color-shadow: light-dark(rgba(0, 0, 0, .1), rgba(0, 0, 0, .3));--tbw-font-family: inherit;--tbw-font-size-header: var(--tbw-font-size);--tbw-font-weight-header: bold;--tbw-cell-padding-header: var(--tbw-spacing-xs) var(--tbw-spacing-md);--tbw-cell-padding-v: var(--tbw-spacing-xs);--tbw-cell-padding-h: var(--tbw-spacing-md);--tbw-cell-padding: var(--tbw-cell-padding-v) var(--tbw-cell-padding-h);--tbw-cell-padding-input: var(--tbw-spacing-xs) var(--tbw-spacing-sm);--tbw-row-height: 1.75em;--tbw-header-height: 1.875em;--tbw-cell-white-space: nowrap;--tbw-border-width: 1px;--tbw-border-style: solid;--tbw-border-input: var(--tbw-border-width) var(--tbw-border-style) var(--tbw-color-border-strong);--tbw-border-header: var(--tbw-border-width) var(--tbw-border-style) var(--tbw-color-border-header);--tbw-row-divider: var(--tbw-border-width) var(--tbw-border-style) var(--tbw-color-border-cell);--tbw-row-hover-outline: 0;--tbw-color-active-row-bg: var(--tbw-color-selection);--tbw-active-row-outline: 0;--tbw-focus-outline-width: 2px;--tbw-focus-outline: var(--tbw-focus-outline-width) var(--tbw-border-style) var(--tbw-color-accent);--tbw-focus-outline-offset: -2px;--tbw-focus-background: rgba(from var(--tbw-color-accent) r g b / 12%);--tbw-range-border-color: var(--tbw-color-accent);--tbw-range-selection-bg: rgba(from var(--tbw-range-border-color) r g b / 12%);--tbw-resize-handle-width: var(--tbw-spacing-sm);--tbw-resize-handle-color: transparent;--tbw-resize-handle-color-hover: var(--tbw-color-accent);--tbw-resize-handle-border-radius: 0;--tbw-resize-indicator-width: 2px;--tbw-resize-indicator-color: var(--tbw-color-accent);--tbw-resize-indicator-opacity: .6;--tbw-transition-duration: .12s;--tbw-transition-ease: ease;--tbw-animation-duration: .2s;--tbw-animation-easing: ease-out;--tbw-animation-enabled: 1;--tbw-row-change-duration: .5s;--tbw-row-insert-duration: .3s;--tbw-row-remove-duration: .2s;--tbw-row-change-color: rgba(from var(--tbw-color-accent) r g b / 25%);--tbw-sort-indicator-color: var(--tbw-color-fg-muted);--tbw-sort-indicator-active-color: var(--tbw-color-accent);--tbw-sort-indicator-display: inline-flex;--tbw-sort-indicator-visibility: visible;--tbw-header-text-transform: none;--tbw-header-letter-spacing: normal;--tbw-color-header-separator: var(--tbw-color-border-cell);--tbw-density-scale: 1;--tbw-shell-header-height: 2.75em;--tbw-shell-header-bg: var(--tbw-color-panel-bg);--tbw-shell-header-border: var(--tbw-color-border);--tbw-shell-title-font-size: var(--tbw-font-size);--tbw-shell-title-font-weight: 600;--tbw-tool-panel-width: 17.5em;--tbw-tool-panel-bg: var(--tbw-color-panel-bg);--tbw-tool-panel-border: var(--tbw-color-border);--tbw-tool-panel-header-height: 2.5em;--tbw-tool-panel-transition: var(--tbw-animation-duration) var(--tbw-animation-easing);--tbw-toolbar-button-size: 2em;--tbw-toolbar-button-gap: var(--tbw-spacing-xs);--tbw-panel-padding: var(--tbw-spacing-lg);--tbw-panel-gap: var(--tbw-spacing-md);--tbw-menu-item-padding: var(--tbw-spacing-sm) var(--tbw-spacing-lg);--tbw-menu-item-gap: var(--tbw-spacing-md);--tbw-menu-min-width: 10rem;--tbw-button-padding: var(--tbw-spacing-sm) var(--tbw-spacing-lg);--tbw-button-padding-sm: var(--tbw-spacing-xs) var(--tbw-spacing-md);--tbw-input-height: var(--tbw-row-height);--tbw-input-padding: 0 var(--tbw-spacing-md);--tbw-detail-padding: var(--tbw-spacing-xl);--tbw-detail-max-height: 31.25rem;--tbw-indicator-size: var(--tbw-spacing-sm)}}\n@layer tbw-base{tbw-grid{color-scheme:inherit;position:relative;display:block;width:100%;height:100%;min-height:0;contain:content;font-family:var(--tbw-font-family);font-size:var(--tbw-font-size);font-feature-settings:"tnum","lnum";background:var(--tbw-color-bg);color:var(--tbw-color-fg);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);overflow:clip;outline:none}tbw-grid,tbw-grid *{box-sizing:border-box}tbw-grid .tbw-grid-root{position:relative;display:flex;flex-direction:column;height:100%}tbw-grid .tbw-grid-root.has-shell{display:flex;flex-direction:column;height:100%}tbw-grid .tbw-grid-root:has(.selected){-webkit-user-select:none;user-select:none}tbw-grid .rows-body-wrapper{flex:1;min-height:0;display:flex;flex-direction:row;width:100%;min-width:fit-content}tbw-grid .rows-body{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:visible}tbw-grid .rows-container{display:flex;flex-direction:row;flex:1;min-height:0;overflow:visible}tbw-grid .rows-viewport{flex:1;min-width:0;position:relative;display:block;overflow:clip}tbw-grid .rows-viewport .rows{position:absolute;top:0;left:0;min-width:100%;will-change:transform;z-index:var(--tbw-z-layer-rows, 1)}tbw-grid .faux-vscroll{position:sticky;inset-inline-end:0;flex-shrink:0;width:auto;overflow-y:auto;overflow-x:hidden;z-index:var(--tbw-z-layer-header, 30)}tbw-grid .faux-vscroll-spacer{width:1px}tbw-grid[data-has-focus] .cell-focus,tbw-grid[data-has-focus] .row-focus{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}tbw-grid .sticky-left,tbw-grid .sticky-right{position:sticky;z-index:25}tbw-grid .sticky-left{box-shadow:1px 0 0 var(--tbw-color-border)}tbw-grid .sticky-right{box-shadow:-1px 0 0 var(--tbw-color-border)}}\n@layer tbw-base{tbw-grid .header{display:block;flex-shrink:0;z-index:var(--tbw-z-layer-header, 30);background:var(--tbw-color-header-bg);overflow:visible}tbw-grid .header-group-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-color-header-bg);z-index:var(--tbw-z-layer-header, 30)}tbw-grid .header-group-cell{display:flex;align-items:center;justify-content:flex-start;padding:var(--tbw-cell-padding-header, 2px 8px);color:var(--tbw-color-header-group-fg, var(--tbw-color-header-fg));font-weight:var(--tbw-font-weight-header-group, var(--tbw-font-weight-header));justify-content:var(--tbw-align-header-group, var(--tbw-align-header, flex-start))}tbw-grid .header-group-cell:not(:last-child){border-right:2px solid var(--tbw-color-border)}tbw-grid .header-row{display:grid;grid-template-columns:var(--tbw-column-template);color:var(--tbw-color-header-fg);font-size:var(--tbw-font-size-header);min-height:var(--tbw-header-height);border-bottom:var(--tbw-border-header);z-index:var(--tbw-z-layer-header, 30);text-transform:var(--tbw-header-text-transform);letter-spacing:var(--tbw-header-letter-spacing)}tbw-grid .header-row>.cell{display:flex;align-items:center;gap:4px;padding:var(--tbw-cell-padding-header, 2px 8px);background-color:var(--tbw-color-header-bg);font-weight:var(--tbw-font-weight-header);border-right:1px solid var(--tbw-color-border-cell);overflow:visible;min-width:0}tbw-grid .header-row>.cell>span:first-child{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:inherit}tbw-grid .header-row>.cell>span[part~=sort-indicator]{flex-shrink:0;opacity:.6;color:var(--tbw-sort-indicator-color);display:var(--tbw-sort-indicator-display, inline-flex);visibility:var(--tbw-sort-indicator-visibility, visible);transition:opacity .15s,visibility 0s,display 0s allow-discrete;transition-behavior:allow-discrete}tbw-grid .header-row>.cell:hover>span[part~=sort-indicator]{display:inline-flex;visibility:visible}tbw-grid .header-row>.cell[aria-sort=ascending]>span[part~=sort-indicator],tbw-grid .header-row>.cell[aria-sort=descending]>span[part~=sort-indicator]{display:inline-flex;visibility:visible;opacity:1;color:var(--tbw-sort-indicator-active-color)}tbw-grid .header-row>.cell:last-child{border-right:0}tbw-grid .header-row>.cell:last-child .resize-handle{right:0;width:calc(var(--tbw-resize-handle-width) / 2)}tbw-grid .header-row>.cell.grouped.group-end:not(:last-child){border-right:2px solid var(--tbw-color-border)}tbw-grid .header-row>.cell.resizable{position:relative}tbw-grid .header-row>.cell.sticky-left,tbw-grid .header-row>.cell.sticky-right{background:var(--tbw-color-header-bg);z-index:35}tbw-grid .sortable{cursor:pointer;-webkit-user-select:none;user-select:none}tbw-grid .resize-handle{position:absolute;top:0;right:calc(var(--tbw-resize-handle-width) / -2);width:var(--tbw-resize-handle-width);height:100%;cursor:e-resize;-webkit-user-select:none;user-select:none;touch-action:none;z-index:20;background:var(--tbw-resize-handle-color);transition:background .12s ease;border-radius:var(--tbw-resize-handle-border-radius)}tbw-grid .resize-handle:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);width:var(--tbw-resize-indicator-width, 2px);height:0;background:var(--tbw-resize-indicator-color, var(--tbw-color-accent));opacity:0;pointer-events:none;transition:opacity .12s ease,height 0s .12s;z-index:1000}tbw-grid .resize-handle:hover{background:var(--tbw-resize-handle-color-hover)}tbw-grid .resize-handle:hover:after{height:100vh;opacity:var(--tbw-resize-indicator-opacity, .6);transition:opacity .12s ease,height 0s}}\n@layer tbw-base{tbw-grid .data-grid-row{display:grid;grid-template-columns:var(--tbw-column-template);contain:layout style}tbw-grid .data-grid-row:nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid .data-grid-row:hover{background:var(--tbw-color-row-hover)}tbw-grid .data-grid-row>.cell{display:block;padding:var(--tbw-cell-padding, 2px 8px);border-bottom:var(--tbw-row-divider);min-height:var(--tbw-row-height);align-content:center;border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;min-width:0;white-space:var(--tbw-cell-white-space, nowrap);text-overflow:ellipsis}tbw-grid .data-grid-row>.cell>*{overflow:hidden;text-overflow:ellipsis;white-space:inherit;min-width:0}tbw-grid .data-grid-row>.cell:last-child{border-right:0}tbw-grid .data-grid-row>.cell[data-type=boolean]{text-align:center}tbw-grid .data-grid-row>.cell[data-type=boolean] input[type=checkbox]{margin:0;width:var(--tbw-checkbox-size);height:var(--tbw-checkbox-size);vertical-align:middle}tbw-grid .data-grid-row>.cell.selected:focus-visible,tbw-grid .data-grid-row>.cell:focus-visible:not(.cell-focus){outline:none}tbw-grid .data-grid-row>.cell.sticky-left,tbw-grid .data-grid-row>.cell.sticky-right{background:var(--tbw-color-panel-bg)}tbw-grid .selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}}\n@layer tbw-base{tbw-grid .tbw-shell-header{display:flex;align-items:center;gap:8px;min-height:var(--tbw-shell-header-height);padding:0 8px;background:var(--tbw-shell-header-bg);border-bottom:1px solid var(--tbw-shell-header-border);flex-shrink:0}tbw-grid .tbw-shell-title{font-size:var(--tbw-shell-title-font-size);font-weight:var(--tbw-shell-title-font-weight);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}tbw-grid .tbw-shell-content{flex:1;display:flex;align-items:center;gap:12px;min-width:0;overflow:hidden}tbw-grid .tbw-shell-toolbar{display:flex;align-items:center;gap:var(--tbw-toolbar-button-gap);flex-shrink:0}tbw-grid .tbw-toolbar-btn{display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-toolbar-button-size);height:var(--tbw-toolbar-button-size);padding:0;border:1px solid transparent;border-radius:var(--tbw-border-radius);background:transparent;color:var(--tbw-color-fg);cursor:pointer;font-size:16px;transition:background var(--tbw-transition-duration) var(--tbw-transition-ease),border-color var(--tbw-transition-duration) var(--tbw-transition-ease)}tbw-grid .tbw-toolbar-btn:hover{background:var(--tbw-color-row-hover)}tbw-grid .tbw-toolbar-btn:focus-visible{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}tbw-grid .tbw-toolbar-btn.active{background:var(--tbw-focus-background);border-color:var(--tbw-color-accent)}tbw-grid .tbw-toolbar-btn:disabled{opacity:.5;cursor:not-allowed}tbw-grid .tbw-toolbar-separator{width:1px;height:20px;background:var(--tbw-color-border);margin:0 4px}tbw-grid .tbw-shell-body{position:relative;display:flex;flex:1;min-height:0;overflow:visible}tbw-grid .tbw-grid-content{flex:1;min-width:0;min-height:0;display:flex;flex-direction:row;overflow:hidden}tbw-grid .tbw-scroll-area{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow-x:auto;overflow-y:hidden;overflow-anchor:none}}\n@layer tbw-base{tbw-grid .tbw-tool-panel{position:absolute;top:0;bottom:0;right:0;width:0;overflow:hidden;background:var(--tbw-tool-panel-bg);border-left:1px solid var(--tbw-tool-panel-border);transition:width var(--tbw-tool-panel-transition);display:flex;flex-direction:column;z-index:30;box-shadow:-2px 0 8px var(--tbw-color-shadow)}tbw-grid .tbw-tool-panel[data-position=left]{right:auto;left:0;border-left:none;border-right:1px solid var(--tbw-tool-panel-border);box-shadow:2px 0 8px var(--tbw-color-shadow)}tbw-grid .tbw-tool-panel.open{width:var(--tbw-tool-panel-width)}tbw-grid .tbw-tool-panel-resize{position:absolute;top:0;bottom:0;width:6px;cursor:col-resize;background:transparent;z-index:10;transition:background var(--tbw-transition-duration) var(--tbw-transition-ease)}tbw-grid .tbw-tool-panel-resize[data-handle-position=left]{left:0}tbw-grid .tbw-tool-panel-resize[data-handle-position=right]{right:0}tbw-grid .tbw-tool-panel-resize:hover,tbw-grid .tbw-tool-panel-resize.resizing{background:var(--tbw-color-accent)}tbw-grid .tbw-tool-panel-header{display:flex;align-items:center;justify-content:space-between;min-height:var(--tbw-tool-panel-header-height);padding:0 12px;border-bottom:1px solid var(--tbw-tool-panel-border);flex-shrink:0}tbw-grid .tbw-tool-panel-title{font-weight:600;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}tbw-grid .tbw-tool-panel-close{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:none;border-radius:var(--tbw-border-radius);background:transparent;color:var(--tbw-color-fg-muted);cursor:pointer;font-size:14px}tbw-grid .tbw-tool-panel-close:hover{background:var(--tbw-color-row-hover);color:var(--tbw-color-fg)}tbw-grid .tbw-tool-panel-content{flex:1;overflow:auto}tbw-grid .tbw-accordion{display:flex;flex-direction:column;gap:0}tbw-grid .tbw-accordion-section{border-bottom:1px solid var(--tbw-tool-panel-border)}tbw-grid .tbw-accordion-section:last-child{border-bottom:none}tbw-grid .tbw-accordion-section.single .tbw-accordion-header{cursor:default}tbw-grid .tbw-accordion-section.single .tbw-accordion-header:hover{background:transparent}tbw-grid .tbw-accordion-section.expanded .tbw-accordion-chevron{transform:rotate(90deg)}tbw-grid .tbw-accordion-section.expanded .tbw-accordion-content{display:block}tbw-grid .tbw-accordion-header{display:flex;align-items:center;gap:8px;width:100%;padding:10px 12px;border:none;background:transparent;color:var(--tbw-color-fg);font-size:13px;font-weight:600;text-align:start;cursor:pointer;-webkit-user-select:none;user-select:none}tbw-grid .tbw-accordion-header:hover{background:var(--tbw-color-row-hover)}tbw-grid .tbw-accordion-chevron{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;font-size:10px;color:var(--tbw-color-fg-muted);transition:transform .15s ease;flex-shrink:0}tbw-grid .tbw-accordion-icon{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;font-size:14px;flex-shrink:0}tbw-grid .tbw-accordion-title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}tbw-grid .tbw-accordion-content{display:none}}\n@layer tbw-base{.tbw-loading-overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:1000;pointer-events:all;animation:tbw-fade-in .15s ease-out}.tbw-spinner{--tbw-spinner-size: 48px;--tbw-spinner-border-width: 3px;--tbw-spinner-color: var(--tbw-color-accent);--tbw-spinner-track-color: var(--tbw-color-border);width:var(--tbw-spinner-size);height:var(--tbw-spinner-size);border:var(--tbw-spinner-border-width) solid var(--tbw-spinner-track-color);border-top-color:var(--tbw-spinner-color);border-radius:50%;animation:tbw-spin .8s linear infinite}.tbw-spinner--large{--tbw-spinner-size: min(48px, calc(100% - 16px) )}.tbw-spinner--small{--tbw-spinner-size: calc(var(--tbw-row-height, 28px) * .6);--tbw-spinner-border-width: 2px}.data-grid-row.tbw-row-loading{position:relative;pointer-events:none}.tbw-row-loading-overlay{position:absolute;inset:0;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:26;animation:tbw-fade-in .15s ease-out;pointer-events:none;display:flex;align-items:center}.tbw-row-loading-spinner{--_spinner-size: calc(var(--tbw-row-height, 28px) * .6);margin-left:var(--tbw-spacing-md);width:var(--_spinner-size);height:var(--_spinner-size);border:2px solid var(--tbw-spinner-track-color, var(--tbw-color-border));border-top-color:var(--tbw-spinner-color, var(--tbw-color-accent));border-radius:50%;animation:tbw-spin .8s linear infinite}.cell.tbw-cell-loading{position:relative;pointer-events:none}.cell.tbw-cell-loading:before{content:"";position:absolute;inset:0;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:26;animation:tbw-fade-in .15s ease-out}.cell.tbw-cell-loading:after{--_spinner-size: calc(var(--tbw-row-height, 28px) * .5);content:"";position:absolute;left:var(--tbw-spacing-sm);top:0;bottom:0;margin:auto 0;width:var(--_spinner-size);height:var(--_spinner-size);border:2px solid var(--tbw-spinner-track-color, var(--tbw-color-border));border-top-color:var(--tbw-spinner-color, var(--tbw-color-accent));border-radius:50%;animation:tbw-spin .8s linear infinite;z-index:27}}\n@layer tbw-base{tbw-grid .tbw-expanding{animation:tbw-expand var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}tbw-grid .tbw-collapsing{animation:tbw-collapse var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}tbw-grid[data-animation-mode=off]{--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}tbw-grid[data-animation-mode=off] .data-grid-row[data-animating]{animation:none}tbw-grid .data-grid-row[data-animating=change]{animation:tbw-row-change var(--tbw-row-change-duration) ease-out}tbw-grid .data-grid-row[data-animating=insert]{animation:tbw-row-insert var(--tbw-row-insert-duration) ease-out;will-change:max-height,opacity}tbw-grid .data-grid-row[data-animating=remove]{animation:tbw-row-remove var(--tbw-row-remove-duration) ease-out forwards;will-change:max-height,opacity,transform;pointer-events:none}}@keyframes tbw-expand{0%{opacity:0;max-height:0;transform:translateY(-8px)}to{opacity:1;max-height:500px;transform:translateY(0)}}@keyframes tbw-collapse{0%{opacity:1;max-height:500px;transform:translateY(0)}to{opacity:0;max-height:0;transform:translateY(-8px)}}@keyframes tbw-row-change{0%{background-color:transparent}20%{background-color:var(--tbw-row-change-color)}to{background-color:transparent}}@keyframes tbw-row-insert{0%{opacity:0;max-height:0;overflow:hidden}to{opacity:1;max-height:var(--tbw-row-height, 28px);overflow:hidden}}@keyframes tbw-row-remove{0%{opacity:1;transform:translateY(0);max-height:var(--tbw-row-height, 28px)}to{opacity:0;max-height:0;transform:translateY(-8px)}}@keyframes tbw-spin{to{transform:rotate(360deg)}}@keyframes tbw-fade-in{0%{opacity:0}to{opacity:1}}\n@layer tbw-base{@media(forced-colors:active){tbw-grid{--tbw-color-border: CanvasText;--tbw-color-border-strong: CanvasText;--tbw-color-border-cell: CanvasText;--tbw-color-border-header: CanvasText;--tbw-color-fg: CanvasText;--tbw-color-bg: Canvas;--tbw-color-panel-bg: Canvas;--tbw-color-header-bg: Canvas;--tbw-color-header-fg: CanvasText;--tbw-color-accent: Highlight;--tbw-color-accent-fg: HighlightText;--tbw-color-selection: Highlight;--tbw-color-row-hover: Highlight;--tbw-focus-outline: 2px solid Highlight;--tbw-range-border-color: Highlight}tbw-grid .cell:focus,tbw-grid .cell.active-cell{outline:2px solid Highlight!important;outline-offset:-2px}tbw-grid .data-grid-row[aria-selected=true]{background:Highlight!important;color:HighlightText!important}}@media(prefers-reduced-motion:reduce){tbw-grid[data-animation-mode=reduced-motion]{--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}tbw-grid[data-animation-mode=reduced-motion] .data-grid-row[data-animating]{animation:none}}}\n')}getPlugin(e){return this.#X?.getPlugin(e)}getPluginByName(e){return this.#X?.getPluginByName(e)}requestRender(){this.#O.requestPhase(he.ROWS,"plugin:requestRender")}requestColumnsRender(){this.#O.requestPhase(he.COLUMNS,"plugin:requestColumnsRender")}requestRenderWithFocus(){this._restoreFocusAfterRender=!0,this.#O.requestPhase(he.ROWS,"plugin:requestRenderWithFocus")}updateTemplate(){c(this)}requestAfterRender(){this.#O.requestPhase(he.STYLE,"plugin:requestAfterRender")}#Ae(){this.#X=new it(this);const e=this.#s?.plugins,t=Array.isArray(e)?e:[];this.#X.attachAll(t)}#ke(){!function(e){let t=!1;for(const{name:i,styles:n}of e)Ne.has(i)||(Ne.set(i,n),t=!0);t&&Ge()}(this.#X?.getPluginStyles()??[])}#we(){const e=this.#s?.plugins,t=Array.isArray(e)?e:[];if(this.#Z===t)return;if(this.#Z&&this.#Z.length===t.length&&this.#Z.every((e,i)=>e===t[i]))return void(this.#Z=t);this.#X&&this.#X.detachAll();for(const n of this.#te.toolPanels.keys()){const e=this.#te.lightDomToolPanelIds.has(n),t=this.#te.apiToolPanelIds.has(n);if(!e&&!t){const e=this.#te.panelCleanups.get(n);e&&(e(),this.#te.panelCleanups.delete(n)),this.#te.toolPanels.delete(n)}}for(const n of this.#te.headerContents.keys()){const e=this.#te.headerContentCleanups.get(n);e&&(e(),this.#te.headerContentCleanups.delete(n)),this.#te.headerContents.delete(n)}this.#Ae(),this.#ke(),this.#Z=t,this.#Te(),this.#Le();const i=this.#N;if(this.#N=this.#X?.getAll().some(e=>e.onScroll)??!1,!i&&this.#N){const e=this.#L.querySelector(".tbw-grid-content")??this.#L.querySelector(".tbw-grid-root");this.#Me(e)}}#Ie(){this.#X?.detachAll()}#Le(){if(!this.#X)return;const e=this.#X.getToolPanels();for(const{panel:i}of e)this.#te.toolPanels.has(i.id)||this.#te.toolPanels.set(i.id,i);const t=this.#X.getHeaderContents();for(const{content:i}of t)this.#te.headerContents.has(i.id)||this.#te.headerContents.set(i.id,i)}#Pe(){const e=nt.getAdapters();if(0===e.length&&!this.__frameworkAdapter)return;const t=this.__frameworkAdapter;return i=>{if(t?.createToolPanelRenderer){const e=t.createToolPanelRenderer(i);if(e)return e}for(const t of e)if(t.createToolPanelRenderer){const e=t.createToolPanelRenderer(i);if(e)return e}}}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=0),this.hasAttribute("version")||this.setAttribute("version",nt.version),this.id||(this.id="tbw-grid-"+ ++nt.#T),this._rows=Array.isArray(this.#I)?[...this.#I]:[],this.#W&&(this.#W.abort(),this.#Q=!1),this.#W=new AbortController,this.#j&&(de(this.#j),this.#j=void 0),this.#He(),this.#P.parseLightDomColumns(this),this.#P.merge(),this.#Ae();const e=this.#s?.plugins;var t,i;this.#Z=Array.isArray(e)?e:[],this.#Le(),this.#M||(this.#De(),this.#ke(),this.#M=!0),this.#ze(),this.#j=(t=()=>{this.#Oe()},i={timeout:100},ae?requestIdleCallback(t,i):window.setTimeout(()=>{const e=Date.now();t({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-e))})},1))}disconnectedCallback(){this.#j&&(de(this.#j),this.#j=void 0),this.#B&&(clearTimeout(this.#B),this.#B=0),this.#Ie(),function(e){for(const t of e.headerContentCleanups.values())t();e.headerContentCleanups.clear();for(const t of e.panelCleanups.values())t();e.panelCleanups.clear();for(const t of e.toolbarContentCleanups.values())t();e.toolbarContentCleanups.clear();for(const t of e.toolbarContents.values())t.onDestroy?.();if(e.isPanelOpen)for(const t of e.expandedSections){const i=e.toolPanels.get(t);i?.onClose?.()}e.isPanelOpen=!1,e.expandedSections.clear(),e.toolPanels.clear(),e.headerContents.clear(),e.toolbarContents.clear(),e.lightDomHeaderContent=[],e.lightDomToolPanelIds.clear(),e.lightDomToolbarContentIds.clear(),e.lightDomContentMoved=!1}(this.#te),this.#ie.setInitialized(!1),this.#ne?.(),this.#ne=void 0,this.#re?.(),this.#re=void 0,Ve(this.#$),this.#W&&(this.#W.abort(),this.#W=void 0),this.#J?.abort(),this.#J=void 0,this.#Q=!1,this._resizeController&&this._resizeController.dispose(),this.#K&&(this.#K.disconnect(),this.#K=void 0),this.#U&&(this.#U.disconnect(),this.#U=void 0,this.#Ce=!1),B(this),this.#Fe.clear(),this.#Z=void 0;for(const e of this._rowPool)e.remove();this._rowPool.length=0,this.__rowsBodyEl=null,this.#H=!1}attributeChangedCallback(e,t,i){if("loading"===e){const e=null!==i&&"false"!==i;return void(this.loading!==e&&(this.loading=e))}if(t!==i&&i&&"null"!==i&&"undefined"!==i)if("rows"===e||"columns"===e||"grid-config"===e)try{const t=JSON.parse(i);"rows"===e?this.rows=t:"columns"===e?this.columns=t:"grid-config"===e&&(this.gridConfig=t)}catch{console.warn(`[tbw-grid] Invalid JSON for '${e}' attribute:`,i)}else"fit-mode"===e&&(this.fitMode=i)}#ze(){const e=this.#L.querySelector(".tbw-grid-content")??this.#L.querySelector(".tbw-grid-root");if(this._headerRowEl=e?.querySelector(".header-row"),this._virtualization.totalHeightEl=e?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=e?.querySelector(".rows-viewport"),this._bodyEl=e?.querySelector(".rows"),this.__rowsBodyEl=e?.querySelector(".rows-body"),this.#ie.isInitialized){Me(this.#L,this.#te),Le(this.#L,this.#s?.shell,this.#te);const e=this.#s?.shell?.toolPanel?.defaultOpen;e&&this.#te.toolPanels.has(e)&&(this.openToolPanel(),this.#te.expandedSections.add(e))}if(this.setAttribute("data-upgraded",""),this.#H=!0,this._resizeController=ge(this),this.#Se(),this.#Me(e),this.#Q)return;this.#Q=!0;const t=this.disconnectSignal;X(this,this,this.#L,t),this.#Te(),queueMicrotask(()=>this.#qe()),this.#O.requestPhase(he.FULL,"afterConnect")}#Te(){const e=this.#s.rowHeight,t=this.#X.hasRowHeightPlugin();"function"==typeof e||t?this._virtualization.variableHeights||(this._virtualization.variableHeights=!0,this._virtualization.rowHeight="number"==typeof e&&e>0?e:this._virtualization.rowHeight||28,this.#Ne(),"function"!=typeof e&&(this.#G=!0)):!t&&"function"!=typeof e&&this._virtualization.variableHeights?(this._virtualization.variableHeights=!1,this._virtualization.positionCache=null):"number"==typeof e&&e>0?(this._virtualization.rowHeight=e,this._virtualization.variableHeights=!1):requestAnimationFrame(()=>this.#Ge())}#Ge(){if(this.#X.hasExtraHeight())return;const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;const t=e.querySelectorAll(".cell");let i=0;t.forEach(e=>{const t=e.offsetHeight;t>i&&(i=t)});const n=e.getBoundingClientRect(),r=Math.max(n.height,i);r>0&&Math.abs(r-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=r,this.#O.requestPhase(he.VIRTUALIZATION,"measureRowHeight"))}#Ee(){const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;const t=e.querySelectorAll(".cell");let i=0;t.forEach(e=>{const t=e.offsetHeight;t>i&&(i=t)});const n=e.getBoundingClientRect(),r=Math.max(n.height,i);if(r>0){if(Math.abs(r-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=r),this.#Ne(),this._virtualization.totalHeightEl){const e=this.#ye(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}}#Me(e){this.#J?.abort(),this.#J=new AbortController;const t=this.#J.signal,i=e?.querySelector(".faux-vscroll"),n=e?.querySelector(".rows");if(this._virtualization.container=i??this,this.#N=this.#X?.getAll().some(e=>e.onScroll)??!1,i&&n){i.addEventListener("scroll",()=>{if(!this._virtualization.enabled&&!this.#N)return;const e=i.scrollTop,t=this._virtualization.rowHeight;if(this._rows.length<=this._virtualization.bypassThreshold)n.style.transform=`translateY(${-e}px)`;else{const i=this._virtualization.positionCache;let r,o;if(this._virtualization.variableHeights&&i&&i.length>0){r=et(i,e),-1===r&&(r=0);const n=r-r%2;o=i[n]?.offset??n*t}else{r=Math.floor(e/t);o=(r-r%2)*t}const s=-(e-o);n.style.transform=`translateY(${s}px)`}this.#q=e,this.#F||(this.#F=requestAnimationFrame(()=>{this.#F=0,null!==this.#q&&(this.#Be(this.#q),this.#q=null)}))},{passive:!0,signal:t});const e=this.#L.querySelector(".tbw-scroll-area");this.#ee=e,this._virtualization.scrollAreaEl=e,e&&this.#N&&e.addEventListener("scroll",()=>{const t=this.#Y;t.scrollTop=i.scrollTop,t.scrollLeft=e.scrollLeft,t.scrollHeight=i.scrollHeight,t.scrollWidth=e.scrollWidth,t.clientHeight=i.clientHeight,t.clientWidth=e.clientWidth,this.#X?.onScroll(t)},{passive:!0,signal:t});const r=this.#L.querySelector(".tbw-grid-content"),o=this.#ee;r&&(r.addEventListener("wheel",e=>{const t=e.shiftKey||Math.abs(e.deltaX)>Math.abs(e.deltaY);if(t&&o){const t=e.shiftKey?e.deltaY:e.deltaX,{scrollLeft:i,scrollWidth:n,clientWidth:r}=o;(t>0&&i<n-r||t<0&&i>0)&&(e.preventDefault(),o.scrollLeft+=t)}else if(!t){const{scrollTop:t,scrollHeight:n,clientHeight:r}=i;(e.deltaY>0&&t<n-r||e.deltaY<0&&t>0)&&(e.preventDefault(),i.scrollTop+=e.deltaY)}},{passive:!1,signal:t}),We(r,this.#$,{fauxScrollbar:i,scrollArea:o},t))}var r,o,s;this._bodyEl&&(r=this,o=this._bodyEl,s=t,o.addEventListener("mousedown",e=>{const t=e.target.closest(".cell[data-col]");t&&(t.classList.contains("editing")||(e.preventDefault(),j(r,t)))},{signal:s}),o.addEventListener("click",e=>{const t=e.target.closest(".data-grid-row");if(t&&W(r,e,t),!document.activeElement?.closest(".cell.editing")){const t=e.target.closest("tbw-grid");t&&t.focus({preventScroll:!0})}},{signal:s}),o.addEventListener("dblclick",e=>{const t=e.target.closest(".data-grid-row");t&&W(r,e,t)},{signal:s})),this.#K?.disconnect(),this._virtualization.viewportEl&&(this.#K=new ResizeObserver(()=>{this.#Ve(),this.#O.requestPhase(he.VIRTUALIZATION,"resize-observer")}),this.#K.observe(this._virtualization.viewportEl)),this.#L.addEventListener("focusin",()=>{this.dataset.hasFocus=""},{signal:t}),this.#L.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.#L.contains(t)||this.#$e(t))||delete this.dataset.hasFocus},{signal:t})}#Ce=!1;#xe(){if(this.#Ce)return;const e=this._bodyEl?.querySelector(".data-grid-row");e&&(this.#Ce=!0,this.#U?.disconnect(),this.#U=new ResizeObserver(()=>{this.#Ge()}),this.#U.observe(e))}addEventListener(e,t,i){super.addEventListener(e,t,i)}removeEventListener(e,t,i){super.removeEventListener(e,t,i)}#Re(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}#qe(){const e=this._bodyEl?.querySelectorAll(".data-grid-row");e?.forEach((e,t)=>{const i=t===this._focusRow;e.setAttribute("aria-selected",String(i)),e.querySelectorAll(".cell").forEach((e,t)=>{e.setAttribute("aria-selected",String(i&&t===this._focusCol))})})}#he(e){this.#z[e]=!0,this.#D||(this.#D=!0,queueMicrotask(()=>this.#We()))}#We(){if(!this.#D||!this.#H)return void(this.#D=!1);const e=this.#z;if(this.#D=!1,this.#z={rows:!1,columns:!1,gridConfig:!1,fitMode:!1},e.gridConfig)return this.#Ke(),void(e.rows&&this.#Ue());e.columns&&this.#je(),e.rows&&this.#Ue(),e.fitMode&&this.#Ye()}#Ue(){this._rows=Array.isArray(this.#I)?[...this.#I]:[],this.#Xe(),this.#O.requestPhase(he.ROWS,"applyRowsUpdate")}#Xe(){this.#de.clear();const e=this.#s.getRowId;this._rows.forEach((t,i)=>{const n=this.#Ze(t,e);void 0!==n&&this.#de.set(n,{row:t,index:i})})}#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}#Qe(e,t){const i=this.#Ze(e,t);if(void 0===i)throw new Error('[tbw-grid] Cannot determine row ID. Configure getRowId in gridConfig or ensure rows have an "id" property.');return i}#je(){B(this),this.#P.merge(),this.#Se()}#Ye(){this.#P.merge();"fixed"===this.#s.fitMode?(this.__didInitialAutoSize=!1,l(this)):(this._columns.forEach(e=>{!e.__userResized&&e.__autoSized&&delete e.width}),c(this))}#Ke(){Ae(this,this.#te),ke(this,this.#te);const e=!!this.#L.querySelector(".has-shell"),t=!!this.#L.querySelector(".tbw-tool-panel"),i=this.#L.querySelectorAll(".tbw-accordion-section").length;this.#P.parseLightDomColumns(this),this.#P.merge(),this.#we(),Te(this,this.#te,this.#Pe()),this.#P.markSourcesChanged(),this.#P.merge();const n=_e(this.#s?.shell),r=(this.#s?.shell?.toolPanels?.length??0)>0,o=this.#s?.shell?.toolPanels?.length??0;if(e!==n||!t&&r||t&&o!==i)return He(this.#te),this.#De(),this.#ke(),this.#ze(),void this.#Xe();e&&this.#Je(),this.#Xe(),this.#O.requestPhase(he.COLUMNS,"applyGridConfigUpdate")}#Je(){const e=this.#L.querySelector(".tbw-shell-header");if(!e)return;const t=this.#s.shell?.header?.title??this.#te.lightDomTitle;let i=e.querySelector(".tbw-shell-title");t?(i||(i=document.createElement("h2"),i.className="tbw-shell-title",i.setAttribute("part","shell-title"),e.insertBefore(i,e.firstChild)),i.textContent=t):i&&i.remove()}#be(){if(this.__rowRenderEpoch++,this.#X){const e=this.#ce.length>0?this.#ce:this._columns,t=e.filter(e=>!e.hidden),i=e.filter(e=>e.hidden),n=this.#X.processColumns([...t]);if(n!==t){const r=new Set(n.map(e=>e.field));!t.some(e=>r.has(e.field))&&n.length>0?this._columns=[...n,...i]:this._columns=this.#et(e,n,i)}else this._columns=[...e]}}#et(e,t,i){if(0===i.length)return t;const n=new Map;for(const l of t)n.set(l.field,l);const r=new Set(e.map(e=>e.field)),o=[];for(const l of t)r.has(l.field)||o.push(l);const s=[];for(const l of e){const e=n.get(l.field);e?s.push(e):l.hidden&&s.push(l)}return s.push(...o),s}#ve(){B(this);const e=function(e,t){if(!e._sortState)return t;e.__originalOrder=[...t];const i=(e.effectiveConfig?.sortHandler??Q)(t,e._sortState,e._columns);return i&&"function"==typeof i.then?t:i}(this,Array.isArray(this.#I)?[...this.#I]:[]),t=this.#X?.processRows(e)??e;this._rows=t,this.#Xe(),this._virtualization.variableHeights&&this.#Ne()}#_e(e){const t={...i,...e.animation},n=t.mode??"reduced-motion";let r=1;!1===n||"off"===n?r=0:!0!==n&&"on"!==n||(r=1),this.style.setProperty("--tbw-animation-duration",`${t.duration}ms`),this.style.setProperty("--tbw-animation-easing",t.easing??"ease-out"),this.style.setProperty("--tbw-animation-enabled",String(r)),this.dataset.animationMode="boolean"==typeof n?n?"on":"off":n}#tt(e,t,i=this.__rowRenderEpoch){if(this.#V||(this.#V=(e,t,i)=>this.#X?.renderRow(e,t,i)??!1),function(e,t,i,n,r){const o=Math.max(0,i-t),s=e._bodyEl,l=e._visibleColumns,a=l.length;let d=e.__cachedHeaderRowCount;for(void 0===d&&(d=e.querySelector(".header-group-row")?2:1,e.__cachedHeaderRowCount=d);e._rowPool.length<o;){const t=G();e._rowPool.push(t)}if(e._rowPool.length>o){for(let t=o;t<e._rowPool.length;t++){const i=e._rowPool[t];i.parentNode===s&&i.remove()}e._rowPool.length=o}const c=r&&!1!==e.__hasRenderRowPlugins,h=e._hasAfterRowRenderHook?.()??!1;for(let g=0;g<o;g++){const i=t+g,o=e._rows[i],p=e._rowPool[g];if(p.setAttribute("aria-rowindex",String(i+d+1)),c&&r(o,p,i)){p.__epoch=n,p.__rowDataRef=o,p.parentNode!==s&&s.appendChild(p);continue}const f=p.__epoch,w=p.__rowDataRef;let m=p.children.length;m>a&&p.lastElementChild?.classList.contains("tbw-row-loading-overlay")&&m--;const b=f===n&&m===a,v=w!==o,y=!!e._isGridEditMode;let C=!1;if(b&&v)for(let e=0;e<a;e++)if(l[e].externalView&&!p.querySelector(`.cell[data-col="${e}"] [data-external-view]`)){C=!0;break}if(!b||C){const t=z(p),r=y||e._activeEditRows===i;t&&!r?(p.__isCustomRow&&(p.className="data-grid-row",p.setAttribute("role","row"),p.__isCustomRow=!1),O(p),$(e,p,o,i),p.__epoch=n,p.__rowDataRef=o):t&&r?(V(e,p,o,i),p.__rowDataRef=o):(p.__isCustomRow&&(p.className="data-grid-row",p.setAttribute("role","row"),p.__isCustomRow=!1),$(e,p,o,i),p.__epoch=n,p.__rowDataRef=o)}else if(v){const t=z(p),r=y||e._activeEditRows===i;t&&!r?(O(p),$(e,p,o,i),p.__epoch=n,p.__rowDataRef=o):(V(e,p,o,i),p.__rowDataRef=o)}else{const t=z(p),r=y||e._activeEditRows===i;t&&!r?(O(p),$(e,p,o,i),p.__epoch=n,p.__rowDataRef=o):V(e,p,o,i)}let x=!1;const E=e.changedRowIds;if(E&&E.length>0)try{const t=e.getRowId?.(o);t&&(x=E.includes(t))}catch{}x!==p.classList.contains("changed")&&p.classList.toggle("changed",x);const R=e.effectiveConfig?.rowClass;if(R){const e=p.getAttribute("data-dynamic-classes");e&&e.split(" ").forEach(e=>e&&p.classList.remove(e));try{const e=R(o);if(e&&e.length>0){const t=e.filter(e=>e&&"string"==typeof e);t.forEach(e=>p.classList.add(e)),p.setAttribute("data-dynamic-classes",t.join(" "))}else p.removeAttribute("data-dynamic-classes")}catch(u){console.warn("[tbw-grid] rowClass callback error:",u),p.removeAttribute("data-dynamic-classes")}}h&&e._afterRowRender?.({row:o,rowIndex:i,rowElement:p}),p.parentNode!==s&&s.appendChild(p)}}(this,e,t,i,this.#V),this.#se.size>0)for(const n of this.#se)this.#ge(n,!0)}#it={rowCount:-1,colCount:-1,ariaLabel:void 0,ariaDescribedBy:void 0};#nt(e,t){!function(e,t,i,n,r){if(n===e.rowCount&&r===e.colCount)return!1;const o=e.rowCount;e.rowCount=n,e.colCount=r,t&&(t.setAttribute("aria-rowcount",String(n)),t.setAttribute("aria-colcount",String(r))),n!==o&&i&&(n>0?i.setAttribute("role","rowgroup"):i.removeAttribute("role"))}(this.#it,this.__rowsBodyEl,this._bodyEl,e,t)}#me(){!function(e,t,i,n){if(!t)return!1;let r=!1;const o=function(e,t){const i=e?.gridAriaLabel;return i||(e?.shell?.header?.title??t?.lightDomTitle??void 0)}(i,n);o!==e.ariaLabel&&(e.ariaLabel=o,o?t.setAttribute("aria-label",o):t.removeAttribute("aria-label"),r=!0);const s=i?.gridAriaDescribedBy;s!==e.ariaDescribedBy&&(e.ariaDescribedBy=s,s?t.setAttribute("aria-describedby",s):t.removeAttribute("aria-describedby"),r=!0)}(this.#it,this.__rowsBodyEl,this.#s,this.#te)}#ue(){const e=this.querySelector(".tbw-grid-root");var t;e&&(this.#oe?(this.#ae||(this.#ae=function(e){const t=document.createElement("div");return t.className="tbw-loading-overlay",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.appendChild(ce("large",e)),t}(this.#s?.loadingRenderer)),function(e,t){e.appendChild(t)}(e,this.#ae)):(t=this.#ae,t?.remove()))}#ge(e,t){const i=this.#de.get(e);if(!i)return;const n=this.findRenderedRowElement?.(i.index);n&&function(e,t){if(t){if(e.classList.add("tbw-row-loading"),e.setAttribute("aria-busy","true"),!e.querySelector(".tbw-row-loading-overlay")){const t=document.createElement("div");t.className="tbw-row-loading-overlay",t.setAttribute("aria-hidden","true");const i=document.createElement("div");i.className="tbw-row-loading-spinner",t.appendChild(i),e.appendChild(t)}}else e.classList.remove("tbw-row-loading"),e.removeAttribute("aria-busy"),e.querySelector(".tbw-row-loading-overlay")?.remove()}(n,t)}#pe(e,t,i){const n=this.#de.get(e);if(!n)return;const r=this.findRenderedRowElement?.(n.index);if(!r)return;const o=this._visibleColumns.findIndex(e=>e.field===t);if(o<0)return;const s=r.children[o];s&&function(e,t){t?(e.classList.add("tbw-cell-loading"),e.setAttribute("aria-busy","true")):(e.classList.remove("tbw-cell-loading"),e.removeAttribute("aria-busy"))}(s,i)}#Se(){if(this.isConnected&&this._headerRowEl&&this._bodyEl){if(this.#P.parseLightDomColumns(this),this.#h){const e=this.#h;this.#h=void 0,this.#P.merge();const t=this.#X?.getAll()??[];this.#P.applyState(e,t)}this._bodyEl&&(this._bodyEl.style.display="",this._bodyEl.style.gridTemplateColumns=""),this.#O.requestPhase(he.FULL,"setup")}}#Be(e){let t=0,i=0,n=0,r=0,o=0;if(this.#N){const e=this._virtualization.container,s=this.#ee;t=s?.scrollLeft??0,i=e?.scrollHeight??0,n=s?.scrollWidth??0,r=e?.clientHeight??0,o=s?.clientWidth??0}if(this.refreshVirtualWindow(!1)&&this.#X?.onScrollRender(),this._virtualization.variableHeights&&(this.#B&&clearTimeout(this.#B),this.#B=window.setTimeout(()=>{this.#B=0,this.#rt(this._virtualization.start,this._virtualization.end)},100)),this.#N){const s=this.#Y;s.scrollTop=e,s.scrollLeft=t,s.scrollHeight=i,s.scrollWidth=n,s.clientHeight=r,s.clientWidth=o,this.#X?.onScroll(s)}}findHeaderRow(){return this.#L.querySelector(".header-row")}findRenderedRowElement(e){return Array.from(this._bodyEl.querySelectorAll(".data-grid-row")).find(t=>{const i=t.querySelector(".cell[data-row]");return i&&Number(i.getAttribute("data-row"))===e})||null}_dispatchCellClick(e,t,i,n){const r=this._rows[t],o=this._visibleColumns[i];if(!r||!o)return!1;const s=o.field,l=r[s],a=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,composed:!0,detail:{rowIndex:t,colIndex:i,column:o,field:s,value:l,row:r,cellEl:n,trigger:"pointer",originalEvent:e}});if(this.dispatchEvent(a),a.defaultPrevented)return!0;const d={row:r,rowIndex:t,colIndex:i,column:o,field:s,value:l,cellEl:n,originalEvent:e},c=this.#X?.onCellClick(d)??!1;return this.#Re("cell-click",d),c}_dispatchRowClick(e,t,i,n){if(!i)return!1;const r={rowIndex:t,row:i,rowEl:n,originalEvent:e},o=this.#X?.onRowClick(r)??!1;return this.#Re("row-click",r),o}_dispatchHeaderClick(e,t,i){if(!t)return!1;const n={colIndex:this._columns.indexOf(t),field:t.field,column:t,headerEl:i,originalEvent:e};return this.#X?.onHeaderClick(n)??!1}_dispatchKeyDown(e){return this.#X?.onKeyDown(e)??!1}_getHorizontalScrollOffsets(e,t){return this.#X?.getHorizontalScrollOffsets(e,t)??{left:0,right:0}}queryPlugins(e){return this.#X?.queryPlugins(e)??[]}query(e,t){return this.#X?.queryPlugins({type:e,context:t})??[]}_dispatchCellMouseDown(e){return this.#X?.onCellMouseDown(e)??!1}_dispatchCellMouseMove(e){this.#X?.onCellMouseMove(e)}_dispatchCellMouseUp(e){this.#X?.onCellMouseUp(e)}_afterCellRender(e){this.#X?.afterCellRender(e)}_hasAfterCellRenderHook(){return this.#X?.hasAfterCellRenderHook()??!1}_afterRowRender(e){this.#X?.afterRowRender(e)}_hasAfterRowRenderHook(){return this.#X?.hasAfterRowRenderHook()??!1}async ready(){return this.#E}async forceLayout(){return this.#O.requestPhase(he.FULL,"forceLayout"),this.#O.whenReady()}async getConfig(){return Object.freeze({...this.#s||{}})}getRowId(e){return this.#Qe(e,this.#s.getRowId)}getRow(e){return this.#de.get(e)?.row}_getRowEntry(e){return this.#de.get(e)}updateRow(e,t,i="api"){const n=this.#de.get(e);if(!n)throw new Error(`[tbw-grid] Row with ID "${e}" not found. Ensure the row exists and getRowId is correctly configured.`);const{row:r,index:o}=n,s=[];for(const[l,a]of Object.entries(t)){const e=r[l];e!==a&&(s.push({field:l,oldValue:e,newValue:a}),r[l]=a)}for(const{field:l,oldValue:a,newValue:d}of s)this.#Re("cell-change",{row:r,rowId:e,rowIndex:o,field:l,oldValue:a,newValue:d,changes:t,source:i});s.length>0&&(B(this),this.#O.requestPhase(he.VIRTUALIZATION,"updateRow"))}updateRows(e,t="api"){let i=!1;for(const{id:n,changes:r}of e){const e=this.#de.get(n);if(!e)throw new Error(`[tbw-grid] Row with ID "${n}" not found. Ensure the row exists and getRowId is correctly configured.`);const{row:o,index:s}=e;for(const[l,a]of Object.entries(r)){const e=o[l];e!==a&&(i=!0,o[l]=a,this.#Re("cell-change",{row:o,rowId:n,rowIndex:s,field:l,oldValue:e,newValue:a,changes:r,source:t}))}}i&&(B(this),this.#O.requestPhase(he.VIRTUALIZATION,"updateRows"))}animateRow(e,t){return be(this,e,t)}animateRows(e,t){return function(e,t,i){return Promise.all(t.map(t=>be(e,t,i))).then(e=>e.filter(Boolean).length)}(this,e,t)}animateRowById(e,t){return function(e,t,i){const n=e._rows??[],r=e.getRowId;if(!r)return Promise.resolve(!1);const o=n.findIndex(e=>{if(null==e)return!1;try{return r(e)===t}catch{return!1}});return o<0?Promise.resolve(!1):be(e,o,i)}(this,e,t)}async insertRow(e,t,i=!0){const n=Math.max(0,Math.min(e,this._rows.length));this.#I=[...this.#I,t];const r=[...this._rows];r.splice(n,0,t),this._rows=r,this._sortState&&(this.__originalOrder=[...this.__originalOrder,t]),B(this),this.#Xe(),this.__rowRenderEpoch++;for(const o of this._rowPool)o.__epoch=-1;this.refreshVirtualWindow(!0),this.#X?.emitPluginEvent("row-inserted",{row:t,index:n}),i&&(await new Promise(e=>requestAnimationFrame(()=>e())),await this.animateRow(n,"insert"))}async removeRow(e,t=!0){const i=this._rows[e];if(!i)return;t&&await this.animateRow(e,"remove");const n=this._rows.indexOf(i);if(n<0)return i;const r=[...this._rows];r.splice(n,1),this._rows=r;const o=this.#I.indexOf(i);if(o>=0){const e=[...this.#I];e.splice(o,1),this.#I=e}if(this._sortState){const e=this.__originalOrder.indexOf(i);if(e>=0){const t=[...this.__originalOrder];t.splice(e,1),this.__originalOrder=t}}B(this),this.#Xe(),this.__rowRenderEpoch++;for(const s of this._rowPool)s.__epoch=-1;return this.refreshVirtualWindow(!0),t&&requestAnimationFrame(()=>{this.querySelectorAll('[data-animating="remove"]').forEach(e=>{e.removeAttribute("data-animating")})}),i}suspendProcessing(){}focusCell(e,t){const i=this._rows.length-1;if(i<0)return;let n;if("string"==typeof t){if(n=this._visibleColumns.findIndex(e=>e.field===t),n<0)return}else n=t;const r=this._visibleColumns.length-1;r<0||(this._focusRow=Math.max(0,Math.min(e,i)),this._focusCol=Math.max(0,Math.min(n,r)),K(this))}get focusedCell(){if(0===this._rows.length||0===this._visibleColumns.length)return null;const e=this._visibleColumns[this._focusCol];return{rowIndex:this._focusRow,colIndex:this._focusCol,field:e?.field??""}}scrollToRow(e,t){const i=this._virtualization;if(!i.enabled)return;const n=i.container;if(!n)return;const r=this._rows.length;if(0===r)return;const o=Math.max(0,Math.min(e,r-1)),s=t?.align??"nearest",l=t?.behavior??"instant";let a,d;const c=i.positionCache;i.variableHeights&&c&&c.length>o?(a=c[o].offset,d=c[o].height):(a=o*i.rowHeight,d=i.rowHeight);const h=i.viewportEl?.clientHeight??n.clientHeight??0;if(h<=0)return;const u=n.scrollTop,g=a+d,p=u+h;let f;switch(s){case"start":f=a;break;case"center":f=a-h/2+d/2;break;case"end":f=g-h;break;default:if(a>=u&&g<=p)return;f=a<u?a:g-h}f=Math.max(0,f),"smooth"===l?n.scrollTo({top:f,behavior:"smooth"}):n.scrollTop=f}scrollToRowById(e,t){const i=this.#de.get(e);i&&this.scrollToRow(i.index,t)}setColumnVisible(e,t){const i=this.#P.setColumnVisible(e,t);return i&&this.requestStateChange(),i}toggleColumnVisibility(e){const t=this.#P.toggleColumnVisibility(e);return t&&this.requestStateChange(),t}isColumnVisible(e){return this.#P.isColumnVisible(e)}showAllColumns(){this.#P.showAllColumns(),this.requestStateChange()}getAllColumns(){return this.#P.getAllColumns()}setColumnOrder(e){this.#P.setColumnOrder(e),this.requestStateChange()}getColumnOrder(){return this.#P.getColumnOrder()}getColumnState(){const e=this.#X?.getAll()??[];return this.#P.collectState(e)}set columnState(e){e&&(this.#h=e,this.#P.initialColumnState=e,this.#M&&this.#ot(e))}get columnState(){return this.getColumnState()}#ot(e){const t=this.#X?.getAll()??[];this.#P.applyState(e,t),this.#Se()}requestStateChange(){const e=this.#X?.getAll()??[];this.#P.requestStateChange(e)}resetColumnState(){this.#h=void 0,this.__originalOrder=[];const e=this.#X?.getAll()??[];this.#P.resetState(e),this.#P.merge(),this.#Se()}get isToolPanelOpen(){return this.#ie.isPanelOpen}get defaultRowHeight(){return this._virtualization.rowHeight}get expandedToolPanelSections(){return this.#ie.expandedSections}openToolPanel(){this.#ie.openToolPanel()}closeToolPanel(){this.#ie.closeToolPanel()}toggleToolPanel(){this.#ie.toggleToolPanel()}toggleToolPanelSection(e){this.#ie.toggleToolPanelSection(e)}getToolPanels(){return this.#ie.getToolPanels()}registerToolPanel(e){this.#te.apiToolPanelIds.add(e.id),this.#ie.registerToolPanel(e)}unregisterToolPanel(e){this.#te.apiToolPanelIds.delete(e),this.#ie.unregisterToolPanel(e)}getHeaderContents(){return this.#ie.getHeaderContents()}registerHeaderContent(e){this.#ie.registerHeaderContent(e)}unregisterHeaderContent(e){this.#ie.unregisterHeaderContent(e)}getToolbarContents(){return this.#ie.getToolbarContents()}registerToolbarContent(e){this.#ie.registerToolbarContent(e)}unregisterToolbarContent(e){this.#ie.unregisterToolbarContent(e)}#st=!1;refreshShellHeader(){this.#st||(this.#st=!0,queueMicrotask(()=>{this.#st=!1,this.isConnected&&(this.#He(),this.#P.markSourcesChanged(),this.#P.merge(),He(this.#te),this.#De(),this.#ke(),this.#lt())}))}#lt(){const e=this.#L.querySelector(".tbw-grid-content")??this.#L.querySelector(".tbw-grid-root");if(this._headerRowEl=e?.querySelector(".header-row"),this._virtualization.totalHeightEl=e?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=e?.querySelector(".rows-viewport"),this._bodyEl=e?.querySelector(".rows"),this.__rowsBodyEl=e?.querySelector(".rows-body"),this.#ie.isInitialized){Me(this.#L,this.#te),Le(this.#L,this.#s?.shell,this.#te);const e=this.#s?.shell?.toolPanel?.defaultOpen;e&&this.#te.toolPanels.has(e)&&(this.openToolPanel(),this.#te.expandedSections.add(e))}this._resizeController=ge(this),this.#Me(e),this.#O.requestPhase(he.COLUMNS,"shellRefresh")}#Fe=new Map;registerStyles(e,t){let i=this.#Fe.get(e);i||(i=new CSSStyleSheet,this.#Fe.set(e,i)),i.replaceSync(t),this.#at()}unregisterStyles(e){this.#Fe.delete(e)&&this.#at()}getRegisteredStyles(){return Array.from(this.#Fe.keys())}#at(){const e=Array.from(this.#Fe.values()),t=document.adoptedStyleSheets.filter(e=>!Array.from(this.#Fe.values()).includes(e));document.adoptedStyleSheets=[...t,...e]}#dt=new Set;#ct=new Map;registerExternalFocusContainer(e){if(this.#dt.has(e))return;this.#dt.add(e);const t=new AbortController,i=t.signal;e.addEventListener("focusin",()=>{this.dataset.hasFocus=""},{signal:i}),e.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&this.containsFocus(t)||delete this.dataset.hasFocus},{signal:i}),this.#ct.set(e,()=>t.abort())}unregisterExternalFocusContainer(e){this.#dt.delete(e);const t=this.#ct.get(e);t&&(t(),this.#ct.delete(e))}containsFocus(e){const t=e??document.activeElement;return!!t&&(!!this.contains(t)||this.#$e(t))}#$e(e){for(const t of this.#dt)if(t.contains(e))return!0;return!1}#He(){Ae(this,this.#te),ke(this,this.#te),Te(this,this.#te,this.#Pe())}#ht(){const e=this.#L.querySelector(".tbw-shell-header");if(!e)return;He(this.#te);const t=function(e,t,i="☰"){const n=e?.header?.title??t.lightDomTitle??"",r=!!n,o=Se(i),s=e?.header?.toolbarContents??[],l=[...t.toolbarContents.values()],a=new Set(s.map(e=>e.id)),d=[...s];for(const w of l)a.has(w.id)||d.push(w);const c=d.length>0,h=t.toolPanels.size>0,u=c&&h,g=[...d].sort((e,t)=>(e.order??0)-(t.order??0));let p="";for(const w of g)p+=`<div class="tbw-toolbar-content-slot" data-toolbar-content="${w.id}"></div>`;if(u&&(p+='<div class="tbw-toolbar-separator"></div>'),h){const e=t.isPanelOpen;p+=`<button class="${e?"tbw-toolbar-btn active":"tbw-toolbar-btn"}" data-panel-toggle title="Settings" aria-label="Toggle settings panel" aria-pressed="${e}" aria-controls="tbw-tool-panel">${o}</button>`}return`\n <div class="tbw-shell-header" part="shell-header" role="presentation">\n ${r?`<div class="tbw-shell-title">${f=n,f&&"string"==typeof f?f.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"):""}</div>`:""}\n <div class="tbw-shell-content" part="shell-content" role="presentation" data-light-dom-header-content></div>\n <div class="tbw-shell-toolbar" part="shell-toolbar" role="presentation">\n ${p}\n </div>\n </div>\n `;var f}(this.#s.shell,this.#te,this.#s.icons?.toolPanel),i=document.createElement("div");i.innerHTML=t;const n=i.firstElementChild;n&&(e.replaceWith(n),this.#ut(),Le(this.#L,this.#s?.shell,this.#te))}#Oe(){const e=()=>{const e=this.#te.lightDomTitle,t=this.#te.hasToolButtonsContainer;this.#He();const i=this.#te.lightDomTitle,n=this.#te.hasToolButtonsContainer;(i&&!e||n&&!t)&&(this.#P.markSourcesChanged(),this.#P.merge(),this.#ht())},t=()=>{this.__lightDomColumnsCache=void 0,this.#Se()};this.#P.registerLightDomHandler("tbw-grid-header",e),this.#P.registerLightDomHandler("tbw-grid-tool-buttons",e),this.#P.registerLightDomHandler("tbw-grid-tool-panel",e),this.#P.registerLightDomHandler("tbw-grid-column",t),this.#P.registerLightDomHandler("tbw-grid-detail",t),this.#P.observeLightDOM(this)}refreshColumns(){this.__lightDomColumnsCache=void 0,B(this),this.#P.parseLightDomColumns(this);const e=this.#te.lightDomTitle,t=this.#te.hasToolButtonsContainer;this.#He();const i=this.#te.lightDomTitle,n=this.#te.hasToolButtonsContainer;(i&&!e||n&&!t)&&(this.#P.markSourcesChanged(),this.#P.merge(),this.#ht()),this.#O.requestPhase(he.COLUMNS,"refreshColumns")}#Ve(){const e=this._virtualization.container,t=this._virtualization.viewportEl??e;t&&(this._virtualization.cachedViewportHeight=t.clientHeight),e&&(this._virtualization.cachedFauxHeight=e.clientHeight);const i=this._virtualization.scrollAreaEl;i&&(this._virtualization.cachedScrollAreaHeight=i.clientHeight)}#ye(e,t=!1){const i=this._virtualization;let n,r,o;if(t){const e=i.container??this,t=i.viewportEl??e,s=i.scrollAreaEl;n=e.clientHeight,r=t.clientHeight,o=s?s.clientHeight:n,i.cachedFauxHeight=n,i.cachedViewportHeight=r,i.cachedScrollAreaHeight=o}else n=i.cachedFauxHeight,r=i.cachedViewportHeight,o=i.cachedScrollAreaHeight||n;const s=o-r,l=Math.max(0,n-o);let a,d=0;i.variableHeights&&i.positionCache?a=function(e){if(0===e.length)return 0;const t=e[e.length-1];return t.offset+t.height}(i.positionCache):(a=e*i.rowHeight,d=this.#X?.getExtraHeight()??0);return a+s+d+l}#Ne(){if(!this._virtualization.variableHeights)return;const e=this._rows,t=this._virtualization.rowHeight||28,i=this.#s.rowHeight,n=this.#s.getRowId,r=n?e=>n(e):void 0;this._virtualization.positionCache=function(e,t,i,n,r){const o=new Array(e.length);let s=0;for(let l=0;l<e.length;l++){const a=e[l];let d=r?.(a,l),c=void 0!==d;void 0===d&&(d=Qe(t,a,n.rowId),c=void 0!==d),void 0===d&&(d=i,c=!1),o[l]={offset:s,height:d,measured:c},s+=d}return o}(e,this._virtualization.heightCache,t,{rowId:r},(e,t)=>{const n=this.#X?.getRowHeight?.(e,t);if(void 0!==n)return n;if(i){const n=i(e,t);if(void 0!==n&&n>0)return n}});const o=function(e,t,i,n){let r=0,o=0;for(let s=0;s<e.length;s++){const i=e[s];if(i.measured){const e=n?.(t[s],s);void 0===e&&(o+=i.height,r++)}}return{measuredCount:r,averageHeight:r>0?o/r:i}}(this._virtualization.positionCache,e,t,(e,t)=>this.#X?.getRowHeight?.(e,t));this._virtualization.measuredCount=o.measuredCount,o.measuredCount>0&&(this._virtualization.averageHeight=o.averageHeight)}invalidateRowHeight(e,t){if(!this._virtualization.variableHeights)return;if(!this._virtualization.positionCache)return;if(e<0||e>=this._rows.length)return;const i=this._virtualization.positionCache,n=this._rows[e];let r=t;void 0===r&&(r=this.#X?.getRowHeight?.(n,e)),void 0===r&&(r=this._virtualization.rowHeight);const o=i[e];if(o&&!(Math.abs(o.height-r)<1)&&(Je(i,e,r),this._virtualization.totalHeightEl)){const e=this.#ye(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}#rt(e,t){if(!this._virtualization.variableHeights)return;if(!this._virtualization.positionCache)return;if(!this._bodyEl)return;const i=this._bodyEl.querySelectorAll(".data-grid-row"),n=this.#s.getRowId,r=tt({positionCache:this._virtualization.positionCache,heightCache:this._virtualization.heightCache,rows:this._rows,defaultHeight:this._virtualization.rowHeight,start:e,end:t,getPluginHeight:(e,t)=>this.#X?.getRowHeight?.(e,t),getRowId:n?e=>n(e):void 0},i);if(r.hasChanges&&(this._virtualization.measuredCount=r.measuredCount,this._virtualization.averageHeight=r.averageHeight,this._virtualization.totalHeightEl)){const e=this.#ye(this._rows.length);this._virtualization.totalHeightEl.style.height=`${e}px`}}refreshVirtualWindow(e=!1,t=!1){if(!this._bodyEl)return!1;const i=this._rows.length;if(!this._virtualization.enabled)return this.#tt(0,i),t||this.#X?.afterRender(),!0;if(this._rows.length<=this._virtualization.bypassThreshold)return this._virtualization.start=0,this._virtualization.end=i,e&&(this._bodyEl.style.transform="translateY(0px)"),this.#tt(0,i,this.__rowRenderEpoch),e&&this._virtualization.totalHeightEl&&(this._virtualization.totalHeightEl.style.height=`${this.#ye(i,!0)}px`),this.#nt(i,this._visibleColumns.length),t||this.#X?.afterRender(),!0;const n=this._virtualization.container??this,r=this._virtualization.viewportEl??n,o=e?this._virtualization.cachedViewportHeight=r.clientHeight:this._virtualization.cachedViewportHeight||(this._virtualization.cachedViewportHeight=r.clientHeight),s=this._virtualization.rowHeight,l=n.scrollTop;let a;const d=this._virtualization.positionCache;if(this._virtualization.variableHeights&&d&&d.length>0)a=et(d,l),-1===a&&(a=0);else{a=Math.floor(l/s);let e=0;const t=10;for(;e<t;){const t=this.#X?.getExtraHeightBefore?.(a)??0,i=Math.floor((l-t)/s);if(i>=a||i<0)break;a=i,e++}}a-=a%2,a<0&&(a=0);const c=this.#X?.adjustVirtualStart(a,l,s);let h;if(void 0!==c&&c<a&&(a=c,a-=a%2,a<0&&(a=0)),this._virtualization.variableHeights&&d&&d.length>0){const e=o+3*s;let t=0;for(h=a;h<i&&t<e;)t+=d[h].height,h++;const n=Math.ceil(o/s)+3;h-a<n&&(h=Math.min(a+n,i))}else{h=a+(Math.ceil(o/s)+3)}h>i&&(h=i);const u=this._virtualization.start,g=this._virtualization.end;if(!e&&a===u&&h===g)return!1;this._virtualization.start=a,this._virtualization.end=h;const p=e?this._virtualization.cachedFauxHeight=n.clientHeight:this._virtualization.cachedFauxHeight||(this._virtualization.cachedFauxHeight=n.clientHeight);if(e){const e=this._virtualization.scrollAreaEl;e&&(this._virtualization.cachedScrollAreaHeight=e.clientHeight)}if(0===p&&o>0)return this.#O.requestPhase(he.VIRTUALIZATION,"stale-refs-retry"),!1;if(e&&this._virtualization.totalHeightEl){const e=this.#ye(i);this._virtualization.totalHeightEl.style.height=`${e}px`}let f;if(this._virtualization.variableHeights&&d&&d[a])f=d[a].offset;else{f=a*s+(this.#X?.getExtraHeightBefore?.(a)??0)}const w=-(l-f);return this._bodyEl.style.transform=`translateY(${w}px)`,this.#tt(a,h,this.__rowRenderEpoch),e&&this._virtualization.variableHeights&&this.#rt(a,h),this.#nt(i,this._visibleColumns.length),e&&!t&&(this.#X?.afterRender(),queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const e=this.#ye(i);0===this._virtualization.cachedFauxHeight&&this._virtualization.cachedViewportHeight>0||(this._virtualization.totalHeightEl.style.height=`${e}px`)})),!0}#De(){this.#He(),this.#P.markSourcesChanged(),this.#P.merge();const e=this.#s?.shell;Oe(this.#L,e,{isPanelOpen:this.#te.isPanelOpen,expandedSections:this.#te.expandedSections},this.#s?.icons)&&(this.#ut(),this.#ie.setInitialized(!0))}#ut(){!function(e,t,i,n){const r=e.querySelector(".tbw-shell-toolbar");r&&r.addEventListener("click",e=>{e.target.closest("[data-panel-toggle]")&&n.onPanelToggle()});const o=e.querySelector(".tbw-accordion");o&&o.addEventListener("click",e=>{const t=e.target.closest(".tbw-accordion-header");if(t){const e=t.closest("[data-section]"),i=e?.getAttribute("data-section");i&&n.onSectionToggle(i)}})}(this.#L,this.#s,this.#te,{onPanelToggle:()=>this.toggleToolPanel(),onSectionToggle:e=>this.toggleToolPanelSection(e)}),this.#ne?.(),this.#ne=function(e,t,i){const n=e.querySelector(".tbw-tool-panel"),r=e.querySelector("[data-resize-handle]"),o=e.querySelector(".tbw-shell-body");if(!n||!r||!o)return()=>{};const s=t?.toolPanel?.position??"right";let l=0,a=0,d=0,c=!1;const h=e=>{if(!c)return;e.preventDefault();const t="left"===s?e.clientX-l:l-e.clientX,i=Math.min(d,Math.max(200,a+t));n.style.width=`${i}px`},u=()=>{if(!c)return;c=!1,r.classList.remove("resizing"),n.style.transition="",document.body.style.cursor="",document.body.style.userSelect="";const e=n.getBoundingClientRect().width;i(e),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",u)},g=e=>{e.preventDefault(),c=!0,l=e.clientX,a=n.getBoundingClientRect().width,d=o.getBoundingClientRect().width-20,r.classList.add("resizing"),n.style.transition="none",document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",h),document.addEventListener("mouseup",u)};return r.addEventListener("mousedown",g),()=>{r.removeEventListener("mousedown",g),document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",u)}}(this.#L,this.#s?.shell,e=>{this.style.setProperty("--tbw-tool-panel-width",`${e}px`)}),this.#re?.(),this.#re=function(e,t,i,n){if(!t?.toolPanel?.closeOnClickOutside)return()=>{};const r=e=>{if(!i.isPanelOpen)return;const t=e.target;t&&(t.closest(".tbw-tool-panel")||t.closest("[data-panel-toggle]")||n())};return e.addEventListener("mousedown",r),()=>e.removeEventListener("mousedown",r)}(this,this.#s?.shell,this.#te,()=>this.closeToolPanel())}}customElements.get(nt.tagName)||customElements.define(nt.tagName,nt),globalThis.DataGridElement=nt;class rt{static dependencies;static manifest;version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#gt;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}attach(e){this.#gt?.abort(),this.#gt=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#gt?.abort(),this.#gt=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const i=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(i),i.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid}get disconnectSignal(){return this.#gt?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...r,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),i=parseInt(t,10);if(!isNaN(i))return i}return 200}resolveIcon(e,t){return void 0!==t?t:this.gridIcons[e]}setIcon(e,t){"string"==typeof t?e.innerHTML=t:t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}warn(e){console.warn(`[tbw-grid:${this.name}] ${e}`)}}const ot={ROOT:"tbw-grid-root",HEADER:"header",HEADER_ROW:"header-row",HEADER_CELL:"header-cell",ROWS_VIEWPORT:"rows-viewport",ROWS_SPACER:"rows-spacer",ROWS_CONTAINER:"rows",DATA_ROW:"data-row",GROUP_ROW:"group-row",DATA_CELL:"data-cell",SELECTED:"selected",FOCUSED:"focused",EDITING:"editing",EXPANDED:"expanded",COLLAPSED:"collapsed",DRAGGING:"dragging",RESIZING:"resizing",SORTABLE:"sortable",SORTED_ASC:"sorted-asc",SORTED_DESC:"sorted-desc",HIDDEN:"hidden",STICKY_LEFT:"sticky-left",STICKY_RIGHT:"sticky-right",PINNED_TOP:"pinned-top",PINNED_BOTTOM:"pinned-bottom",TREE_TOGGLE:"tree-toggle",TREE_INDENT:"tree-indent",GROUP_TOGGLE:"group-toggle",GROUP_LABEL:"group-label",GROUP_COUNT:"group-count",RANGE_SELECTION:"range-selection",SELECTION_OVERLAY:"selection-overlay"},st={ROW_INDEX:"data-row-index",COL_INDEX:"data-col-index",FIELD:"data-field",GROUP_KEY:"data-group-key",TREE_LEVEL:"data-tree-level",STICKY:"data-sticky"},lt={ROOT:`.${ot.ROOT}`,HEADER:`.${ot.HEADER}`,HEADER_ROW:`.${ot.HEADER_ROW}`,HEADER_CELL:`.${ot.HEADER_CELL}`,ROWS_VIEWPORT:`.${ot.ROWS_VIEWPORT}`,ROWS_CONTAINER:`.${ot.ROWS_CONTAINER}`,DATA_ROW:`.${ot.DATA_ROW}`,DATA_CELL:`.${ot.DATA_CELL}`,GROUP_ROW:`.${ot.GROUP_ROW}`,ROW_BY_INDEX:e=>`.${ot.DATA_ROW}[${st.ROW_INDEX}="${e}"]`,CELL_BY_FIELD:e=>`.${ot.DATA_CELL}[${st.FIELD}="${e}"]`,CELL_AT:(e,t)=>`.${ot.DATA_ROW}[${st.ROW_INDEX}="${e}"] .${ot.DATA_CELL}[${st.COL_INDEX}="${t}"]`,SELECTED_ROWS:`.${ot.DATA_ROW}.${ot.SELECTED}`,EDITING_CELL:`.${ot.DATA_CELL}.${ot.EDITING}`};function at(e,t,i=!0){let n=e;if(i&&(n=n.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.meta?.utility)),t?.length){const e=new Set(t);n=n.filter(t=>e.has(t.field))}return n}function dt(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}function ct(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}function ht(e,t){const i=t.delimiter??"\t",n=t.newline??"\n",r=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),o=[];let s=[],l="",a=!1;for(let d=0;d<r.length;d++){const e=r[d];'"'!==e||a?'"'===e&&a?'"'===r[d+1]?(l+='"',d++):a=!1:e!==i||a?e!==n||a?l+=e:(s.push(l),l="",(s.length>1||s.some(e=>""!==e.trim()))&&o.push(s),s=[]):(s.push(l),l=""):a=!0}return s.push(l),(s.length>1||s.some(e=>""!==e.trim()))&&o.push(s),o}function ut(e,t){const{rows:i,target:n,fields:r}=e;if(!n)return;const o=t.rows,s=t.effectiveConfig.columns??[],l=s.map(e=>e.field),a=new Map;s.forEach(e=>{a.set(e.field,!0===e.editable)});const d=[...o],c=n.bounds?n.bounds.endRow:1/0;i.forEach((e,t)=>{const i=n.row+t;if(!(i>c)){if(n.bounds){if(i>=d.length)return}else for(;i>=d.length;){const e={};l.forEach(t=>e[t]=""),d.push(e)}d[i]={...d[i]},e.forEach((e,t)=>{const n=r[t];n&&a.get(n)&&(d[i][n]=e)})}}),t.rows=d}function gt(e){if(null==e)return 100;if("number"==typeof e)return e;const t=parseFloat(e);return isNaN(t)?100:t}function pt(e){return e.map(e=>gt(e.width))}function ft(e){const t=[];let i=0;for(const n of e)t.push(i),i+=gt(n.width);return t}function wt(e){return e.reduce((e,t)=>e+gt(t.width),0)}function mt(e,t,i,n,r){const o=i.length;if(0===o)return{startCol:0,endCol:0,visibleColumns:[]};let s=function(e,t,i){let n=0,r=t.length-1;for(;n<r;){const o=Math.floor((n+r)/2);t[o]+i[o]<=e?n=o+1:r=o}return n}(e,i,n);s=Math.max(0,s-r);const l=e+t;let a=s;for(let c=s;c<o;c++){if(i[c]>=l){a=c-1;break}a=c}a=Math.min(o-1,a+r);const d=[];for(let c=s;c<=a;c++)d.push(c);return{startCol:s,endCol:a,visibleColumns:d}}const bt="@layer tbw-plugins{.tbw-context-menu{position:fixed;background:var(--tbw-context-menu-bg, var(--tbw-color-panel-bg));color:var(--tbw-context-menu-fg, var(--tbw-color-fg));border:1px solid var(--tbw-context-menu-border, var(--tbw-color-border));border-radius:var(--tbw-context-menu-radius, var(--tbw-border-radius));box-shadow:var(--tbw-context-menu-shadow, 0 2px 10px var(--tbw-color-shadow));min-width:var(--tbw-context-menu-min-width, var(--tbw-menu-min-width));padding:var(--tbw-spacing-xs) 0;z-index:10000;font-size:var(--tbw-context-menu-font-size, var(--tbw-font-size-sm));font-family:var(--tbw-context-menu-font-family, var(--tbw-font-family))}.tbw-context-menu-item{display:flex;align-items:center;padding:var(--tbw-context-menu-item-padding, var(--tbw-menu-item-padding));cursor:pointer;gap:var(--tbw-context-menu-item-gap, var(--tbw-menu-item-gap))}.tbw-context-menu-item:hover:not(.disabled){background:var(--tbw-context-menu-hover, var(--tbw-color-row-hover))}.tbw-context-menu-item.disabled{opacity:.5;cursor:default}.tbw-context-menu-item.danger{color:var(--tbw-context-menu-danger, var(--tbw-color-danger))}.tbw-context-menu-icon{width:var(--tbw-context-menu-icon-size, var(--tbw-icon-size));text-align:center}.tbw-context-menu-label{flex:1}.tbw-context-menu-shortcut kbd{color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted));font-size:var(--tbw-context-menu-shortcut-size, var(--tbw-font-size-xs))}.tbw-context-menu-arrow{font-size:var(--tbw-context-menu-arrow-size, var(--tbw-font-size-2xs));color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted))}.tbw-context-menu-separator{height:1px;background:var(--tbw-context-menu-border, var(--tbw-color-border));margin:var(--tbw-spacing-xs) 0}}";function vt(e,t){return("function"==typeof e?e(t):e).filter(e=>!0!==e.hidden&&("function"!=typeof e.hidden||!e.hidden(t)))}function yt(e){const t=[];for(const i of e)i.separator&&(0===t.length||t[t.length-1].separator)||t.push(i);return t.length>0&&t[t.length-1].separator&&t.pop(),t}function Ct(e,t){return!0===e.disabled||"function"==typeof e.disabled&&e.disabled(t)}function xt(e,t,i,n=r.submenuArrow){const o=document.createElement("div");o.className="tbw-context-menu",o.setAttribute("role","menu");const s=e.some(e=>!e.separator&&e.icon);for(const r of e){if(r.separator){const e=document.createElement("div");e.className="tbw-context-menu-separator",e.setAttribute("role","separator"),o.appendChild(e);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",r.cssClass&&e.classList.add(r.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",r.id);const l=Ct(r,t);if(l&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),r.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=r.icon,e.appendChild(t)}else if(s){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML="&nbsp;",e.appendChild(t)}const a=document.createElement("span");if(a.className="tbw-context-menu-label",a.textContent=r.name,e.appendChild(a),r.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(r.shortcut))r.shortcut.forEach((e,i)=>{i>0&&t.appendChild(document.createTextNode("+"));const n=document.createElement("kbd");n.textContent=e,t.appendChild(n)});else{const e=document.createElement("kbd");e.textContent=r.shortcut,t.appendChild(e)}e.appendChild(t)}if(r.subMenu?.length){const o=document.createElement("span");o.className="tbw-context-menu-arrow","string"==typeof n?o.innerHTML=n:n instanceof HTMLElement&&o.appendChild(n.cloneNode(!0)),e.appendChild(o),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!r.subMenu)return;const o=xt(vt(r.subMenu,t),t,i,n);o.classList.add("tbw-context-submenu"),o.style.position="absolute",o.style.left="100%",o.style.top="0",e.style.position="relative",e.appendChild(o)}),e.addEventListener("mouseleave",()=>{const t=e.querySelector(".tbw-context-menu");t&&t.remove()})}l||!r.action||r.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),i(r)}),o.appendChild(e)}return o}function Et(e,t,i){e.style.position="fixed",e.style.left=`${t}px`,e.style.top=`${i}px`,e.style.visibility="hidden",e.style.zIndex="10000";const n=e.getBoundingClientRect(),r=window.innerWidth,o=window.innerHeight;let s=t,l=i;t+n.width>r&&(s=t-n.width),i+n.height>o&&(l=i-n.height),s=Math.max(0,s),l=Math.max(0,l),e.style.left=`${s}px`,e.style.top=`${l}px`,e.style.visibility="visible"}const Rt="getContextMenuItems";let St=null,_t=null,At=null,kt=0;const Tt=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:e=>{const t=e.grid;t?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:e=>{const t=e.grid;t?.plugins?.export?.exportCsv?.()}}];class Lt extends rt{static manifest={queries:[{type:Rt,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:Tt}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),kt++}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,this.uninstallGlobalHandlers()}syncSelectionOnContextMenu(e){if(e<0)return[];const t=this.grid?.query("getSelectedRowIndices"),i=t?.[0];return i?i.includes(e)?i:(this.grid?.query("selectRows",[e]),[e]):[e]}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size"];copyGridStyles(e){const t=this.gridElement;if(!t)return;const i=getComputedStyle(t),n=[],r=i.getPropertyValue("color-scheme").trim();r&&n.push(`color-scheme: ${r}`);for(const o of Lt.CSS_VARS_TO_COPY){const e=i.getPropertyValue(o).trim();e&&n.push(`${o}: ${e}`)}if(n.length>0){const t=e.getAttribute("style")||"";e.setAttribute("style",t+n.join("; ")+";")}}installGlobalHandlers(){!At&&"undefined"!=typeof document&&bt&&(At=document.createElement("style"),At.id="tbw-context-menu-styles",At.textContent=bt,document.head.appendChild(At)),St||(St=()=>{document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())},document.addEventListener("click",St)),_t||(_t=e=>{if("Escape"===e.key){document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())}},document.addEventListener("keydown",_t))}uninstallGlobalHandlers(){kt--,kt>0||(St&&(document.removeEventListener("click",St),St=null),_t&&(document.removeEventListener("keydown",_t),_t=null),At&&(At.remove(),At=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(Rt,e),i=[];for(const n of t)Array.isArray(n)&&i.push(...n);return i.sort((e,t)=>(e.order??100)-(t.order??100)),this.insertGroupSeparators(i)}insertGroupSeparators(e){if(e.length<=1)return e;const t=[];let i=-1;for(const n of e){if(n.separator){t.push(n);continue}const e=Math.floor((n.order??100)/10);i>=0&&e!==i&&t.push({id:`__sep-${i}-${e}`,label:"",separator:!0,action:()=>{}}),i=e,t.push(n)}return t}convertPluginItems(e){return e.map(e=>({id:e.id,name:e.label,icon:e.icon,shortcut:e.shortcut,disabled:e.disabled??!1,action:()=>e.action(),separator:e.separator,cssClass:e.cssClass}))}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root");t&&"true"!==t.getAttribute("data-context-menu-bound")&&(t.setAttribute("data-context-menu-bound","true"),t.addEventListener("contextmenu",e=>{const t=e;t.preventDefault();const i=t.target,n=i.closest("[data-row][data-col]"),r=i.closest('[part~="header-cell"]');let o;if(n){const e=parseInt(n.getAttribute("data-row")??"-1",10),i=parseInt(n.getAttribute("data-col")??"-1",10),r=this.visibleColumns[i],s=this.rows[e],l=this.syncSelectionOnContextMenu(e);o={row:s,rowIndex:e,column:r,columnIndex:i,field:r?.field??"",value:s?.[r?.field]??null,isHeader:!1,event:t,selectedRows:l}}else{if(!r)return;{const e=parseInt(r.getAttribute("data-col")??"-1",10),i=this.visibleColumns[e];o={row:null,rowIndex:-1,column:i,columnIndex:e,field:i?.field??"",value:null,isHeader:!0,event:t,selectedRows:[]}}}this.params=o,this.position={x:t.clientX,y:t.clientY};const s=this.collectPluginItems(o);let l=vt(this.config.items??Tt,o);if(s.length>0){const e=this.convertPluginItems(s);l=l.length>0&&e.length>0?[...l,{id:"__plugin-sep",name:"",separator:!0},...e]:[...l,...e]}l=yt(l),l.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=xt(l,o,e=>{e.action&&e.action(o),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),Et(this.menuElement,t.clientX,t.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:o,items:l}))}))}showMenu(e,t,i){const n={row:i.row??null,rowIndex:i.rowIndex??-1,column:i.column??null,columnIndex:i.columnIndex??-1,field:i.field??"",value:i.value??null,isHeader:i.isHeader??!1,event:i.event??new MouseEvent("contextmenu"),selectedRows:i.selectedRows??[]},r=this.collectPluginItems(n);let o=vt(this.config.items??Tt,n);if(r.length>0){const e=this.convertPluginItems(r);o=o.length>0&&e.length>0?[...o,{id:"__plugin-sep",name:"",separator:!0},...e]:[...o,...e]}o=yt(o),this.menuElement&&this.menuElement.remove(),this.menuElement=xt(o,n,e=>{e.action&&e.action(n),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),Et(this.menuElement,e,t),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}function Mt(e){return t=>{const i=e.editorParams,n=document.createElement("input");n.type="date",t.value instanceof Date?n.valueAsDate=t.value:"string"==typeof t.value&&t.value&&(n.value=t.value.split("T")[0]),i?.min&&(n.min=i.min),i?.max&&(n.max=i.max),i?.placeholder&&(n.placeholder=i.placeholder);return n.addEventListener("change",()=>{var r;if(n.value)"string"==typeof t.value?t.commit(n.value):t.commit(n.valueAsDate);else if(e.nullable)t.commit(null);else{const e=i?.default;"string"==typeof t.value||"string"==typeof e?t.commit("string"==typeof e?e:`${(r=e??new Date).getFullYear()}-${String(r.getMonth()+1).padStart(2,"0")}-${String(r.getDate()).padStart(2,"0")}`):t.commit(e instanceof Date?e:new Date)}}),n.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),n}}const It="__tbw_null__";function Pt(e){switch(e.type){case"number":return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");n.type="number",n.value=null!=t.value?String(t.value):"",void 0!==i?.min&&(n.min=String(i.min)),void 0!==i?.max&&(n.max=String(i.max)),void 0!==i?.step&&(n.step=String(i.step)),i?.placeholder&&(n.placeholder=i.placeholder);const r=()=>{""===n.value?e.nullable?t.commit(null):t.commit(i?.min??0):t.commit(Number(n.value))};return n.addEventListener("blur",r),n.addEventListener("keydown",e=>{"Enter"===e.key&&r(),"Escape"===e.key&&t.cancel()}),n}}(e);case"boolean":return e=>{const t=document.createElement("input");return t.type="checkbox",t.checked=!!e.value,t.addEventListener("change",()=>e.commit(t.checked)),t};case"date":return Mt(e);case"select":return function(e){return t=>{const i=e.editorParams,n=document.createElement("select");if(e.multi&&(n.multiple=!0),e.nullable||i?.includeEmpty){const r=document.createElement("option");r.value=e.nullable?It:"",r.textContent=e.nullable?i?.emptyLabel??"(Blank)":i?.emptyLabel??"",null==t.value&&(r.selected=!0),n.appendChild(r)}const r=function(e){const t=e.options;return t?"function"==typeof t?t():t:[]}(e);r.forEach(i=>{const r=document.createElement("option");r.value=String(i.value),r.textContent=i.label,e.multi&&Array.isArray(t.value)&&t.value.includes(i.value)?r.selected=!0:e.multi||t.value!==i.value||(r.selected=!0),n.appendChild(r)});const o=()=>{if(e.multi){const e=Array.from(n.selectedOptions).map(e=>e.value);t.commit(e)}else e.nullable&&n.value===It?t.commit(null):t.commit(n.value)};return n.addEventListener("change",o),n.addEventListener("blur",o),n.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),n}}(e);default:return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");n.type="text",n.value=null!=t.value?String(t.value):"",void 0!==i?.maxLength&&(n.maxLength=i.maxLength),i?.pattern&&(n.pattern=i.pattern),i?.placeholder&&(n.placeholder=i.placeholder);const r=()=>{const i=n.value;""!==i?"string"==typeof t.value&&i===t.value.replace(/[\n\r]/g,"")||("number"==typeof t.value?t.commit(Number(i)):t.commit(i)):e.nullable?t.commit(null):t.commit("")};return n.addEventListener("blur",r),n.addEventListener("keydown",e=>{"Enter"===e.key&&r(),"Escape"===e.key&&t.cancel()}),n}}(e)}}function Ht(e,t,i){const n=e.get(t);return!!n&&!zt(n,i)}function Dt(e,t,i,n){const r=e.get(t);if(!r)return!1;return!zt(r[n],i[n])}function zt(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(typeof e!=typeof t)return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!zt(e[i],t[i]))return!1;return!0}if("object"==typeof e){const i=e,n=t,r=Object.keys(i),o=Object.keys(n);if(r.length!==o.length)return!1;for(const e of r)if(!zt(i[e],n[e]))return!1;return!0}return!1}function Ot(e,t,i){e.set(t,structuredClone(i))}function Ft(e,t){const i=e.get(t);return i?structuredClone(i):void 0}function qt(e,t,i){const n=e.get(t);if(!n)return!1;const r=n,o=i;for(const s of Object.keys(r))o[s]=r[s];return!0}function Nt(e){return"string"==typeof e&&("__proto__"!==e&&"constructor"!==e&&"prototype"!==e)}function Gt(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}function Bt(e){}function Vt(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 $t(e,t){const i=URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(i)}function Wt(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}const Kt="(Blank)";function Ut(e){if(e instanceof Date)return e.getTime();const t=Number(e);if(!isNaN(t))return t;return new Date(e).getTime()}function jt(e,t,i=!1,n){return t.length?e.filter(e=>t.every(t=>function(e,t,i=!1,n){const r=e[t.field];if("blank"===t.operator)return null==r||""===r;if("notBlank"===t.operator)return null!=r&&""!==r;if(n&&("notIn"===t.operator||"in"===t.operator)){const i=n(r,e),o=Array.isArray(i)?i:null!=i?[i]:[];if("notIn"===t.operator){const e=t.value;return!Array.isArray(e)||(0===o.length?!e.includes(Kt):!o.some(t=>e.includes(t)))}if("in"===t.operator){const e=t.value;return!!Array.isArray(e)&&(0===o.length?e.includes(Kt):o.some(t=>e.includes(t)))}}if("notIn"===t.operator)return null==r||""===r?!Array.isArray(t.value)||!t.value.includes(Kt):Array.isArray(t.value)&&!t.value.includes(r);if("in"===t.operator)return null==r||""===r?Array.isArray(t.value)&&t.value.includes(Kt):Array.isArray(t.value)&&t.value.includes(r);if(null==r)return!1;const o=String(r),s=i?o:o.toLowerCase(),l=i?String(t.value):String(t.value).toLowerCase();switch(t.operator){case"contains":return s.includes(l);case"notContains":return!s.includes(l);case"equals":return s===l;case"notEquals":return s!==l;case"startsWith":return s.startsWith(l);case"endsWith":return s.endsWith(l);case"lessThan":return Ut(r)<Ut(t.value);case"lessThanOrEqual":return Ut(r)<=Ut(t.value);case"greaterThan":return Ut(r)>Ut(t.value);case"greaterThanOrEqual":return Ut(r)>=Ut(t.value);case"between":return Ut(r)>=Ut(t.value)&&Ut(r)<=Ut(t.valueTo);default:return!0}}(e,t,i,n?.get(t.field)))):e}function Yt(e,t,i){const n=new Set;let r=!1;for(const o of e){const e=o[t];if(i){const t=i(e,o);if(Array.isArray(t)){0===t.length&&(r=!0);for(const e of t)null!=e&&n.add(e)}else null!=t?n.add(t):r=!0}else null!=e&&""!==e?n.add(e):r=!0}return r&&n.add(Kt),[...n].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t)))}function Xt(e,t){const i=new Map;for(const{field:r,filterValue:o}of t)i.set(r,{values:new Set,hasBlank:!1,hasExtractor:!!o});for(const r of e)for(const{field:e,filterValue:n}of t){const t=i.get(e),o=r[e];if(n){const e=n(o,r);if(Array.isArray(e)){0===e.length&&(t.hasBlank=!0);for(const i of e)null!=i&&t.values.add(i)}else null!=e?t.values.add(e):t.hasBlank=!0}else null!=o&&""!==o?t.values.add(o):t.hasBlank=!0}const n=new Map;for(const[r,{values:o,hasBlank:s}]of i)s&&o.add(Kt),n.set(r,[...o].sort((e,t)=>"number"==typeof e&&"number"==typeof t?e-t:String(e).localeCompare(String(t))));return n}const Zt="__tbw_expander";function Qt(e){return e.field===Zt}function Jt(e){return!0===e.meta?.utility}class ei extends rt{static manifest={events:[{type:"filter-applied",description:"Emitted when filter criteria change. Subscribers can react to row visibility changes."}],queries:[{type:"getContextMenuItems",description:"Contributes filter-related items to the header context menu"}]};name="filtering";styles='@layer tbw-plugins{tbw-grid .tbw-quick-filter-input{flex:1;max-width:300px;height:var(--tbw-input-height, 1.75rem);padding:var(--tbw-input-padding, 0 .5rem);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);background:var(--tbw-color-bg);color:var(--tbw-color-fg);font-size:var(--tbw-font-size-sm, .8125rem)}tbw-grid .tbw-quick-filter-input:focus{outline:none;border-color:var(--tbw-color-accent)}tbw-grid .header-cell.filtered:before{content:"";position:absolute;top:var(--tbw-spacing-xs, .25rem);right:var(--tbw-spacing-xs, .25rem);width:var(--tbw-indicator-size, .375rem);height:var(--tbw-indicator-size, .375rem);background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border-radius:50%}tbw-grid .tbw-filter-btn{display:var(--tbw-filter-btn-display, inline-flex);visibility:var(--tbw-filter-btn-visibility, visible);align-items:center;justify-content:center;background:transparent;border:none;cursor:pointer;padding:2px;margin-left:var(--tbw-spacing-xs, .25rem);opacity:.4;transition:opacity .15s,visibility 0s,display 0s allow-discrete;color:inherit;vertical-align:middle;transition-behavior:allow-discrete}tbw-grid .tbw-filter-btn:hover,tbw-grid .tbw-filter-btn.active{opacity:1;visibility:visible;display:inline-flex}tbw-grid .tbw-filter-btn.active{color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6))}tbw-grid .header-row .cell:hover .tbw-filter-btn,tbw-grid .header-row .cell.filtered .tbw-filter-btn{display:inline-flex;visibility:visible}}';get defaultConfig(){return{debounceMs:300,caseSensitive:!1,trimInput:!0,useWorker:!0}}isFilteringEnabled(){return!1!==this.grid.effectiveConfig?.filterable}isColumnFilterable(e){return!!this.isFilteringEnabled()&&!1!==e.filterable}getFilterValues(){const e=this.grid.effectiveConfig?.columns;if(!e)return;let t;for(const i of e)i.field&&i.filterValue&&(t||(t=new Map),t.set(i.field,i.filterValue));return t}filters=new Map;cachedResult=null;cacheKey=null;cachedInputSpot=null;openPanelField=null;panelElement=null;panelAnchorElement=null;searchText=new Map;excludedValues=new Map;panelAbortController=null;globalStylesInjected=!1;static DEFAULT_LIST_ITEM_HEIGHT=28;static LIST_OVERSCAN=3;static LIST_BYPASS_THRESHOLD=50;getListItemHeight(){if(this.panelElement){const e=getComputedStyle(this.panelElement).getPropertyValue("--tbw-filter-item-height");if(e&&e.trim()){const t=parseFloat(e);if(!isNaN(t)&&t>0)return t}}return ei.DEFAULT_LIST_ITEM_HEIGHT}computeSelected(){const e=[];for(const[n,r]of this.filters){if("set"!==r.type||"notIn"!==r.operator)continue;const t=this.grid.effectiveConfig?.columns?.find(e=>e.field===n);e.push({field:n,filterValue:t?.filterValue})}if(0===e.length)return{};const t=Xt(this.sourceRows,e),i={};for(const{field:n}of e){const e=this.excludedValues.get(n),r=t.get(n)??[];i[n]=e?r.filter(t=>!e.has(t)):r}return i}syncExcludedValues(e,t){t?"set"===t.type&&"notIn"===t.operator&&Array.isArray(t.value)?this.excludedValues.set(e,new Set(t.value)):"set"===t.type&&this.excludedValues.delete(e):this.excludedValues.delete(e)}attach(e){super.attach(e),this.injectGlobalStyles()}detach(){this.filters.clear(),this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,this.openPanelField=null,this.panelElement&&(this.panelElement.remove(),this.panelElement=null),this.searchText.clear(),this.excludedValues.clear(),this.panelAbortController?.abort(),this.panelAbortController=null}handleQuery(e){if("getContextMenuItems"===e.type){const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field)return;if(!this.isFilteringEnabled())return;if(!this.isColumnFilterable(i))return;const n=[],r=this.isFieldFiltered(i.field),o=this.filters.size>0;return r&&n.push({id:"filtering/clear-column-filter",label:"Clear Filter",icon:"✕",order:20,action:()=>this.clearFieldFilter(i.field)}),o&&n.push({id:"filtering/clear-all-filters",label:"Clear All Filters",icon:"✕",order:21,disabled:!o,action:()=>this.clearAllFilters()}),n.length>0?n:void 0}}processRows(e){const t=[...this.filters.values()];if(!t.length)return[...e];if(this.config.filterHandler)return this.cachedResult?this.cachedResult:[...e];const i=(n=t,JSON.stringify(n.map(e=>({field:e.field,operator:e.operator,value:e.value,valueTo:e.valueTo}))));var n;const r={len:e.length,first:e[0],mid:e[Math.floor(e.length/2)],last:e[e.length-1]},o=null!=this.cachedInputSpot&&r.len===this.cachedInputSpot.len&&r.first===this.cachedInputSpot.first&&r.mid===this.cachedInputSpot.mid&&r.last===this.cachedInputSpot.last;if(this.cacheKey===i&&this.cachedResult&&o)return this.cachedResult;const s=jt([...e],t,this.config.caseSensitive,this.getFilterValues());return this.cachedResult=s,this.cacheKey=i,this.cachedInputSpot=r,s}afterRender(){const e=this.gridElement;if(!e)return;e.querySelectorAll('[part~="header-cell"]').forEach(e=>{const t=e.getAttribute("data-col");if(null===t)return;const i=this.visibleColumns[parseInt(t,10)];if(!i||!this.isColumnFilterable(i))return;if(Jt(i))return;const n=i.field;if(!n)return;const r=this.filters.has(n);let o=e.querySelector(".tbw-filter-btn");if(o){const t=o.classList.contains("active");if(o.classList.toggle("active",r),e.classList.toggle("filtered",r),t!==r){const e=r?"filterActive":"filter";this.setIcon(o,this.resolveIcon(e))}return}o=document.createElement("button"),o.className="tbw-filter-btn",o.setAttribute("aria-label",`Filter ${i.header??n}`);const s=r?"filterActive":"filter";this.setIcon(o,this.resolveIcon(s)),r&&(o.classList.add("active"),e.classList.add("filtered")),o.addEventListener("click",e=>{e.stopPropagation(),this.toggleFilterPanel(n,i,o)});const l=e.querySelector(".resize-handle");l?e.insertBefore(o,l):e.appendChild(o)})}setFilter(e,t,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)}this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,i?.silent||this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:[...this.filters.values()]}),this.requestRender()}getFilter(e){return this.filters.get(e)}getFilters(){return[...this.filters.values()]}getFilterModel(){return this.getFilters()}setFilterModel(e,t){this.filters.clear(),this.excludedValues.clear();for(const i of e)this.filters.set(i.field,i),this.syncExcludedValues(i.field,i);this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null,t?.silent||this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:[...this.filters.values()]}),this.requestRender()}clearAllFilters(e){this.filters.clear(),this.excludedValues.clear(),this.searchText.clear(),this.applyFiltersInternal(e?.silent)}clearFieldFilter(e,t){this.filters.delete(e),this.excludedValues.delete(e),this.searchText.delete(e),this.applyFiltersInternal(t?.silent)}isFieldFiltered(e){return this.filters.has(e)}getFilteredRowCount(){return this.cachedResult?.length??this.rows.length}getActiveFilters(){return this.getFilters()}getUniqueValues(e){const t=this.grid.effectiveConfig?.columns?.find(t=>t.field===e),i=t?.filterValue;return Yt(this.sourceRows,e,i)}copyGridThemeContext(e){const t=this.gridElement;if(!t)return;for(const n of t.classList)n.startsWith("tbw-")||"selecting"===n||e.classList.add(n);const i=t.dataset.theme;i&&(e.dataset.theme=i)}injectGlobalStyles(){if(this.globalStylesInjected)return;if(document.getElementById("tbw-filter-panel-styles"))return void(this.globalStylesInjected=!0);const e=document.createElement("style");e.id="tbw-filter-panel-styles",e.textContent="@layer tbw-plugins{.tbw-filter-panel{position:fixed;background:var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));color:var(--tbw-filter-panel-fg, var(--tbw-color-fg, light-dark(#222222, #eeeeee)));border:1px solid var(--tbw-filter-panel-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-panel-radius, var(--tbw-border-radius, .25rem));box-shadow:0 4px 16px var(--tbw-filter-panel-shadow, var(--tbw-color-shadow, light-dark(rgba(0, 0, 0, .1), rgba(0, 0, 0, .3))));padding:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));z-index:10000;min-width:200px;max-width:280px;max-height:350px;display:flex;flex-direction:column;font-family:var(--tbw-font-family, system-ui, sans-serif);font-size:var(--tbw-font-size, .8125rem);transform-origin:top center}.tbw-filter-panel.tbw-filter-panel-above{transform-origin:bottom center}.tbw-filter-panel.tbw-filter-panel-animated{animation:tbw-filter-panel-enter var(--tbw-animation-duration, .15s) var(--tbw-animation-easing, ease-out)}.tbw-filter-panel.tbw-filter-panel-above.tbw-filter-panel-animated{animation:tbw-filter-panel-enter-above var(--tbw-animation-duration, .15s) var(--tbw-animation-easing, ease-out)}@keyframes tbw-filter-panel-enter{0%{opacity:0;transform:scaleY(.3) translateY(-10px)}to{opacity:1;transform:scaleY(1) translateY(0)}}@keyframes tbw-filter-panel-enter-above{0%{opacity:0;transform:scaleY(.3) translateY(10px)}to{opacity:1;transform:scaleY(1) translateY(0)}}@supports (anchor-name: --test){.tbw-filter-panel{position-anchor:--tbw-filter-anchor;top:anchor(bottom);left:anchor(left);margin-top:4px;position-try-fallbacks:flip-inline,flip-block,flip-block flip-inline}}.tbw-filter-search{margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));min-height:var(--tbw-filter-item-height, 28px)}.tbw-filter-search-input{height:var(--tbw-filter-item-height, 28px);width:100%;padding:var(--tbw-filter-search-padding, var(--tbw-spacing-sm, .375rem) var(--tbw-spacing-md, .5rem));background:var(--tbw-filter-input-bg, var(--tbw-color-bg, transparent));color:inherit;border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-input-radius, var(--tbw-border-radius, .25rem));font-size:inherit;box-sizing:border-box}.tbw-filter-search-input:focus{outline:none;border-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));box-shadow:0 0 0 2px rgba(from var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6)) r g b / 15%)}.tbw-filter-actions{display:flex;padding:var(--tbw-button-padding-sm, .25rem .125rem);margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border-bottom:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));min-height:var(--tbw-filter-item-height, 28px)}.tbw-filter-actions .tbw-filter-value-item{flex:1}.tbw-filter-values{flex:1;overflow-y:auto;margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));max-height:180px;position:relative}.tbw-filter-values-spacer{width:1px}.tbw-filter-values-content{position:absolute;top:0;left:0;right:0}.tbw-filter-value-item{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding-sm, .25rem .125rem);cursor:pointer;border-radius:3px;height:var(--tbw-filter-item-height, 28px)}.tbw-filter-value-item:hover{background:var(--tbw-filter-hover, var(--tbw-color-row-hover, light-dark(#f0f6ff, #1c1c1c)))}.tbw-filter-checkbox{margin:0;cursor:pointer;accent-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6))}.tbw-filter-no-match{color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem)) 0;text-align:center;font-style:italic}.tbw-filter-buttons{display:flex;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding-top:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border-top:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)))}.tbw-filter-apply-btn{flex:1;padding:var(--tbw-filter-btn-padding, var(--tbw-button-padding, .375rem .75rem));background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));color:var(--tbw-filter-accent-fg, var(--tbw-color-accent-fg, light-dark(#ffffff, #000000)));border:none;border-radius:var(--tbw-border-radius, .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);font-weight:var(--tbw-filter-btn-font-weight, 500);min-height:var(--tbw-filter-btn-min-height, auto)}.tbw-filter-apply-btn:hover{filter:brightness(.9)}.tbw-filter-clear-btn{flex:1;padding:var(--tbw-filter-btn-padding, var(--tbw-button-padding, .375rem .75rem));background:transparent;color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-border-radius, .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);font-weight:var(--tbw-filter-btn-font-weight, 500);min-height:var(--tbw-filter-btn-min-height, auto)}.tbw-filter-clear-btn:hover{background:var(--tbw-filter-hover, var(--tbw-color-row-hover, light-dark(#f0f6ff, #1c1c1c)))}.tbw-filter-range-inputs,.tbw-filter-date-range{display:flex;align-items:flex-end;gap:var(--tbw-spacing-sm, .375rem);margin-bottom:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-filter-range-group,.tbw-filter-date-group{display:flex;flex-direction:column;gap:var(--tbw-spacing-xs, .25rem);flex:1}.tbw-filter-range-label{font-size:var(--tbw-font-size-xs, .75rem);color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)))}.tbw-filter-range-input,.tbw-filter-date-input{width:100%;height:var(--tbw-filter-item-height, 28px);padding:var(--tbw-spacing-xs, .25rem) var(--tbw-spacing-sm, .375rem);background:var(--tbw-filter-input-bg, var(--tbw-color-bg, transparent));color:inherit;border:1px solid var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:var(--tbw-filter-input-radius, var(--tbw-border-radius, .25rem));font-size:inherit;box-sizing:border-box}.tbw-filter-range-input:focus,.tbw-filter-date-input:focus{outline:none;border-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));box-shadow:0 0 0 2px rgba(from var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6)) r g b / 15%)}.tbw-filter-range-separator{color:var(--tbw-filter-muted, var(--tbw-color-fg-muted, light-dark(#555555, #aaaaaa)));padding-bottom:var(--tbw-spacing-xs, .25rem)}.tbw-filter-blank-option{display:flex;align-items:center;gap:var(--tbw-spacing-sm, .375rem);padding:var(--tbw-spacing-xs, .25rem) 0;margin-bottom:var(--tbw-spacing-xs, .25rem);font-size:var(--tbw-font-size-sm, .8125rem);cursor:pointer;-webkit-user-select:none;user-select:none}.tbw-filter-blank-checkbox{accent-color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));margin:0;cursor:pointer}.tbw-filter-date-range.tbw-filter-disabled,.tbw-filter-range-inputs.tbw-filter-disabled,.tbw-filter-range-slider.tbw-filter-disabled{opacity:.4;pointer-events:none}.tbw-filter-range-slider{position:relative;height:24px;margin:var(--tbw-spacing-md, .5rem) 0 var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-filter-range-track{position:absolute;top:50%;left:0;right:0;height:4px;background:var(--tbw-filter-input-border, var(--tbw-color-border, light-dark(#d0d0d4, #454545)));border-radius:2px;transform:translateY(-50%)}.tbw-filter-range-fill{position:absolute;top:50%;height:4px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border-radius:2px;transform:translateY(-50%)}.tbw-filter-range-thumb{position:absolute;top:0;width:100%;height:100%;background:none;pointer-events:none;-webkit-appearance:none;appearance:none}.tbw-filter-range-thumb::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:16px;height:16px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border:2px solid var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));border-radius:50%;cursor:pointer;pointer-events:all;box-shadow:0 1px 3px #0003}.tbw-filter-range-thumb::-moz-range-thumb{width:16px;height:16px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border:2px solid var(--tbw-filter-panel-bg, var(--tbw-color-panel-bg, light-dark(#eeeeee, #222222)));border-radius:50%;cursor:pointer;pointer-events:all;box-shadow:0 1px 3px #0003}.tbw-filter-range-thumb::-webkit-slider-thumb:hover{transform:scale(1.1)}.tbw-filter-range-thumb::-moz-range-thumb:hover{transform:scale(1.1)}}",document.head.appendChild(e),this.globalStylesInjected=!0}toggleFilterPanel(e,t,i){if(this.openPanelField===e)return void this.closeFilterPanel();this.closeFilterPanel();const n=document.createElement("div");if(n.className="tbw-filter-panel",this.copyGridThemeContext(n),this.isAnimationEnabled&&n.classList.add("tbw-filter-panel-animated"),this.panelElement=n,this.openPanelField=e,this.config.valuesHandler)return n.innerHTML='<div class="tbw-filter-loading">Loading...</div>',document.body.appendChild(n),this.positionPanel(n,i),this.setupPanelCloseHandler(n,i),void this.config.valuesHandler(e,t).then(i=>{this.openPanelField===e&&this.panelElement&&(n.innerHTML="",this.renderPanelContent(e,t,n,i))});const r=Yt(this.sourceRows,e,t.filterValue);document.body.appendChild(n),this.positionPanel(n,i),this.renderPanelContent(e,t,n,r),this.setupPanelCloseHandler(n,i)}renderPanelContent(e,t,i,n){let r=this.excludedValues.get(e);r||(r=new Set,this.excludedValues.set(e,r));const o=this.searchText.get(e)??"",s={field:e,column:t,uniqueValues:n,excludedValues:r,searchText:o,currentFilter:this.filters.get(e),applySetFilter:(t,i)=>{this.applySetFilter(e,t,i),this.closeFilterPanel()},applyTextFilter:(t,i,n)=>{this.applyTextFilter(e,t,i,n),this.closeFilterPanel()},clearFilter:()=>{this.clearFieldFilter(e),this.closeFilterPanel()},closePanel:()=>this.closeFilterPanel()};let l=!1;if(this.config.filterPanelRenderer&&(this.config.filterPanelRenderer(i,s),l=i.children.length>0),!l&&t.type){const e=this.grid.effectiveConfig.typeDefaults?.[t.type];e?.filterPanelRenderer&&(e.filterPanelRenderer(i,s),l=i.children.length>0)}if(!l){const e=t.type;"number"===e?this.renderNumberFilterPanel(i,s,n):"date"===e?this.renderDateFilterPanel(i,s,n):this.renderDefaultFilterPanel(i,s,n,r)}}setupPanelCloseHandler(e,t){this.panelAbortController=new AbortController,setTimeout(()=>{document.addEventListener("click",i=>{e.contains(i.target)||i.target===t||this.closeFilterPanel()},{signal:this.panelAbortController?.signal})},0)}closeFilterPanel(){const e=this.panelElement;e&&(e.remove(),this.panelElement=null),this.panelAnchorElement&&(this.panelAnchorElement.style.anchorName="",this.panelAnchorElement=null),this.openPanelField=null,this.panelAbortController?.abort(),this.panelAbortController=null}static supportsAnchorPositioning=null;static checkAnchorPositioningSupport(){return null===ei.supportsAnchorPositioning&&(ei.supportsAnchorPositioning=CSS.supports("anchor-name","--test")),ei.supportsAnchorPositioning}positionPanel(e,t){const i=t.closest(".cell")??t;if(i.style.anchorName="--tbw-filter-anchor",this.panelAnchorElement=i,ei.checkAnchorPositioningSupport())return void requestAnimationFrame(()=>{const t=e.getBoundingClientRect(),n=i.getBoundingClientRect();t.top<n.top&&e.classList.add("tbw-filter-panel-above")});const n=i.getBoundingClientRect();e.style.position="fixed",e.style.top=`${n.bottom+4}px`,e.style.left=`${n.left}px`,requestAnimationFrame(()=>{const t=e.getBoundingClientRect();t.right>window.innerWidth-8&&(e.style.left=n.right-t.width+"px"),t.bottom>window.innerHeight-8&&(e.style.top=n.top-t.height-4+"px",e.classList.add("tbw-filter-panel-above"))})}renderDefaultFilterPanel(e,t,i,n){const{field:r,column:o}=t,s=this.getListItemHeight(),l=e=>{if(null==e)return"(Blank)";if(o.format&&!o.filterValue){const t=o.format(e,void 0);if(t)return t}return String(e)};i=i.slice().sort((e,t)=>l(e).localeCompare(l(t)));const a=document.createElement("div");a.className="tbw-filter-search";const d=document.createElement("input");d.type="text",d.placeholder="Search...",d.className="tbw-filter-search-input",d.value=this.searchText.get(r)??"",a.appendChild(d),e.appendChild(a);const c=document.createElement("div");c.className="tbw-filter-actions";const h=document.createElement("label");h.className="tbw-filter-value-item",h.style.padding="0",h.style.margin="0";const u=document.createElement("input");u.type="checkbox",u.className="tbw-filter-checkbox";const g=document.createElement("span");g.textContent="Select All",h.appendChild(u),h.appendChild(g),c.appendChild(h);const p=()=>{const e=[...b.values()],t=e.every(e=>e),i=e.every(e=>!e);u.checked=t,u.indeterminate=!t&&!i};u.addEventListener("change",()=>{const e=u.checked;for(const t of b.keys())b.set(t,e);p(),C()}),e.appendChild(c);const f=document.createElement("div");f.className="tbw-filter-values";const w=document.createElement("div");w.className="tbw-filter-values-spacer",f.appendChild(w);const m=document.createElement("div");m.className="tbw-filter-values-content",f.appendChild(m);const b=new Map;i.forEach(e=>{const t=null==e?"__null__":String(e);b.set(t,!n.has(e))}),p();let v=[];const y=(e,t)=>{const i=l(e),n=null==e?"__null__":String(e),r=document.createElement("label");r.className="tbw-filter-value-item",r.style.position="absolute",r.style.top=`calc(var(--tbw-filter-item-height, 28px) * ${t})`,r.style.left="0",r.style.right="0",r.style.boxSizing="border-box";const o=document.createElement("input");o.type="checkbox",o.className="tbw-filter-checkbox",o.checked=b.get(n)??!0,o.dataset.value=n,o.addEventListener("change",()=>{b.set(n,o.checked),p()});const s=document.createElement("span");return s.textContent=i,r.appendChild(o),r.appendChild(s),r},C=()=>{const e=v.length,t=f.clientHeight,i=f.scrollTop;if(w.style.height=e*s+"px",n=e,r=ei.LIST_BYPASS_THRESHOLD/3,n<=r)return m.innerHTML="",m.style.transform="translateY(0px)",void v.forEach((e,t)=>{m.appendChild(y(e,t))});var n,r;const o=function(e){const{totalRows:t,viewportHeight:i,scrollTop:n,rowHeight:r,overscan:o}=e,s=Math.ceil(i/r);let l=Math.floor(n/r)-o;l<0&&(l=0);let a=l+s+2*o;return a>t&&(a=t),a===t&&l>0&&(l=Math.max(0,a-s-2*o)),{start:l,end:a,offsetY:l*r,totalHeight:t*r}}({totalRows:e,viewportHeight:t,scrollTop:i,rowHeight:s,overscan:ei.LIST_OVERSCAN});m.style.transform=`translateY(${o.offsetY}px)`,m.innerHTML="";for(let s=o.start;s<o.end;s++)m.appendChild(y(v[s],s-o.start))},x=e=>{const t=this.config.caseSensitive??!1,n=t?e:e.toLowerCase();if(v=i.filter(i=>{const r=l(i),o=t?r:r.toLowerCase();return!e||o.includes(n)}),0===v.length){w.style.height="0px",m.innerHTML="";const e=document.createElement("div");return e.className="tbw-filter-no-match",e.textContent="No matching values",void m.appendChild(e)}C()};let E;f.addEventListener("scroll",()=>{v.length>0&&C()},{passive:!0}),x(d.value),e.appendChild(f),d.addEventListener("input",()=>{clearTimeout(E),E=setTimeout(()=>{this.searchText.set(r,d.value),x(d.value)},this.config.debounceMs??150)});const R=document.createElement("div");R.className="tbw-filter-buttons";const S=document.createElement("button");S.className="tbw-filter-apply-btn",S.textContent="Apply",S.addEventListener("click",()=>{const e=[];for(const[t,n]of b)if(!n)if("__null__"===t)e.push(null);else{const n=i.find(e=>String(e)===t);e.push(void 0!==n?n:t)}t.applySetFilter(e)}),R.appendChild(S);const _=document.createElement("button");_.className="tbw-filter-clear-btn",_.textContent="Clear Filter",_.addEventListener("click",()=>{t.clearFilter()}),R.appendChild(_),e.appendChild(R)}renderNumberFilterPanel(e,t,i){const{field:n,column:r}=t,o=r.filterParams,s=r.editorParams,l=(e,t)=>{if("number"==typeof e)return e;if("string"==typeof e){const i=parseFloat(e);return isNaN(i)?t:i}return t},a=i.filter(e=>"number"==typeof e&&!isNaN(e)),d=a.length>0?Math.min(...a):0,c=a.length>0?Math.max(...a):100,h=l(o?.min??s?.min,d),u=l(o?.max??s?.max,c),g=o?.step??s?.step??1,p=this.filters.get(n);let f=h,w=u;const m="blank"===p?.operator;"between"===p?.operator?(f=l(p.value,h),w=l(p.valueTo,u)):"greaterThanOrEqual"===p?.operator?f=l(p.value,h):"lessThanOrEqual"===p?.operator&&(w=l(p.value,u));const b=document.createElement("div");b.className="tbw-filter-range-inputs";const v=document.createElement("div");v.className="tbw-filter-range-group";const y=document.createElement("label");y.textContent="Min",y.className="tbw-filter-range-label";const C=document.createElement("input");C.type="number",C.className="tbw-filter-range-input",C.min=String(h),C.max=String(u),C.step=String(g),C.value=String(f),v.appendChild(y),v.appendChild(C),b.appendChild(v);const x=document.createElement("span");x.className="tbw-filter-range-separator",x.textContent="–",b.appendChild(x);const E=document.createElement("div");E.className="tbw-filter-range-group";const R=document.createElement("label");R.textContent="Max",R.className="tbw-filter-range-label";const S=document.createElement("input");S.type="number",S.className="tbw-filter-range-input",S.min=String(h),S.max=String(u),S.step=String(g),S.value=String(w),E.appendChild(R),E.appendChild(S),b.appendChild(E),e.appendChild(b);const _=document.createElement("div");_.className="tbw-filter-range-slider";const A=document.createElement("div");A.className="tbw-filter-range-track";const k=document.createElement("div");k.className="tbw-filter-range-fill";const T=document.createElement("input");T.type="range",T.className="tbw-filter-range-thumb tbw-filter-range-thumb-min",T.min=String(h),T.max=String(u),T.step=String(g),T.value=String(f);const L=document.createElement("input");L.type="range",L.className="tbw-filter-range-thumb tbw-filter-range-thumb-max",L.min=String(h),L.max=String(u),L.step=String(g),L.value=String(w),_.appendChild(A),_.appendChild(k),_.appendChild(T),_.appendChild(L),e.appendChild(_);const M=document.createElement("label");M.className="tbw-filter-blank-option";const I=document.createElement("input");I.type="checkbox",I.className="tbw-filter-blank-checkbox",I.checked=m;const P=document.createTextNode("Blank");M.appendChild(I),M.appendChild(P);const H=e=>{C.disabled=e,S.disabled=e,T.disabled=e,L.disabled=e,b.classList.toggle("tbw-filter-disabled",e),_.classList.toggle("tbw-filter-disabled",e)};H(m),I.addEventListener("change",()=>{H(I.checked)}),e.appendChild(M);const D=()=>{const e=parseFloat(T.value),t=parseFloat(L.value),i=u-h,n=(e-h)/i*100,r=(t-h)/i*100;k.style.left=`${n}%`,k.style.width=r-n+"%"};T.addEventListener("input",()=>{const e=Math.min(parseFloat(T.value),parseFloat(L.value));T.value=String(e),C.value=String(e),D()}),L.addEventListener("input",()=>{const e=Math.max(parseFloat(L.value),parseFloat(T.value));L.value=String(e),S.value=String(e),D()}),C.addEventListener("input",()=>{let e=parseFloat(C.value)||h;e=Math.max(h,Math.min(e,parseFloat(S.value))),T.value=String(e),D()}),S.addEventListener("input",()=>{let e=parseFloat(S.value)||u;e=Math.min(u,Math.max(e,parseFloat(C.value))),L.value=String(e),D()}),D();const z=document.createElement("div");z.className="tbw-filter-buttons";const O=document.createElement("button");O.className="tbw-filter-apply-btn",O.textContent="Apply",O.addEventListener("click",()=>{if(I.checked)return void t.applyTextFilter("blank","");const e=parseFloat(C.value),i=parseFloat(S.value);t.applyTextFilter("between",e,i)}),z.appendChild(O);const F=document.createElement("button");F.className="tbw-filter-clear-btn",F.textContent="Clear Filter",F.addEventListener("click",()=>{t.clearFilter()}),z.appendChild(F),e.appendChild(z)}renderDateFilterPanel(e,t,i){const{field:n,column:r}=t,o=r.filterParams,s=r.editorParams,l=i.filter(e=>e instanceof Date||"string"==typeof e&&!isNaN(Date.parse(e))).map(e=>e instanceof Date?e:new Date(e)).filter(e=>!isNaN(e.getTime())),a=l.length>0?new Date(Math.min(...l.map(e=>e.getTime()))):null,d=l.length>0?new Date(Math.max(...l.map(e=>e.getTime()))):null,c=e=>e?e.toISOString().split("T")[0]:"",h=e=>e?"string"==typeof e?e:"number"==typeof e?c(new Date(e)):"":"",u=h(o?.min)||h(s?.min)||c(a),g=h(o?.max)||h(s?.max)||c(d),p=this.filters.get(n);let f="",w="";const m="blank"===p?.operator;"between"===p?.operator?(f=h(p.value)||"",w=h(p.valueTo)||""):"greaterThanOrEqual"===p?.operator?f=h(p.value)||"":"lessThanOrEqual"===p?.operator&&(w=h(p.value)||"");const b=document.createElement("div");b.className="tbw-filter-date-range";const v=document.createElement("div");v.className="tbw-filter-date-group";const y=document.createElement("label");y.textContent="From",y.className="tbw-filter-range-label";const C=document.createElement("input");C.type="date",C.className="tbw-filter-date-input",u&&(C.min=u),g&&(C.max=g),C.value=f,v.appendChild(y),v.appendChild(C),b.appendChild(v);const x=document.createElement("span");x.className="tbw-filter-range-separator",x.textContent="–",b.appendChild(x);const E=document.createElement("div");E.className="tbw-filter-date-group";const R=document.createElement("label");R.textContent="To",R.className="tbw-filter-range-label";const S=document.createElement("input");S.type="date",S.className="tbw-filter-date-input",u&&(S.min=u),g&&(S.max=g),S.value=w,E.appendChild(R),E.appendChild(S),b.appendChild(E),e.appendChild(b);const _=document.createElement("label");_.className="tbw-filter-blank-option";const A=document.createElement("input");A.type="checkbox",A.className="tbw-filter-blank-checkbox",A.checked=m;const k=document.createTextNode("Show only blank");_.appendChild(A),_.appendChild(k);const T=e=>{C.disabled=e,S.disabled=e,b.classList.toggle("tbw-filter-disabled",e)};T(m),A.addEventListener("change",()=>{T(A.checked)}),e.appendChild(_);const L=document.createElement("div");L.className="tbw-filter-buttons";const M=document.createElement("button");M.className="tbw-filter-apply-btn",M.textContent="Apply",M.addEventListener("click",()=>{if(A.checked)return void t.applyTextFilter("blank","");const e=C.value,i=S.value;e&&i?t.applyTextFilter("between",e,i):e?t.applyTextFilter("greaterThanOrEqual",e):i?t.applyTextFilter("lessThanOrEqual",i):t.clearFilter()}),L.appendChild(M);const I=document.createElement("button");I.className="tbw-filter-clear-btn",I.textContent="Clear Filter",I.addEventListener("click",()=>{t.clearFilter()}),L.appendChild(I),e.appendChild(L)}applySetFilter(e,t,i){this.excludedValues.set(e,new Set(t)),0===t.length?this.filters.delete(e):this.filters.set(e,{field:e,type:"set",operator:"notIn",value:t,...void 0!==i&&{valueTo:i}}),this.applyFiltersInternal()}applyTextFilter(e,t,i,n){this.filters.set(e,{field:e,type:"text",operator:t,value:i,valueTo:n}),this.applyFiltersInternal()}applyFiltersInternal(e){this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null;const t=[...this.filters.values()];if(this.config.filterHandler){const i=this.grid;i.setAttribute("aria-busy","true");const n=this.config.filterHandler(t,this.sourceRows),r=n=>{i.removeAttribute("aria-busy"),this.cachedResult=n,this.grid.rows=n,e||this.emit("filter-change",{filters:t,filteredRowCount:n.length,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:t}),this.requestRender()};return void(n&&"function"==typeof n.then?n.then(r):r(n))}e||this.emit("filter-change",{filters:t,filteredRowCount:0,selected:this.computeSelected()}),this.emitPluginEvent("filter-applied",{filters:t}),this.requestRender()}getColumnState(e){const t=this.filters.get(e);if(t)return{filter:{type:t.type,operator:t.operator,value:t.value,valueTo:t.valueTo}}}applyColumnState(e,t){if(!t.filter)return void this.filters.delete(e);const i={field:e,type:t.filter.type,operator:t.filter.operator,value:t.filter.value,valueTo:t.filter.valueTo};this.filters.set(e,i),this.cachedResult=null,this.cacheKey=null,this.cachedInputSpot=null}}function ti(e){if(!e.length)return[];const t=new Map,i=[],n=(e,t)=>{if(!t.length)return;const n=i[i.length-1];n&&n.implicit&&n.firstIndex+n.columns.length===e?n.columns.push(...t):i.push({id:"__implicit__"+e,label:void 0,columns:t,firstIndex:e,implicit:!0})};let r=[],o=0;return e.forEach((e,s)=>{const l=e.group;if(!l)return 0===r.length&&(o=s),void r.push(e);r.length&&(n(o,r.slice()),r=[]);const a="string"==typeof l?l:l.id;let d=t.get(a);d||(d={id:a,label:"string"==typeof l?void 0:l.label,columns:[],firstIndex:s},t.set(a,d),i.push(d)),d.columns.push(e)}),r.length&&n(o,r),1===i.length&&i[0].implicit&&i[0].columns.length===e.length?[]:i}const ii={sum:(e,t)=>e.reduce((e,i)=>e+(Number(i[t])||0),0),avg:(e,t)=>{const i=e.reduce((e,i)=>e+(Number(i[t])||0),0);return e.length?i/e.length:0},count:e=>e.length,min:(e,t)=>e.length?Math.min(...e.map(e=>Number(e[t])||1/0)):0,max:(e,t)=>e.length?Math.max(...e.map(e=>Number(e[t])||-1/0)):0,first:(e,t)=>e[0]?.[t],last:(e,t)=>e[e.length-1]?.[t]},ni=new Map,ri={register(e,t){ni.set(e,t)},unregister(e){ni.delete(e)},get(e){if(void 0!==e)return"function"==typeof e?e:ni.get(e)??ii[e]},run(e,t,i,n){const r=this.get(e);return r?r(t,i,n):void 0},has:e=>ni.has(e)||e in ii,list:()=>[...Object.keys(ii),...ni.keys()]},oi={sum:e=>e.reduce((e,t)=>e+t,0),avg:e=>e.length?e.reduce((e,t)=>e+t,0)/e.length:0,count:e=>e.length,min:e=>e.length?Math.min(...e):0,max:e=>e.length?Math.max(...e):0,first:e=>e[0]??0,last:e=>e[e.length-1]??0};ri.register.bind(ri),ri.unregister.bind(ri);const si=ri.get.bind(ri),li=ri.run.bind(ri);function ai({rows:e,config:t,expanded:i,initialExpanded:n}){const r=t.groupOn;if("function"!=typeof r)return[];const o={key:"__root__",value:null,depth:-1,rows:[],children:new Map};if(e.forEach(e=>{let t=r(e);null==t||!1===t?t=["__ungrouped__"]:Array.isArray(t)||(t=[t]);let i=o;t.forEach((e,t)=>{const n=null==e?"∅":String(e),r="__root__"===i.key?n:i.key+"||"+n;let o=i.children.get(n);o||(o={key:r,value:e,depth:t,rows:[],children:new Map,parent:i},i.children.set(n,o)),i=o}),i.rows.push(e)}),1===o.children.size&&o.children.has("__ungrouped__")){if(o.children.get("__ungrouped__").rows.length===e.length)return[]}const s=new Set([...i,...n??[]]),l=[],a=t=>{if(t===o)return void t.children.forEach(e=>a(e));const i=s.has(t.key);l.push({kind:"group",key:t.key,value:t.value,depth:t.depth,rows:t.rows,expanded:i}),i&&(t.children.size?t.children.forEach(e=>a(e)):t.rows.forEach(t=>l.push({kind:"data",row:t,rowIndex:e.indexOf(t)})))};return a(o),l}ri.list.bind(ri);function di(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}function ci(e,t,i,n){const r=document.createElement("div");r.className="master-detail-row",r.setAttribute("data-detail-for",String(t)),r.setAttribute("role","row");const o=document.createElement("div");o.className="master-detail-cell",o.setAttribute("role","cell"),o.style.gridColumn=`1 / ${n+1}`;const s=i(e,t);return"string"==typeof s?o.innerHTML=s:s instanceof HTMLElement&&o.appendChild(s),r.appendChild(o),r}class hi extends rt{name="masterDetail";styles="@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-right:none!important;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1 / 3}tbw-grid .master-detail-expander{display:flex;align-items:center;justify-content:center;width:100%;height:100%}tbw-grid .master-detail-toggle{cursor:pointer;opacity:.7;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center}tbw-grid .master-detail-toggle:hover{opacity:1}tbw-grid .master-detail-row{grid-column:1 / -1;display:grid;background:var(--tbw-master-detail-bg, var(--tbw-color-row-alt));border-bottom:1px solid var(--tbw-master-detail-border, var(--tbw-color-border));overflow:hidden}tbw-grid .master-detail-cell{padding:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));overflow:auto}tbw-grid .master-detail-row.tbw-expanding{animation:tbw-detail-expand var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .master-detail-row.tbw-collapsing{animation:tbw-detail-collapse var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-detail-expand{0%{opacity:0;max-height:0;padding-top:0;padding-bottom:0}to{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem);padding-top:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));padding-bottom:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem))}}@keyframes tbw-detail-collapse{0%{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem)}to{opacity:0;max-height:0}}}";get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,animation:"slide"}}attach(e){super.attach(e),this.parseLightDomDetail()}parseLightDomDetail(){const e=this.grid;if(!e||"function"!=typeof e.querySelector)return;const t=e.querySelector("tbw-grid-detail");if(!t)return;const i=e;if(i.__frameworkAdapter?.parseDetailElement){const e=i.__frameworkAdapter.parseDetailElement(t);if(e)return void(this.config={...this.config,detailRenderer:e})}const n=t.getAttribute("animation"),r=t.getAttribute("show-expand-column"),o=t.getAttribute("expand-on-row-click"),s=t.getAttribute("collapse-on-click-outside"),l=t.getAttribute("height"),a={};null!==n&&(a.animation="false"!==n&&n),null!==r&&(a.showExpandColumn="false"!==r),null!==o&&(a.expandOnRowClick="true"===o),null!==s&&(a.collapseOnClickOutside="true"===s),null!==l&&(a.detailHeight="auto"===l?"auto":parseInt(l,10));const d=t.innerHTML.trim();d&&!this.config.detailRenderer&&(a.detailRenderer=(e,t)=>y(C(d,{value:e,row:e}))),Object.keys(a).length>0&&(this.config={...this.config,...a})}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}animateExpand(e,t,i){if(!this.isAnimationEnabled||!1===this.animationStyle)return!1;e.classList.add("tbw-expanding");let n=!1;const r=()=>{n||(n=!0,e.classList.remove("tbw-expanding"),void 0!==t&&void 0!==i&&this.#pt(e,t,i))};return e.addEventListener("animationend",r,{once:!0}),setTimeout(r,this.animationDuration+50),!0}animateCollapse(e,t){if(!this.isAnimationEnabled||!1===this.animationStyle)return void t();e.classList.add("tbw-collapsing");const i=()=>{e.classList.remove("tbw-collapsing"),t()};e.addEventListener("animationend",i,{once:!0}),setTimeout(i,this.animationDuration+50)}#pt(e,t,i){if(!e.isConnected)return;const n=e.offsetHeight;if(n>0){const e=this.measuredDetailHeights.get(t);this.measuredDetailHeights.set(t,n),e!==n&&this.grid.invalidateRowHeight(i)}}expandedRows=new Set;detailElements=new Map;measuredDetailHeights=new Map;rowsToAnimate=new Set;static DEFAULT_DETAIL_HEIGHT=150;getDetailHeight(e){const t=this.detailElements.get(e);if(t){if(!(t.classList.contains("tbw-expanding")||t.classList.contains("tbw-collapsing"))){const i=t.offsetHeight;if(i>0)return this.measuredDetailHeights.set(e,i),i}}const i=this.measuredDetailHeights.get(e);return i&&i>0?i:"number"==typeof this.config?.detailHeight?this.config.detailHeight:hi.DEFAULT_DETAIL_HEIGHT}toggleAndEmit(e,t){this.expandedRows=di(this.expandedRows,e);const i=this.expandedRows.has(e);i&&this.rowsToAnimate.add(e),this.emit("detail-expand",{rowIndex:t,row:e,expanded:i}),this.requestRender()}detach(){this.expandedRows.clear(),this.detailElements.clear(),this.measuredDetailHeights.clear(),this.rowsToAnimate.clear()}processColumns(e){if(!(!0===this.config.showExpandColumn||!1!==this.config.showExpandColumn&&!!this.config.detailRenderer))return[...e];const t=[...e],i=function(e){return e.find(Qt)}(t);if(i)return t;const n=(r=this.name,{field:Zt,header:"",width:32,resizable:!1,sortable:!1,filterable:!1,meta:{lockPosition:!0,suppressMovable:!0,expanderColumn:!0,expanderPlugin:r,utility:!0}});var r;return n.viewRenderer=e=>{const{row:t}=e,i=this.expandedRows.has(t),n=document.createElement("span");n.className="master-detail-expander expander-cell";const r=document.createElement("span");return r.className="master-detail-toggle"+(i?" expanded":""),this.setIcon(r,this.resolveIcon(i?"collapse":"expand")),r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.setAttribute("aria-expanded",String(i)),r.setAttribute("aria-label",i?"Collapse details":"Expand details"),n.appendChild(r),n},[n,...t]}onRowClick(e){if(this.config.expandOnRowClick&&this.config.detailRenderer)return this.toggleAndEmit(e.row,e.rowIndex),!1}onCellClick(e){const t=e.originalEvent?.target;if(t?.classList.contains("master-detail-toggle"))return this.toggleAndEmit(e.row,e.rowIndex),!0;this.expandedRows.size>0&&queueMicrotask(()=>this.#ft())}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusCol,i=this.grid._focusRow,n=this.visibleColumns[t];if(!n||!Qt(n))return;const r=this.rows[i];return r?(e.preventDefault(),this.toggleAndEmit(r,i),this.requestRenderWithFocus(),!0):void 0}afterRender(){this.#ft()}onScrollRender(){this.config.detailRenderer&&0!==this.expandedRows.size&&this.#ft()}#ft(){if(!this.config.detailRenderer)return;const e=this.gridElement?.querySelector(".rows");if(!e)return;const t=this.grid,i=t._rowPool,n=t._virtualization?.start??0,r=t._virtualization?.end??0,o=this.columns.length,s=n,l=r,a=new Map;if(i){const t=Math.min(i.length,l-s);for(let n=0;n<t;n++){const t=i[n];t.parentNode===e&&a.set(s+n,t)}}else{const t=e.querySelectorAll(".data-grid-row");for(const e of t){const t=e.querySelector(".cell[data-row]"),i=t?parseInt(t.getAttribute("data-row")??"-1",10):-1;i>=0&&a.set(i,e)}}for(const[d,c]of this.detailElements){const e=this.rows.indexOf(d),t=this.expandedRows.has(d),i=e>=0&&a.has(e);if(!t||!i){const e=this.grid.__frameworkAdapter;if(e?.unmount){const t=c.querySelector(".master-detail-cell"),i=t?.firstElementChild;i&&e.unmount(i)}c.parentNode&&c.remove(),this.detailElements.delete(d)}}for(const[d,c]of a){const e=this.rows[d];if(!e||!this.expandedRows.has(e))continue;const t=this.detailElements.get(e);if(t){t.previousElementSibling!==c&&c.after(t);continue}const i=ci(e,d,this.config.detailRenderer,o);"number"==typeof this.config.detailHeight&&(i.style.height=`${this.config.detailHeight}px`),c.after(i),this.detailElements.set(e,i);const n=this.rowsToAnimate.has(e);n&&this.rowsToAnimate.delete(e);n&&this.animateExpand(i,e,d)||requestAnimationFrame(()=>{this.#pt(i,e,d)})}}getExtraHeight(){let e=0;for(const t of this.expandedRows)e+=this.getDetailHeight(t);return e}getExtraHeightBefore(e){let t=0;for(const i of this.expandedRows){const n=this.rows.indexOf(i);n>=0&&n<e&&(t+=this.getDetailHeight(i))}return t}getRowHeight(e,t){if(!this.expandedRows.has(e))return;return(this.grid.defaultRowHeight??28)+this.getDetailHeight(e)}adjustVirtualStart(e,t,i){if(0===this.expandedRows.size)return e;const n=this.grid?._virtualization?.positionCache;let r=e;if(n&&n.length>0)for(const o of this.expandedRows){const i=this.rows.indexOf(o);if(i<0||i>=e)continue;n[i].offset+n[i].height>t&&i<r&&(r=i)}else{const n=[];for(const e of this.expandedRows){const t=this.rows.indexOf(e);t>=0&&n.push({index:t,row:e})}n.sort((e,t)=>e.index-t.index);let o=0;for(const{index:s,row:l}of n){const n=s*i+o,a=this.getDetailHeight(l);o+=a,s>=e||n+i+a>t&&s<r&&(r=s)}}return r}expand(e){const t=this.rows[e];t&&(this.rowsToAnimate.add(t),this.expandedRows=function(e,t){const i=new Set(e);return i.add(t),i}(this.expandedRows,t),this.requestRender())}collapse(e){const t=this.rows[e];t&&(this.expandedRows=function(e,t){const i=new Set(e);return i.delete(t),i}(this.expandedRows,t),this.requestRender())}toggle(e){const t=this.rows[e];t&&(this.expandedRows=di(this.expandedRows,t),this.expandedRows.has(t)&&this.rowsToAnimate.add(t),this.requestRender())}isExpanded(e){const t=this.rows[e];return!!t&&function(e,t){return e.has(t)}(this.expandedRows,t)}expandAll(){for(const e of this.rows)this.rowsToAnimate.add(e),this.expandedRows.add(e);this.requestRender()}collapseAll(){this.expandedRows.clear(),this.requestRender()}getExpandedRows(){const e=[];for(const t of this.expandedRows){const i=this.rows.indexOf(t);i>=0&&e.push(i)}return e}getDetailElement(e){const t=this.rows[e];return t?this.detailElements.get(t):void 0}refreshDetailRenderer(){const e=this.config.detailRenderer;if(this.config={...this.config,detailRenderer:void 0},this.parseLightDomDetail(),!this.config.detailRenderer&&e&&(this.config={...this.config,detailRenderer:e}),this.config.detailRenderer){const e=this.grid;"function"==typeof e.refreshColumns?e.refreshColumns():this.requestRender()}}}function ui(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 gi(e,t){const i=e.findIndex(e=>e.field===t);return i>=0?i+1:void 0}function pi(e,t){return e.find(e=>e.field===t)?.direction}function fi(e){return e.pinned??e.sticky??e.meta?.pinned??e.meta?.sticky}function wi(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 mi(e,t){const i=fi(e);return!!i&&"left"===wi(i,t)}function bi(e,t){const i=fi(e);return!!i&&"right"===wi(i,t)}function vi(e){return e.some(e=>null!=fi(e))}function yi(e,t){const i=Array.from(e.querySelectorAll(".header-row .cell"));if(!i.length)return;const n=M(e);let r=0;for(const s of t)if(mi(s,n)){const t=i.find(e=>e.getAttribute("data-field")===s.field);t&&(t.classList.add("sticky-left"),t.style.position="sticky",t.style.left=r+"px",e.querySelectorAll(`.data-grid-row .cell[data-field="${s.field}"]`).forEach(e=>{e.classList.add("sticky-left"),e.style.position="sticky",e.style.left=r+"px"}),r+=t.offsetWidth)}let o=0;for(const s of[...t].reverse())if(bi(s,n)){const t=i.find(e=>e.getAttribute("data-field")===s.field);t&&(t.classList.add("sticky-right"),t.style.position="sticky",t.style.right=o+"px",e.querySelectorAll(`.data-grid-row .cell[data-field="${s.field}"]`).forEach(e=>{e.classList.add("sticky-right"),e.style.position="sticky",e.style.right=o+"px"}),o+=t.offsetWidth)}}function Ci(e){e.querySelectorAll(".sticky-left, .sticky-right").forEach(e=>{e.classList.remove("sticky-left","sticky-right"),e.style.position="",e.style.left="",e.style.right=""})}const xi="canMoveColumn";function Ei(e,t){const i=document.createElement("div");i.className="tbw-pinned-rows",i.setAttribute("role","presentation"),i.setAttribute("aria-live","polite");const n=document.createElement("div");n.className="tbw-pinned-rows-left";const r=document.createElement("div");r.className="tbw-pinned-rows-center";const o=document.createElement("div");if(o.className="tbw-pinned-rows-right",!1!==e.showRowCount){const e=document.createElement("span");e.className="tbw-status-panel tbw-status-panel-row-count",e.textContent=`Total: ${t.totalRows} rows`,n.appendChild(e)}if(e.showFilteredCount&&t.filteredRows!==t.totalRows){const e=document.createElement("span");e.className="tbw-status-panel tbw-status-panel-filtered-count",e.textContent=`Filtered: ${t.filteredRows}`,n.appendChild(e)}if(e.showSelectedCount&&t.selectedRows>0){const e=document.createElement("span");e.className="tbw-status-panel tbw-status-panel-selected-count",e.textContent=`Selected: ${t.selectedRows}`,o.appendChild(e)}if(e.customPanels)for(const s of e.customPanels){const e=Ti(s,t);switch(s.position){case"left":n.appendChild(e);break;case"center":r.appendChild(e);break;case"right":o.appendChild(e)}}return i.appendChild(n),i.appendChild(r),i.appendChild(o),i}function Ri(e){const t=document.createElement("div");return t.className=`tbw-aggregation-rows tbw-aggregation-rows-${e}`,t.setAttribute("role","presentation"),t}function Si(e,t,i,n,r=!1){e.innerHTML="";for(const o of t){const t=document.createElement("div");t.className="tbw-aggregation-row",t.setAttribute("role","presentation"),o.id&&t.setAttribute("data-aggregation-id",o.id);o.fullWidth??r?_i(t,o,i,n):Ai(t,o,i,n),e.appendChild(t)}}function _i(e,t,i,n){const r=document.createElement("div");r.className="tbw-aggregation-cell tbw-aggregation-cell-full",r.style.gridColumn="1 / -1";const o="function"==typeof t.label?t.label(n,i):t.label;if(o){const e=document.createElement("span");e.className="tbw-aggregation-label",e.textContent=o,r.appendChild(e)}const s=function(e,t,i){const n=e.aggregators&&Object.keys(e.aggregators).length>0,r=e.cells&&Object.keys(e.cells).length>0;if(!n&&!r)return null;const o=document.createElement("span");o.className="tbw-aggregation-aggregates";for(const s of t){const{value:t,formatter:n}=ki(e,s,i);if(null!=t){const e=document.createElement("span");e.className="tbw-aggregation-aggregate",e.setAttribute("data-field",s.field);const i=s.header??s.field,r=n?n(t,s.field,s):String(t);e.textContent=`${i}: ${r}`,o.appendChild(e)}}return o.children.length>0?o:null}(t,i,n);s&&r.appendChild(s),e.appendChild(r)}function Ai(e,t,i,n){for(const r of i){const i=document.createElement("div");i.className="tbw-aggregation-cell",i.setAttribute("data-field",r.field);const{value:o,formatter:s}=ki(t,r,n);i.textContent=null!=o?s?s(o,r.field,r):String(o):"",e.appendChild(i)}}function ki(e,t,i){let n,r;const o=e.aggregators?.[t.field];if(o)if("object"==typeof(s=o)&&null!==s&&"aggFunc"in s){const e=si(o.aggFunc);e&&(n=e(i,t.field,t)),r=o.formatter}else{const e=si(o);e&&(n=e(i,t.field,t))}else if(e.cells&&Object.prototype.hasOwnProperty.call(e.cells,t.field)){const r=e.cells[t.field];n="function"==typeof r?r(i,t.field,t):r}var s;return{value:n,formatter:r}}function Ti(e,t){const i=document.createElement("div");i.className="tbw-status-panel tbw-status-panel-custom",i.id=`status-panel-${e.id}`;const n=e.render(t);return"string"==typeof n?i.innerHTML=n:i.appendChild(n),i}function Li(e,t,i,n,r){return{totalRows:e.length,filteredRows:r?.cachedResult?.length??e.length,selectedRows:n?.selected?.size??0,columns:t,rows:e,grid:i}}const Mi=function(e){return oi[e]??oi.sum};function Ii(e,t){return[...e,t].join("|")}function Pi(e,t){const i=t.rowGroupFields??[],n=t.columnGroupFields??[],r=t.valueFields??[],o=function(e,t){if(0===t.length)return["value"];const i=new Set;for(const n of e){const e=t.map(e=>String(n[e]??"")).join("|");i.add(e)}return[...i].sort()}(e,n),s=Hi(e,i,n,o,r,0,""),l=function(e,t,i){const n={};function r(e){for(const o of e)if(o.isGroup&&o.children?.length)o.children&&r(o.children);else for(const e of t)for(const t of i){const i=Ii([e],t.field);n[i]=(n[i]??0)+(o.values[i]??0)}}return r(e),n}(s,o,r);return{rows:s,columnKeys:o,totals:l,grandTotal:Object.values(l).reduce((e,t)=>e+t,0)}}function Hi(e,t,i,n,r,o,s){const l=[];if(0===t.length){const t=Di(e,i,n,r),a=zi(t);return l.push({rowKey:s||"all",rowLabel:s||"All",depth:o,values:t,total:a,isGroup:!1,rowCount:e.length}),l}const a=t[0],d=t.slice(1),c=d.length>0,h=function(e,t){const i=new Map;for(const n of e){const e=String(n[t]??""),r=i.get(e);r?r.push(n):i.set(e,[n])}return i}(e,a);for(const[u,g]of h){const e=s?`${s}|${u}`:u,t=Di(g,i,n,r),a=zi(t);let h;c&&(h=Hi(g,d,i,n,r,o+1,e)),l.push({rowKey:e,rowLabel:u||"(blank)",depth:o,values:t,total:a,isGroup:c,children:h,rowCount:g.length})}return l}function Di(e,t,i,n){const r={};for(const o of i)for(const i of n){const n=(t.length>0?e.filter(e=>t.map(t=>String(e[t]??"")).join("|")===o):e).map(e=>Number(e[i.field])||0),s=Mi(i.aggFunc),l=n.length>0?s(n):null;r[Ii([o],i.field)]=l}return r}function zi(e){let t=0;for(const i of Object.values(e))t+=i??0;return t}const Oi=["sum","avg","count","min","max","first","last"];function Fi(e,t,i,n){const r=new AbortController,o={config:t,callbacks:n,signal:r.signal},s=document.createElement("div");return s.className="tbw-pivot-panel",s.appendChild(qi("Options",()=>function(e,t){const{config:i,callbacks:n,signal:r}=t,o=document.createElement("div");return o.className="tbw-pivot-options",o.appendChild(Vi("Enable Pivot View",e,e=>{n.onTogglePivot(e)},r)),o.appendChild(Vi("Show Row Totals",i.showTotals??!0,e=>{n.onOptionChange("showTotals",e)},r)),o.appendChild(Vi("Show Grand Total",i.showGrandTotal??!0,e=>{n.onOptionChange("showGrandTotal",e)},r)),o}(i,o))),s.appendChild(qi("Row Groups",()=>Ni("rowGroups",o))),s.appendChild(qi("Column Groups",()=>Ni("columnGroups",o))),s.appendChild(qi("Values",()=>function(e){const{config:t,callbacks:i,signal:n}=e,r=document.createElement("div");r.className="tbw-pivot-drop-zone tbw-pivot-values-zone",r.setAttribute("data-zone","values");const o=t.valueFields??[];if(0===o.length){const e=document.createElement("div");e.className="tbw-pivot-placeholder",e.textContent="Drag numeric fields here for aggregation",r.appendChild(e)}else for(const s of o)r.appendChild(Bi(s,e));return r.addEventListener("dragover",e=>{e.preventDefault(),r.classList.add("drag-over")},{signal:n}),r.addEventListener("dragleave",()=>{r.classList.remove("drag-over")},{signal:n}),r.addEventListener("drop",e=>{e.preventDefault(),r.classList.remove("drag-over");const t=e.dataTransfer?.getData("text/plain");t&&i.onAddValueField(t,"sum")},{signal:n}),r}(o))),s.appendChild(qi("Available Fields",()=>function(e){const{config:t,callbacks:i,signal:n}=e,r=document.createElement("div");r.className="tbw-pivot-available-fields";const o=i.getAvailableFields(),s=new Set([...t.rowGroupFields??[],...t.columnGroupFields??[],...t.valueFields?.map(e=>e.field)??[]]),l=o.filter(e=>!s.has(e.field));if(0===l.length){const e=document.createElement("div");e.className="tbw-pivot-placeholder",e.textContent="All fields are in use",r.appendChild(e)}else for(const a of l){const e=document.createElement("div");e.className="tbw-pivot-field-chip available",e.textContent=a.header,e.draggable=!0,e.title=`Drag to add "${a.field}" to a zone`,e.addEventListener("dragstart",t=>{t.dataTransfer?.setData("text/plain",a.field),e.classList.add("dragging")},{signal:n}),e.addEventListener("dragend",()=>{e.classList.remove("dragging")},{signal:n}),r.appendChild(e)}return r}(o))),e.appendChild(s),()=>{r.abort(),s.remove()}}function qi(e,t){const i=document.createElement("div");i.className="tbw-pivot-section";const n=document.createElement("div");n.className="tbw-pivot-section-header",n.textContent=e;const r=document.createElement("div");return r.className="tbw-pivot-section-content",r.appendChild(t()),i.appendChild(n),i.appendChild(r),i}function Ni(e,t){const{config:i,callbacks:n,signal:r}=t,o=document.createElement("div");o.className="tbw-pivot-drop-zone",o.setAttribute("data-zone",e);const s="rowGroups"===e?i.rowGroupFields??[]:i.columnGroupFields??[];if(0===s.length){const e=document.createElement("div");e.className="tbw-pivot-placeholder",e.textContent="Drag fields here or click to add",o.appendChild(e)}else for(const l of s)o.appendChild(Gi(l,e,t));return o.addEventListener("dragover",e=>{e.preventDefault(),o.classList.add("drag-over")},{signal:r}),o.addEventListener("dragleave",()=>{o.classList.remove("drag-over")},{signal:r}),o.addEventListener("drop",t=>{t.preventDefault(),o.classList.remove("drag-over");const i=t.dataTransfer?.getData("text/plain");i&&n.onAddFieldToZone(i,e)},{signal:r}),o}function Gi(e,t,i){const{callbacks:n,signal:r}=i,o=document.createElement("div");o.className="tbw-pivot-field-chip",o.draggable=!0;const s=n.getAvailableFields().find(t=>t.field===e),l=document.createElement("span");l.className="tbw-pivot-chip-label",l.textContent=s?.header??e;const a=document.createElement("button");return a.className="tbw-pivot-chip-remove",a.innerHTML="×",a.title="Remove field",a.addEventListener("click",i=>{i.stopPropagation(),n.onRemoveFieldFromZone(e,t)},{signal:r}),o.appendChild(l),o.appendChild(a),o.addEventListener("dragstart",i=>{i.dataTransfer?.setData("text/plain",e),i.dataTransfer?.setData("source-zone",t),o.classList.add("dragging")},{signal:r}),o.addEventListener("dragend",()=>{o.classList.remove("dragging")},{signal:r}),o}function Bi(e,t){const{callbacks:i,signal:n}=t,r=document.createElement("div");r.className="tbw-pivot-field-chip tbw-pivot-value-chip";const o=i.getAvailableFields().find(t=>t.field===e.field),s=document.createElement("div");s.className="tbw-pivot-value-label-wrapper";const l=document.createElement("span");l.className="tbw-pivot-chip-label",l.textContent=o?.header??e.field;const a=document.createElement("select");a.className="tbw-pivot-agg-select",a.title="Aggregation function";for(const c of Oi){const t=document.createElement("option");t.value=c,t.textContent=c.toUpperCase(),t.selected=c===e.aggFunc,a.appendChild(t)}a.addEventListener("change",()=>{i.onUpdateValueAggFunc(e.field,a.value)},{signal:n});const d=document.createElement("button");return d.className="tbw-pivot-chip-remove",d.innerHTML="×",d.title="Remove value field",d.addEventListener("click",t=>{t.stopPropagation(),i.onRemoveValueField(e.field)},{signal:n}),s.appendChild(l),s.appendChild(a),r.appendChild(s),r.appendChild(d),r}function Vi(e,t,i,n){const r=document.createElement("label");r.className="tbw-pivot-checkbox";const o=document.createElement("input");o.type="checkbox",o.checked=t,o.addEventListener("change",()=>i(o.checked),{signal:n});const s=document.createElement("span");return s.textContent=e,r.appendChild(o),r.appendChild(s),r}class $i extends rt{name="pivot";styles='@layer tbw-plugins{.pivot-group-row{display:grid;grid-template-columns:var(--tbw-column-template);font-weight:600;background:var(--tbw-pivot-group-bg, var(--tbw-color-row-alt));min-height:var(--tbw-row-height);border-bottom:var(--tbw-row-divider)}.pivot-group-row:hover{background:var(--tbw-pivot-group-hover, var(--tbw-color-row-hover))}.pivot-leaf-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-pivot-leaf-bg, var(--tbw-color-bg));min-height:var(--tbw-row-height);border-bottom:var(--tbw-row-divider)}.pivot-grand-total-row{display:grid;grid-template-columns:var(--tbw-column-template);font-weight:700;background:var(--tbw-pivot-grand-total-bg, var(--tbw-color-header-bg));min-height:var(--tbw-row-height);border-top:2px solid var(--tbw-color-border-strong)}.pivot-grand-total-row>.cell{display:flex;align-items:center;padding:var(--tbw-cell-padding);border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;min-width:0}.pivot-grand-total-row>.cell:last-child{border-right:0}.pivot-grand-total-footer{position:sticky;bottom:0;z-index:var(--tbw-z-layer-pinned-rows, 20);background:var(--tbw-pivot-grand-total-bg, var(--tbw-color-header-bg));min-width:fit-content}.pivot-group-row>.cell,.pivot-leaf-row>.cell{display:flex;align-items:center;padding:var(--tbw-cell-padding);border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;min-width:0}.pivot-group-row>.cell:last-child,.pivot-leaf-row>.cell:last-child{border-right:0}.pivot-toggle{display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-pivot-toggle-size, var(--tbw-toggle-size, 1.25em));height:var(--tbw-pivot-toggle-size, var(--tbw-toggle-size, 1.25em));margin-right:var(--tbw-spacing-sm, .375em);border:none;background:transparent;cursor:pointer;color:var(--tbw-pivot-toggle-color, var(--tbw-color-fg-muted));border-radius:var(--tbw-border-radius);transition:background var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease),color var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease)}.pivot-toggle:hover{background:var(--tbw-pivot-toggle-hover-bg, var(--tbw-color-row-hover));color:var(--tbw-pivot-toggle-hover-color, var(--tbw-color-fg))}.pivot-toggle:focus{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}.pivot-label{font-weight:inherit}.pivot-count{color:var(--tbw-pivot-count-color, var(--tbw-color-fg-muted));font-size:.9em;font-weight:400}.pivot-total-row{font-weight:700;border-top:2px solid var(--tbw-pivot-border, var(--tbw-color-border-strong))}[data-pivot-depth="1"]{--tbw-pivot-depth: 1}[data-pivot-depth="2"]{--tbw-pivot-depth: 2}[data-pivot-depth="3"]{--tbw-pivot-depth: 3}[data-pivot-depth="4"]{--tbw-pivot-depth: 4}.tbw-pivot-panel{display:flex;flex-direction:column;gap:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));padding:var(--tbw-panel-padding, var(--tbw-spacing-lg, .75rem));height:100%;overflow-y:auto;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-pivot-section{border:1px solid var(--tbw-pivot-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius);background:var(--tbw-pivot-section-bg, var(--tbw-color-bg))}.tbw-pivot-section-header{padding:var(--tbw-button-padding, var(--tbw-spacing-md, .5rem) var(--tbw-spacing-lg, .75rem));font-weight:600;background:var(--tbw-pivot-header-bg, var(--tbw-color-header-bg));border-bottom:1px solid var(--tbw-pivot-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius) var(--tbw-border-radius) 0 0}.tbw-pivot-section-content{padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-pivot-toggle-wrapper{display:flex;align-items:center}.tbw-pivot-toggle-label{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));cursor:pointer}.tbw-pivot-toggle-label input{width:var(--tbw-icon-size, 1rem);height:var(--tbw-icon-size, 1rem);cursor:pointer}.tbw-pivot-drop-zone{min-height:60px;padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));border:2px dashed var(--tbw-pivot-drop-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius);background:var(--tbw-pivot-drop-bg, var(--tbw-color-row-alt));display:flex;flex-wrap:wrap;gap:var(--tbw-spacing-sm, .375rem);align-content:flex-start;transition:all .15s ease}.tbw-pivot-drop-zone.drag-over{border-color:var(--tbw-color-accent);background:var(--tbw-pivot-drop-active, var(--tbw-focus-background))}.tbw-pivot-placeholder{color:var(--tbw-color-fg-muted);font-style:italic;padding:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));text-align:center;width:100%}.tbw-pivot-field-chip{display:inline-flex;align-items:center;gap:var(--tbw-spacing-sm, .375rem);padding:var(--tbw-button-padding-sm, var(--tbw-spacing-xs, .25rem) var(--tbw-spacing-md, .5rem));background:var(--tbw-pivot-chip-bg, var(--tbw-color-header-bg));border:1px solid var(--tbw-pivot-chip-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius);cursor:grab;font-size:var(--tbw-font-size-xs, .75rem);transition:all .15s ease}.tbw-pivot-field-chip:hover{background:var(--tbw-pivot-chip-hover, var(--tbw-color-row-hover));border-color:var(--tbw-color-accent)}.tbw-pivot-field-chip.available{background:var(--tbw-color-bg)}.tbw-pivot-field-chip.dragging{opacity:.5;cursor:grabbing}.tbw-pivot-chip-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:120px}.tbw-pivot-chip-remove{display:flex;align-items:center;justify-content:center;width:var(--tbw-icon-size, 1rem);height:var(--tbw-icon-size, 1rem);padding:0;border:none;background:transparent;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-sm, .875rem);font-weight:700;cursor:pointer;border-radius:50%;transition:all .15s ease}.tbw-pivot-chip-remove:hover{background:var(--tbw-pivot-chip-remove-hover-bg, var(--tbw-color-accent));color:var(--tbw-pivot-chip-remove-hover-fg, var(--tbw-color-accent-fg))}.tbw-pivot-value-chip{padding:var(--tbw-button-padding-sm, var(--tbw-spacing-xs, .25rem) var(--tbw-spacing-md, .5rem))}.tbw-pivot-value-label-wrapper{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));flex:1;min-width:0}.tbw-pivot-agg-select{padding:var(--tbw-spacing-xs, .125rem) var(--tbw-spacing-xs, .25rem);font-size:var(--tbw-font-size-xs, .6875rem);border:1px solid var(--tbw-color-border);border-radius:var(--tbw-border-radius);background:var(--tbw-color-bg);cursor:pointer}.tbw-pivot-available-fields{display:flex;flex-wrap:wrap;gap:var(--tbw-spacing-sm, .375rem);min-height:40px}.tbw-pivot-options{display:flex;flex-direction:column;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-pivot-checkbox{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));cursor:pointer}.tbw-pivot-checkbox input{width:var(--tbw-icon-size-sm, .875rem);height:var(--tbw-icon-size-sm, .875rem);cursor:pointer}.pivot-group-row.tbw-pivot-slide-in,.pivot-leaf-row.tbw-pivot-slide-in{animation:tbw-pivot-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-pivot-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.pivot-group-row.tbw-pivot-fade-in,.pivot-leaf-row.tbw-pivot-fade-in{animation:tbw-pivot-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-pivot-fade-in{0%{opacity:0}to{opacity:1}}}';static PANEL_ID="pivot";get defaultConfig(){return{active:!0,showTotals:!0,showGrandTotal:!0,showToolPanel:!0,animation:"slide"}}isActive=!1;hasInitialized=!1;pivotResult=null;fieldHeaderMap=new Map;expandedKeys=new Set;defaultExpanded=!0;userHasToggledExpand=!1;originalColumns=[];panelContainer=null;grandTotalFooter=null;previousVisibleKeys=new Set;keysToAnimate=new Set;hasValidPivotConfig(){return(this.config.valueFields?.length??0)>0}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detach(){this.isActive=!1,this.hasInitialized=!1,this.pivotResult=null,this.fieldHeaderMap.clear(),this.originalColumns=[],this.panelContainer=null,this.cleanupGrandTotalFooter(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.userHasToggledExpand=!1}getToolPanel(){if(!1!==(this.config?.showToolPanel??this.userConfig?.showToolPanel??!0))return{id:$i.PANEL_ID,title:"Pivot",icon:"⊞",tooltip:"Configure pivot table",order:90,render:e=>this.renderPanel(e)}}processRows(e){if(!this.hasInitialized&&!1!==this.config.active&&this.hasValidPivotConfig()&&(this.hasInitialized=!0,this.isActive=!0),!this.isActive)return[...e];const t=function(e){const t=[];return e.rowGroupFields?.length||e.columnGroupFields?.length||t.push("At least one row or column group field is required"),e.valueFields?.length||t.push("At least one value field is required"),t}(this.config);if(t.length>0)return this.warn(`Config errors: ${t.join(", ")}`),[...e];this.buildFieldHeaderMap(),this.defaultExpanded=this.config.defaultExpanded??!0,this.pivotResult=Pi(e,this.config),0===this.expandedKeys.size&&this.defaultExpanded&&!this.userHasToggledExpand&&this.expandAllKeys();const i=this.config.indentWidth??20,n=function(e,t,i=!0){const n=[];function r(e){n.push(e);const o=t?t.has(e.rowKey):i;if(e.children&&o)for(const t of e.children)r(t)}for(const o of e)r(o);return n}(this.pivotResult.rows,this.expandedKeys,this.defaultExpanded).map(e=>({__pivotRowKey:e.rowKey,__pivotLabel:e.rowLabel,__pivotDepth:e.depth,__pivotIsGroup:e.isGroup,__pivotHasChildren:Boolean(e.children?.length),__pivotExpanded:this.expandedKeys.has(e.rowKey),__pivotRowCount:e.rowCount??0,__pivotIndent:e.depth*i,__pivotTotal:e.total,...e.values}));this.keysToAnimate.clear();const r=new Set;for(const o of n){const e=o.__pivotRowKey;r.add(e),!this.previousVisibleKeys.has(e)&&o.__pivotDepth>0&&this.keysToAnimate.add(e)}return this.previousVisibleKeys=r,n}processColumns(e){if(!this.isActive||!this.pivotResult)return[...e];const t=[],i=(this.config.rowGroupFields??[]).map(e=>this.fieldHeaderMap.get(e)??e).join(" / ");t.push({field:"__pivotLabel",header:i||"Group",width:200});for(const n of this.pivotResult.columnKeys)for(const e of this.config.valueFields??[]){const i=Ii([n],e.field),r=e.header||this.fieldHeaderMap.get(e.field)||e.field;t.push({field:i,header:`${n} - ${r} (${e.aggFunc})`,width:120,type:"number"})}return this.config.showTotals&&t.push({field:"__pivotTotal",header:"Total",width:100,type:"number"}),t}renderRow(e,t,i){const n=e;return n.__pivotRowKey&&n.__pivotHasChildren?function(e,t,i){return t.className="data-grid-row pivot-group-row",t.setAttribute("data-pivot-depth",String(e.__pivotDepth??0)),t.setAttribute("data-pivot-key",String(e.__pivotRowKey??"")),t.setAttribute("role","row"),t.innerHTML="",i.columns.forEach((n,r)=>{const o=document.createElement("div");if(o.className="cell",o.setAttribute("data-col",String(r)),o.setAttribute("data-row",String(i.rowIndex)),o.setAttribute("role","gridcell"),0===r){const t=Number(e.__pivotIndent)||0;o.style.paddingLeft=`${t}px`;const n=String(e.__pivotRowKey),r=document.createElement("button");r.type="button",r.className="pivot-toggle",r.setAttribute("aria-label",e.__pivotExpanded?"Collapse group":"Expand group"),i.setIcon(r,i.resolveIcon(e.__pivotExpanded?"collapse":"expand")),r.addEventListener("click",e=>{e.stopPropagation(),i.onToggle(n)}),o.appendChild(r);const s=document.createElement("span");s.className="pivot-label",s.textContent=String(e.__pivotLabel??""),o.appendChild(s);const l=document.createElement("span");l.className="pivot-count",l.textContent=` (${Number(e.__pivotRowCount)||0})`,o.appendChild(l)}else{const t=e[n.field];o.textContent=null!=t?String(t):""}t.appendChild(o)}),!0}(n,t,{columns:this.gridColumns,rowIndex:i,onToggle:e=>this.toggle(e),resolveIcon:e=>this.resolveIcon(e),setIcon:(e,t)=>this.setIcon(e,t)}):void 0!==n.__pivotRowKey&&this.isActive?function(e,t,i,n){return t.className="data-grid-row pivot-leaf-row",t.setAttribute("data-pivot-depth",String(e.__pivotDepth??0)),t.setAttribute("data-pivot-key",String(e.__pivotRowKey??"")),t.innerHTML="",i.forEach((i,r)=>{const o=document.createElement("div");if(o.className="cell",o.setAttribute("data-col",String(r)),o.setAttribute("data-row",String(n)),o.setAttribute("role","gridcell"),0===r){const t=Number(e.__pivotIndent)||0;o.style.paddingLeft=`${t+20}px`;const i=document.createElement("span");i.className="pivot-label",i.textContent=String(e.__pivotLabel??""),o.appendChild(i)}else{const t=e[i.field];o.textContent=null!=t?String(t):""}t.appendChild(o)}),!0}(n,t,this.gridColumns,i):(this.cleanupPivotStyling(t),!1)}cleanupPivotStyling(e){(e.classList.contains("pivot-group-row")||e.classList.contains("pivot-leaf-row")||e.classList.contains("pivot-grand-total-row"))&&(e.classList.remove("pivot-group-row","pivot-leaf-row","pivot-grand-total-row"),e.classList.add("data-grid-row"),e.removeAttribute("data-pivot-depth"),e.innerHTML="")}onKeyDown(e){if(" "!==e.key)return;if(!this.isActive)return;const t=this.grid._focusRow,i=this.rows[t];return i?.__pivotIsGroup&&i.__pivotHasChildren?(e.preventDefault(),this.toggle(i.__pivotRowKey),this.requestRenderWithFocus(),!0):void 0}afterRender(){this.isActive&&this.config.showGrandTotal&&this.pivotResult?this.renderGrandTotalFooter():this.cleanupGrandTotalFooter();const e=this.animationStyle;if(!1===e||0===this.keysToAnimate.size)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const i="fade"===e?"tbw-pivot-fade-in":"tbw-pivot-slide-in";for(const n of t.querySelectorAll(".pivot-group-row, .pivot-leaf-row")){const e=n.dataset.pivotKey;e&&this.keysToAnimate.has(e)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}renderGrandTotalFooter(){if(!this.pivotResult)return;const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-scroll-area")??e.querySelector(".tbw-grid-content")??e.children[0];if(!t)return;this.grandTotalFooter||(this.grandTotalFooter=document.createElement("div"),this.grandTotalFooter.className="pivot-grand-total-footer",t.appendChild(this.grandTotalFooter));const i={__pivotRowKey:"__grandTotal",__pivotLabel:"Grand Total",__pivotIsGrandTotal:!0,__pivotTotal:this.pivotResult.grandTotal,...this.pivotResult.totals};var n,r,o;n=i,r=this.grandTotalFooter,o=this.gridColumns,r.className="pivot-grand-total-row",r.setAttribute("role","presentation"),r.innerHTML="",o.forEach((e,t)=>{const i=document.createElement("div");if(i.className="cell",i.setAttribute("data-col",String(t)),0===t){const e=document.createElement("span");e.className="pivot-label",e.textContent="Grand Total",i.appendChild(e)}else{const t=n[e.field];i.textContent=null!=t?String(t):""}r.appendChild(i)})}cleanupGrandTotalFooter(){this.grandTotalFooter&&(this.grandTotalFooter.remove(),this.grandTotalFooter=null)}toggle(e){this.userHasToggledExpand=!0,this.expandedKeys.has(e)?this.expandedKeys.delete(e):this.expandedKeys.add(e),this.requestRender()}expand(e){this.userHasToggledExpand=!0,this.expandedKeys.add(e),this.requestRender()}collapse(e){this.userHasToggledExpand=!0,this.expandedKeys.delete(e),this.requestRender()}expandAll(){this.userHasToggledExpand=!0,this.expandAllKeys(),this.requestRender()}collapseAll(){this.userHasToggledExpand=!0,this.expandedKeys.clear(),this.requestRender()}expandAllKeys(){if(!this.pivotResult)return;const e=function(e){const t=[];function i(e){if(e.isGroup&&t.push(e.rowKey),e.children)for(const t of e.children)i(t)}for(const n of e)i(n);return t}(this.pivotResult.rows);for(const t of e)this.expandedKeys.add(t)}isExpanded(e){return this.expandedKeys.has(e)}enablePivot(){0===this.originalColumns.length&&this.captureOriginalColumns(),this.isActive=!0,this.requestRender()}disablePivot(){this.isActive=!1,this.pivotResult=null,this.requestRender()}isPivotActive(){return this.isActive}getPivotResult(){return this.pivotResult}setRowGroupFields(e){this.config.rowGroupFields=e,this.requestRender()}setColumnGroupFields(e){this.config.columnGroupFields=e,this.requestRender()}setValueFields(e){this.config.valueFields=e,this.requestRender()}refresh(){this.pivotResult=null,this.requestRender()}showPanel(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes($i.PANEL_ID)||this.grid.toggleToolPanelSection($i.PANEL_ID)}hidePanel(){this.grid.closeToolPanel()}togglePanel(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection($i.PANEL_ID)}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes($i.PANEL_ID)}get gridColumns(){return this.grid.columns??[]}refreshIfActive(){this.isActive&&this.refresh(),this.refreshPanel()}buildFieldHeaderMap(){const e=this.getAvailableFields();this.fieldHeaderMap.clear();for(const t of e)this.fieldHeaderMap.set(t.field,t.header)}getAvailableFields(){return this.originalColumns.length>0?this.originalColumns:this.captureOriginalColumns()}captureOriginalColumns(){try{const e=this.grid.getAllColumns?.()??this.grid.columns??[];return this.originalColumns=e.filter(e=>!e.field.startsWith("__pivot")).map(e=>({field:e.field,header:e.header??e.field})),this.originalColumns}catch{return[]}}renderPanel(e){this.panelContainer=e,0===this.originalColumns.length&&this.captureOriginalColumns();const t={onTogglePivot:e=>{e?this.enablePivot():this.disablePivot(),this.refreshPanel()},onAddFieldToZone:(e,t)=>this.addFieldToZone(e,t),onRemoveFieldFromZone:(e,t)=>this.removeFieldFromZone(e,t),onAddValueField:(e,t)=>this.addValueField(e,t),onRemoveValueField:e=>this.removeValueField(e),onUpdateValueAggFunc:(e,t)=>this.updateValueAggFunc(e,t),onOptionChange:(e,t)=>{this.config[e]=t,this.isActive&&this.refresh()},getAvailableFields:()=>this.getAvailableFields()};return Fi(e,this.config,this.isActive,t)}refreshPanel(){this.panelContainer&&(this.panelContainer.innerHTML="",this.renderPanel(this.panelContainer))}addFieldToZone(e,t){if("rowGroups"===t){const t=this.config.rowGroupFields??[];t.includes(e)||(this.config.rowGroupFields=[...t,e])}else{const t=this.config.columnGroupFields??[];t.includes(e)||(this.config.columnGroupFields=[...t,e])}this.removeFromOtherZones(e,t),this.refreshIfActive()}removeFieldFromZone(e,t){"rowGroups"===t?this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(t=>t!==e):this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(t=>t!==e),this.refreshIfActive()}removeFromOtherZones(e,t){"rowGroups"!==t&&(this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(t=>t!==e)),"columnGroups"!==t&&(this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(t=>t!==e)),"values"!==t&&(this.config.valueFields=(this.config.valueFields??[]).filter(t=>t.field!==e))}addValueField(e,t){const i=this.config.valueFields??[];i.some(t=>t.field===e)||(this.config.valueFields=[...i,{field:e,aggFunc:t}]),this.removeFromOtherZones(e,"values"),this.refreshIfActive()}removeValueField(e){this.config.valueFields=(this.config.valueFields??[]).filter(t=>t.field!==e),this.refreshIfActive()}updateValueAggFunc(e,t){const i=this.config.valueFields??[],n=i.findIndex(t=>t.field===e);n>=0&&(i[n]={...i[n],aggFunc:t},this.config.valueFields=[...i]),this.isActive&&this.refresh()}}const Wi="tbw-print-isolation-style";async function Ki(e,t={}){const{orientation:i="landscape"}=t,n=e.id;document.querySelectorAll(`#${CSS.escape(n)}`).length>1&&console.warn(`[tbw-grid:print] Multiple elements found with id="${n}". Print isolation may not work correctly. Ensure each grid has a unique ID.`),document.getElementById(Wi)?.remove();const r=function(e,t){const i=document.createElement("style");return i.id=Wi,i.textContent=`\n /* Print isolation: hide everything except the target grid */\n @media print {\n /* Hide all body children by default */\n body > *:not(#${e}) {\n display: none !important;\n }\n\n /* But show the grid and ensure it's not hidden by ancestor rules */\n #${e} {\n display: block !important;\n position: static !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n width: 100% !important;\n max-height: none !important;\n margin: 0 !important;\n padding: 0 !important;\n transform: none !important;\n }\n\n /* If grid is nested, we need to show its ancestors too */\n #${e},\n #${e} * {\n visibility: visible !important;\n }\n\n /* Walk up the DOM and show all ancestors of the grid */\n body *:has(> #${e}),\n body *:has(#${e}) {\n display: block !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n position: static !important;\n transform: none !important;\n background: transparent !important;\n border: none !important;\n padding: 0 !important;\n margin: 0 !important;\n }\n\n /* Hide siblings of ancestors (everything that's not in the path to the grid) */\n body *:has(#${e}) > *:not(:has(#${e})):not(#${e}) {\n display: none !important;\n }\n\n /* Page settings */\n @page {\n size: ${t};\n margin: 1cm;\n }\n\n /* Ensure proper print styling */\n body {\n margin: 0 !important;\n padding: 0 !important;\n background: white !important;\n color-scheme: light !important;\n }\n }\n\n /* Screen: also apply isolation for print preview */\n @media screen {\n /* When this stylesheet is active, we're about to print */\n /* No screen-specific rules needed - isolation only applies to print */\n }\n `,i}(n,i);return document.head.appendChild(r),new Promise(e=>{const t=()=>{window.removeEventListener("afterprint",t),document.getElementById(Wi)?.remove(),e()};window.addEventListener("afterprint",t),window.print(),setTimeout(()=>{window.removeEventListener("afterprint",t),document.getElementById(Wi)?.remove(),e()},5e3)})}const Ui={button:!1,orientation:"landscape",warnThreshold:500,maxRows:0,includeTitle:!0,includeTimestamp:!0,title:"",isolate:!1};function ji(e,t,i){if(t===i)return e;if(t<0||t>=e.length)return e;if(i<0||i>e.length)return e;const n=[...e],[r]=n.splice(t,1);return n.splice(i,0,r),n}const Yi="__tbw_row_drag";function Xi(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 Zi(e){const t=Xi(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function Qi(e){return e.map(Zi)}function Ji(e,t,i){return i.some(i=>function(e,t,i){const n=Xi(i);return e>=n.startRow&&e<=n.endRow&&t>=n.startCol&&t<=n.endCol}(e,t,i))}function en(e){const t=[],i=Xi(e);for(let n=i.startRow;n<=i.endRow;n++)for(let e=i.startCol;e<=i.endCol;e++)t.push({row:n,col:e});return t}function tn(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function nn(e,t){const i=Xi(e),n=Xi(t);return i.startRow===n.startRow&&i.startCol===n.startCol&&i.endRow===n.endRow&&i.endCol===n.endCol}const rn="__tbw_checkbox";function on(e,t){return Math.floor(e/t)}async function sn(e,t,i,n){const r=function(e,t){return{start:e*t,end:(e+1)*t}}(t,i);return e.getRows({startRow:r.start,endRow:r.end,sortModel:n.sortModel,filterModel:n.filterModel})}function ln(e,t,i){const n=on(e,t),r=i.get(n);if(!r)return;return r[e%t]}function an(e,t,i){return void 0!==e.id?String(e.id):i?`${i}-${t}`:String(t)}function dn(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}function cn(e,t,i=null,n=0){const r=t.childrenField??"children",o=new Set;for(let s=0;s<e.length;s++){const l=e[s],a=an(l,s,i),d=l[r];if(Array.isArray(d)&&d.length>0){o.add(a);const e=cn(d,t,a,n+1);for(const t of e)o.add(t)}}return o}function hn(e,t,i,n=null,r=0){const o=i.childrenField??"children";for(let s=0;s<e.length;s++){const l=e[s],a=an(l,s,n);if(a===t)return[a];const d=l[o];if(Array.isArray(d)&&d.length>0){const e=hn(d,t,i,a,r+1);if(e)return[a,...e]}}return null}function un(e,t,i,n){const r=hn(e,t,i);if(!r)return n;const o=new Set(n);for(let s=0;s<r.length-1;s++)o.add(r[s]);return o}function gn(e,t="children"){if(!Array.isArray(e)||0===e.length)return!1;for(const i of e){if(!i)continue;const e=i[t];if(Array.isArray(e)&&e.length>0)return!0}return!1}function pn(e,t,i){const n=[...e.undoStack,t];for(;n.length>i;)n.shift();return{undoStack:n,redoStack:[]}}function fn(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 wn(e){if(0===e.redoStack.length)return{newState:e,action:null};const t=[...e.redoStack],i=t.pop();return i?{newState:{undoStack:[...e.undoStack,i],redoStack:t},action:i}:{newState:e,action:null}}function mn(e){const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}class bn extends rt{static dependencies=[{name:"reorder",required:!1,reason:"Enables drag-to-reorder columns in visibility panel"}];static manifest={queries:[{type:"getContextMenuItems",description:'Contributes "Hide column" item to the header context menu'}]};name="visibility";static PANEL_ID="columns";styles='@layer tbw-plugins{.tbw-visibility-content{display:flex;flex-direction:column;height:100%}.tbw-visibility-list{flex:1;overflow-y:auto;padding:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem))}.tbw-visibility-row{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-menu-item-padding, .375rem .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);border-radius:var(--tbw-border-radius, .25rem);position:relative}.tbw-visibility-row:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-row input[type=checkbox]{cursor:pointer}.tbw-visibility-row.locked span{color:var(--tbw-color-fg-muted)}.tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-row.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-label{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));flex:1;cursor:pointer}.tbw-visibility-row.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-row.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-show-all{margin:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding, .5rem .75rem);border:1px solid var(--tbw-visibility-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius, .25rem);background:var(--tbw-visibility-btn-bg, var(--tbw-color-header-bg));color:var(--tbw-color-fg);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-visibility-show-all:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header{display:flex;align-items:center;padding:var(--tbw-menu-item-padding, .375rem .25rem);font-size:var(--tbw-font-size-sm, .8125rem);font-weight:600;color:var(--tbw-color-fg);border-bottom:1px solid var(--tbw-color-border);margin-top:var(--tbw-spacing-sm, .25rem);position:relative}.tbw-visibility-group-header:first-child{margin-top:0}.tbw-visibility-group-header .tbw-visibility-label{gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-visibility-group-header.reorderable{cursor:grab}.tbw-visibility-group-header.reorderable:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header .tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-group-header.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-group-header.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-group-header.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-group-header.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row--grouped{padding-left:calc(var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem)) + .75rem)}}';get defaultConfig(){return{allowHideAll:!1}}columnListElement=null;isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;draggedGroupId=null;draggedGroupFields=[];clearDragClasses(e){e.querySelectorAll(".tbw-visibility-row, .tbw-visibility-group-header").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-move",()=>{this.columnListElement&&requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})},{signal:this.disconnectSignal})}detach(){this.columnListElement=null,this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}handleQuery(e){if("getContextMenuItems"===e.type){const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field)return;if(i.meta?.lockVisibility)return;return[{id:"visibility/hide-column",label:"Hide Column",icon:"👁",order:30,action:()=>this.hideColumn(i.field)}]}}getToolPanel(){return{id:bn.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(bn.PANEL_ID)||this.grid.toggleToolPanelSection(bn.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(bn.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(bn.PANEL_ID)}renderPanelContent(e){const t=document.createElement("div");t.className="tbw-visibility-content";const i=document.createElement("div");i.className="tbw-visibility-list",t.appendChild(i);const n=document.createElement("button");return n.className="tbw-visibility-show-all",n.textContent="Show All",n.addEventListener("click",()=>{this.grid.showAllColumns(),this.rebuildToggles(i)}),t.appendChild(n),this.columnListElement=i,this.rebuildToggles(i),e.appendChild(t),()=>{this.columnListElement=null,t.remove()}}hasReorderPlugin(){const e=this.grid?.getPluginByName?.("reorder");return!(!e||"function"!=typeof e.moveColumn)}rebuildToggles(e){const t=this.hasReorderPlugin();e.innerHTML="";const i=this.grid.getAllColumns().filter(e=>!e.utility),n=this.grid.query("getColumnGrouping"),r=n?.flat().filter(e=>e&&e.fields.length>0)??[];if(0===r.length)return void this.renderFlatColumnList(i,t,e);const o=new Map;for(const l of r)for(const e of l.fields)o.set(e,l);const s=new Set;for(const l of i){const n=o.get(l.field);if(n){if(!s.has(n.id)){s.add(n.id);const r=new Set(n.fields),o=i.filter(e=>r.has(e.field));o.length>0&&this.renderGroupSection(n,o,t,e)}}else{const n=i.indexOf(l);e.appendChild(this.createColumnRow(l,n,t,e))}}}renderGroupSection(e,t,i,n){const r=document.createElement("div");r.className="tbw-visibility-group-header",r.setAttribute("data-group-id",e.id),i&&(r.draggable=!0,r.classList.add("reorderable"),this.setupGroupDragListeners(r,e,n));const o=document.createElement("label");o.className="tbw-visibility-label";const s=document.createElement("input");s.type="checkbox";const l=t.filter(e=>e.visible).length,a=t.every(e=>e.lockVisible);l===t.length?(s.checked=!0,s.indeterminate=!1):0===l?(s.checked=!1,s.indeterminate=!1):(s.checked=!1,s.indeterminate=!0),s.disabled=a,s.addEventListener("change",()=>{const e=s.checked;for(const i of t)i.lockVisible||this.grid.setColumnVisible(i.field,e);setTimeout(()=>this.rebuildToggles(n),0)});const d=document.createElement("span");if(d.textContent=e.label,o.appendChild(s),o.appendChild(d),r.appendChild(o),i){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,this.resolveIcon("dragHandle")),e.title="Drag to reorder group",r.insertBefore(e,o)}n.appendChild(r);const c=this.grid.getAllColumns().filter(e=>!e.utility);for(const h of t){const e=c.findIndex(e=>e.field===h.field),t=this.createColumnRow(h,e,i,n);t.classList.add("tbw-visibility-row--grouped"),n.appendChild(t)}}renderFlatColumnList(e,t,i){const n=this.grid.getAllColumns().filter(e=>!e.utility);for(const r of e){const e=n.findIndex(e=>e.field===r.field);i.appendChild(this.createColumnRow(r,e,t,i))}}createColumnRow(e,t,i,n){const r=e.header||e.field,o=document.createElement("div");o.className=e.lockVisible?"tbw-visibility-row locked":"tbw-visibility-row",o.setAttribute("data-field",e.field),o.setAttribute("data-index",String(t)),i&&mn(e)&&(o.draggable=!0,o.classList.add("reorderable"),this.setupDragListeners(o,e.field,t,n));const s=document.createElement("label");s.className="tbw-visibility-label";const l=document.createElement("input");l.type="checkbox",l.checked=e.visible,l.disabled=e.lockVisible??!1,l.addEventListener("change",()=>{this.grid.toggleColumnVisibility(e.field),setTimeout(()=>this.rebuildToggles(n),0)});const a=document.createElement("span");if(a.textContent=r,s.appendChild(l),s.appendChild(a),i&&mn(e)){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,this.resolveIcon("dragHandle")),e.title="Drag to reorder",o.appendChild(e)}return o.appendChild(s),o}setupGroupDragListeners(e,t,i){e.addEventListener("dragstart",n=>{this.isDragging=!0,this.draggedGroupId=t.id,this.draggedGroupFields=[...t.fields],this.draggedField=null,this.draggedIndex=null,n.dataTransfer&&(n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",`group:${t.id}`)),e.classList.add("dragging"),i.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&e.classList.add("dragging")})}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedGroupId=null,this.draggedGroupFields=[],this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(i)}),e.addEventListener("dragover",n=>{if(n.preventDefault(),!this.isDragging)return;if(this.draggedGroupId===t.id)return;if(!this.draggedGroupId)return;const r=e.getBoundingClientRect(),o=r.top+r.height/2,s=n.clientY<o;this.clearDragClasses(i),e.classList.add("drop-target"),e.classList.toggle("drop-before",s),e.classList.toggle("drop-after",!s)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",n=>{if(n.preventDefault(),!this.isDragging||!this.draggedGroupId||this.draggedGroupId===t.id)return;const r=e.getBoundingClientRect(),o=n.clientY<r.top+r.height/2;this.executeGroupDrop(this.draggedGroupFields,t.fields,o,i)})}executeGroupDrop(e,t,i,n){const r=this.grid.getAllColumns().map(e=>e.field),o=r.filter(t=>!e.includes(t)),s=i?t[0]:t[t.length-1],l=o.indexOf(s);if(-1===l)return;const a=i?l:l+1,d=r.filter(t=>e.includes(t));o.splice(a,0,...d),this.grid.setColumnOrder(o),requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})}setupDragListeners(e,t,i,n){e.addEventListener("dragstart",n=>{this.isDragging=!0,this.draggedField=t,this.draggedIndex=i,this.draggedGroupId=null,this.draggedGroupFields=[],n.dataTransfer&&(n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",t)),e.classList.add("dragging")}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(n)}),e.addEventListener("dragover",r=>{if(r.preventDefault(),!this.isDragging)return;if(this.draggedGroupId){if(e.classList.contains("tbw-visibility-row--grouped"))return}else if(this.draggedField===t)return;const o=e.getBoundingClientRect(),s=o.top+o.height/2;this.dropIndex=r.clientY<s?i:i+1,this.clearDragClasses(n),this.draggedGroupId?(n.querySelector(`.tbw-visibility-group-header[data-group-id="${this.draggedGroupId}"]`)?.classList.add("dragging"),n.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&e.classList.add("dragging")})):this.draggedField&&n.querySelector(`.tbw-visibility-row[data-field="${this.draggedField}"]`)?.classList.add("dragging"),e.classList.add("drop-target"),e.classList.toggle("drop-before",r.clientY<s),e.classList.toggle("drop-after",r.clientY>=s)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",i=>{if(i.preventDefault(),!this.isDragging)return;if(this.draggedGroupId&&this.draggedGroupFields.length>0){if(e.classList.contains("tbw-visibility-row--grouped"))return;const r=e.getBoundingClientRect(),o=i.clientY<r.top+r.height/2;return void this.executeGroupDrop(this.draggedGroupFields,[t],o,n)}const r=this.draggedField,o=this.draggedIndex,s=this.dropIndex;if(null===r||null===o||null===s)return;const l=s>o?s-1:s;if(l!==o){const e=this.grid.getAllColumns(),t=e.filter(e=>!e.utility),i=t[l]?.field,n={field:r,fromIndex:o,toIndex:i?e.findIndex(e=>e.field===i):e.length};this.emit("column-reorder-request",n)}})}}e.BLANK_FILTER_VALUE=Kt,e.BaseGridPlugin=rt,e.ClipboardPlugin=class extends rt{static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:"\t",newline:"\n",quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e);e.addEventListener("paste",e=>this.#wt(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#mt(e.target),!0)}#mt(e){const t=this.#bt();if(t&&0===t.ranges.length){const t=this.#vt(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()}#wt(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const i=ht(t,this.config),n=this.#bt(),r=n?.ranges?.[0],o=r?.from.row??0,s=r?.from.col??0,l=r&&("range"===n?.mode||"row"===n?.mode)&&(r.from.row!==r.to.row||r.from.col!==r.to.col)?{endRow:r.to.row,endCol:r.to.col}:null,a=l?.endCol??this.visibleColumns.length-1,d=this.visibleColumns[s],c=d?{row:o,col:s,field:d.field,bounds:l}:null,h=[],u=i[0]?.length??0;for(let p=0;p<u&&s+p<=a;p++){const e=this.visibleColumns[s+p];e&&h.push(e.field)}const g={rows:i,text:t,target:c,fields:h};this.emit("paste",g),this.#yt(g)}#yt(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??ut)(e,this.grid)}#bt(){const e=this.grid?.query("getSelection");return e?.[0]}#Ct(e){const t=this.#bt();let i,n;if(e?.columns)i=at(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],n=Math.min(e.from.col,e.to.col),r=Math.max(e.from.col,e.to.col);i=at(this.visibleColumns.slice(n,r+1))}else i=at(this.columns);if(e?.rowIndices)n=dt(this.rows,e.rowIndices);else if(t?.ranges.length){const e=t.ranges[t.ranges.length-1],i=Math.min(e.from.row,e.to.row),r=Math.max(e.from.row,e.to.row);n=[];for(let t=i;t<=r;t++){const e=this.rows[t];e&&n.push(e)}}else n=this.rows;return{columns:i,rows:n}}#xt(e,t,i){const n=i?.delimiter??this.config.delimiter??"\t",r=i?.newline??this.config.newline??"\n",o=i?.includeHeaders??this.config.includeHeaders??!1,s=i?.processCell??this.config.processCell,l=[];o&&l.push(e.map(e=>e.header||e.field).join(n));for(const a of t){const t=e.map(e=>{const t=a[e.field];return s?s(t,e.field,a):ct(t)});l.push(t.join(n))}return l.join(r)}#vt(e){const t=e.closest("[data-field-cache]");if(!t)return null;const i=t.dataset.fieldCache,n=t.dataset.row;if(!i||!n)return null;const r=parseInt(n,10);if(isNaN(r))return null;const o=this.columns.findIndex(e=>e.field===i);return-1===o?null:{row:r,col:o}}getSelectionAsText(e){const{columns:t,rows:i}=this.#Ct(e);return 0===t.length||0===i.length?"":this.#xt(t,i,e)}async copy(e){const{columns:t,rows:i}=this.#Ct(e);if(0===t.length||0===i.length)return"";const n=this.#xt(t,i,e);return await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){console.warn("[copyToClipboard] Clipboard API failed:",t);const i=document.createElement("textarea");i.value=e,i.style.position="fixed",i.style.opacity="0",i.style.pointerEvents="none",document.body.appendChild(i),i.select();const n=document.execCommand("copy");return document.body.removeChild(i),n}}(n),this.lastCopied={text:n,timestamp:Date.now()},this.emit("copy",{text:n,rowCount:i.length,columnCount:t.length}),n}async copyRows(e,t){return 0===e.length?"":this.copy({...t,rowIndices:e})}async paste(){const e=await async function(){try{return await navigator.clipboard.readText()}catch{return""}}();return e?ht(e,this.config):null}getLastCopied(){return this.lastCopied}},e.ColumnVirtualizationPlugin=class extends rt{name="columnVirtualization";get defaultConfig(){return{autoEnable:!0,threshold:30,overscan:3}}isVirtualized=!1;startCol=0;endCol=0;scrollLeft=0;totalWidth=0;columnWidths=[];columnOffsets=[];originalColumns=[];attach(e){super.attach(e);const t=this.columns;this.columnWidths=pt(t),this.columnOffsets=ft(t),this.totalWidth=wt(t),this.endCol=t.length-1}detach(){this.#Et(),this.columnWidths=[],this.columnOffsets=[],this.originalColumns=[],this.isVirtualized=!1,this.startCol=0,this.endCol=0,this.scrollLeft=0,this.totalWidth=0}#Et(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".header-row");t&&(t.style.paddingLeft="",t.style.minWidth="");e.querySelectorAll(".data-grid-row").forEach(e=>{e.style.paddingLeft=""});const i=e.querySelector(".rows-viewport .rows");i&&(i.style.width="");const n=e.querySelector(".rows-body");n&&(n.style.minWidth="")}processColumns(e){(0===this.originalColumns.length||e.length>=this.originalColumns.length)&&(this.originalColumns=e,this.columnWidths=pt(e),this.columnOffsets=ft(e),this.totalWidth=wt(e));const t=this.originalColumns,i=(n=t.length,r=this.config.threshold??30,!!(this.config.autoEnable??!0)&&n>r);var n,r;if(this.isVirtualized=i??!1,!i)return this.startCol=0,this.endCol=t.length-1,[...t];const o=this.grid.clientWidth||800,s=mt(this.scrollLeft,o,this.columnOffsets,this.columnWidths,this.config.overscan??3);return this.startCol=s.startCol,this.endCol=s.endCol,s.visibleColumns.map(e=>t[e])}afterRender(){if(!this.isVirtualized)return;const e=this.gridElement;if(!e)return;const t=this.columnOffsets[this.startCol]??0,i=e.querySelector(".header-row"),n=e.querySelectorAll(".data-grid-row");i&&(i.style.paddingLeft=`${t}px`,i.style.minWidth=`${this.totalWidth}px`),n.forEach(e=>{e.style.paddingLeft=`${t}px`});const r=e.querySelector(".rows-viewport .rows");r&&(r.style.width=`${this.totalWidth}px`);const o=e.querySelector(".rows-body");o&&(o.style.minWidth=`${this.totalWidth}px`)}onScroll(e){if(!this.isVirtualized)return;Math.abs(e.scrollLeft-this.scrollLeft)<1||(this.scrollLeft=e.scrollLeft,this.requestColumnsRender())}getIsVirtualized(){return this.isVirtualized}getVisibleColumnRange(){return{start:this.startCol,end:this.endCol}}scrollToColumn(e){const t=this.columnOffsets[e]??0;this.grid.scrollLeft=t}getColumnOffset(e){return this.columnOffsets[e]??0}getTotalWidth(){return this.totalWidth}},e.ContextMenuPlugin=Lt,e.DEFAULT_ANIMATION_CONFIG=i,e.DEFAULT_GRID_ICONS=r,e.DGEvents={CELL_CHANGE:"cell-change",CELL_COMMIT:"cell-commit",ROW_COMMIT:"row-commit",EDIT_OPEN:"edit-open",EDIT_CLOSE:"edit-close",CHANGED_ROWS_RESET:"changed-rows-reset",MOUNT_EXTERNAL_VIEW:"mount-external-view",MOUNT_EXTERNAL_EDITOR:"mount-external-editor",SORT_CHANGE:"sort-change",COLUMN_RESIZE:"column-resize",ACTIVATE_CELL:"activate-cell",CELL_ACTIVATE:"cell-activate",GROUP_TOGGLE:"group-toggle",COLUMN_STATE_CHANGE:"column-state-change"},e.DataGridElement=nt,e.EditingPlugin=class extends rt{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>!0===e},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'},{property:"nullable",level:"column",description:'the "nullable" column property (allows null values)'}],events:[{type:"cell-edit-committed",description:"Emitted when a cell edit is committed (for plugin-to-plugin coordination)"}],queries:[{type:"isEditing",description:"Returns whether any cell is currently being edited"}]};name="editing";styles="@layer tbw-plugins{tbw-grid{--tbw-editing-bg: var(--tbw-color-selection);--tbw-editing-row-bg: var(--tbw-editing-bg);--tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));--tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);--tbw-font-size-editor: inherit;--tbw-editing-row-outline-color: var(--tbw-color-accent);--tbw-editing-row-outline-width: 1px;--tbw-invalid-bg: light-dark(#fef2f2, #450a0a);--tbw-invalid-border-color: light-dark(#ef4444, #f87171)}tbw-grid:not(.tbw-grid-mode) .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:calc(var(--tbw-row-height) + 2px);align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}tbw-grid .data-grid-row>.cell[data-invalid=true]{background:var(--tbw-invalid-bg);outline:1px solid var(--tbw-invalid-border-color);outline-offset:-1px}}";get defaultConfig(){return{mode:"row",editOn:"click"}}get#Rt(){return"grid"===this.config.mode}#St=-1;#_t;#At;#kt=-1;#Tt=new Map;#Lt=new Set;#Mt=new Set;#It=new Map;#Pt=!1;#Ht=-1;#Dt=new Map;#zt=!1;#Ot=!1;#Ft=!1;#qt=new Map;#Nt=!1;#Gt=new Set;#Bt=new Set;attach(e){super.attach(e);const t=this.disconnectSignal,i=e;if(i._activeEditRows=-1,i._rowEditSnapshots=new Map,Object.defineProperty(e,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(e,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),e.resetChangedRows=e=>this.resetChangedRows(e),e.beginBulkEdit=(e,t)=>{t&&this.beginCellEdit(e,t)},document.addEventListener("keydown",e=>{if(!this.#Rt&&"Escape"===e.key&&-1!==this.#St){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}this.#Vt(this.#St,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",e=>{if(this.#Rt)return;if(-1===this.#St)return;const t=i.findRenderedRowElement?.(this.#St);if(!t)return;if((e.composedPath&&e.composedPath()||[]).includes(t))return;const n=e.target;if(!n||this.gridElement.contains(n)||!this.grid.containsFocus?.(n)){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}queueMicrotask(()=>{-1!==this.#St&&this.#Vt(this.#St,!1)})}},{signal:t}),this.config.focusTrap&&this.gridElement.addEventListener("focusout",e=>{if(this.#Rt)return;if(-1===this.#St)return;const t=e.relatedTarget;t&&this.grid.containsFocus?.(t)||t&&this.gridElement.contains(t)||queueMicrotask(()=>{-1!==this.#St&&this.#$t()})},{signal:t}),this.gridElement.addEventListener("cell-change",e=>{const t=e.detail;if("user"===t.source)return;const i=`${t.rowIndex}:${t.field}`,n=this.#It.get(i);n&&n(t.newValue)},{signal:t}),this.config.dirtyTracking){const e=e=>{const t=e.detail,i=t?.action;if(!i)return;const n=this.rows[i.rowIndex];if(!n)return;const r=this.grid.getRowId(n);if(!r)return;const o=Ht(this.#qt,r,n);this.emit("dirty-change",{rowId:r,row:n,original:Ft(this.#qt,r),type:o?"modified":"pristine"})};this.gridElement.addEventListener("undo",e,{signal:t}),this.gridElement.addEventListener("redo",e,{signal:t}),this.on("row-inserted",e=>{const t=this.grid.getRowId(e.row);null!=t&&this.markAsNew(String(t))})}this.#Rt&&(i._isGridEditMode=!0,this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",e=>{const t=e.target;if(t.matches(D)){if(this.#Ot)return t.blur(),void this.gridElement.focus();this.#zt=!0}},{signal:t}),this.gridElement.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.gridElement.contains(t)||this.grid.containsFocus?.(t))&&t.matches(D)||(this.#zt=!1)},{signal:t}),this.gridElement.addEventListener("keydown",e=>{if("Escape"===e.key&&this.#zt){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}const t=document.activeElement;t&&this.gridElement.contains(t)&&(t.blur(),this.gridElement.focus()),this.#zt=!1,this.#Ot=!0,e.preventDefault(),e.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",e=>{e.target.matches(D)&&(this.#Ot=!1)},{signal:t}))}detach(){this.gridElement._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#St=-1,this.#_t=void 0,this.#At=void 0,this.#kt=-1,this.#Tt.clear(),this.#Lt.clear(),this.#Bt.clear(),this.#Mt.clear(),this.#It.clear(),this.#qt.clear(),this.#Gt.clear(),this.#zt=!1,this.#Ot=!1,this.#Ft=!1,super.detach()}handleQuery(e){if("isEditing"===e.type)return this.#Rt||-1!==this.#St}onCellClick(e){if(this.#Rt)return!1;const t=this.grid,i=this.config.editOn??t.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;if("click"!==i&&"dblclick"!==i)return!1;const n="dblclick"===e.originalEvent.type;if("click"===i&&n)return!1;if("dblclick"===i&&!n)return!1;const{rowIndex:r}=e,o=t._columns?.some(e=>e.editable);return!!o&&(e.originalEvent.stopPropagation(),this.beginBulkEdit(r),!0)}onKeyDown(e){const t=this.grid;if("Escape"===e.key){if(this.#Rt&&this.#zt){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}const t=document.activeElement;return t&&this.gridElement.contains(t)&&t.blur(),this.#zt=!1,this.requestAfterRender(),!0}if(-1!==this.#St&&!this.#Rt){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}return this.#Vt(this.#St,!0),!0}}if(this.#Rt&&!this.#zt&&("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key))return!1;if(this.#Rt&&this.#zt&&("ArrowUp"===e.key||"ArrowDown"===e.key))return!0;if(("ArrowUp"===e.key||"ArrowDown"===e.key)&&-1!==this.#St&&!this.#Rt){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}const i=t._rows.length-1,n=this.#St;return this.#Vt(n,!1),"ArrowDown"===e.key?t._focusRow=Math.min(i,t._focusRow+1):t._focusRow=Math.max(0,t._focusRow-1),e.preventDefault(),K(t),this.requestAfterRender(),!0}if("Tab"===e.key&&(-1!==this.#St||this.#Rt)){if(e.preventDefault(),this.#Ft)return this.#Vt(this.#St,!1),!0;const t=!e.shiftKey;return this.#Wt(t),!0}if(" "===e.key||"Spacebar"===e.key){if(-1!==this.#St)return!1;const i=t._focusRow,n=t._focusCol;if(i>=0&&n>=0){const r=t._visibleColumns[n],o=t._rows[i];if(r?.editable&&"boolean"===r.type&&o){const t=r.field;if(Nt(t)){const n=!o[t];return this.#Kt(i,r,n,o),e.preventDefault(),this.requestRender(),!0}}}return!1}if(!("Enter"!==e.key||e.shiftKey||e.ctrlKey||e.altKey||e.metaKey)){if(this.#Rt&&!this.#zt)return this.#$t(),!0;if(-1!==this.#St){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}return!1}const i=this.config.editOn??t.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;const n=t._focusRow,r=t._focusCol;if(n>=0){const i=t._columns?.some(e=>e.editable);if(i){const i=t._visibleColumns[r],o=t._rows[n],s=i?.field??"",l=s&&o?o[s]:void 0,a=this.gridElement.querySelector(`[data-row="${n}"][data-col="${r}"]`),d=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:n,colIndex:r,field:s,value:l,row:o,cellEl:a,trigger:"keyboard",originalEvent:e}});this.gridElement.dispatchEvent(d);const c=new CustomEvent("activate-cell",{cancelable:!0,bubbles:!0,detail:{row:n,col:r}});return this.gridElement.dispatchEvent(c),d.defaultPrevented||c.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(n),!0)}}return!1}if("F2"===e.key){if(-1!==this.#St||this.#Rt)return!1;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return!1;const i=t._focusRow,n=t._focusCol;if(i>=0&&n>=0){const r=t._visibleColumns[n];if(r?.editable&&r.field)return e.preventDefault(),this.beginCellEdit(i,r.field),!0}return!1}return!1}processColumns(e){const t=this.grid,i=t.effectiveConfig?.typeDefaults,n=t.__frameworkAdapter;return i||n?.getTypeDefault?e.map(e=>{if(!e.type)return e;let t;if(i?.[e.type]?.editorParams&&(t=i[e.type].editorParams),!t&&n?.getTypeDefault){const i=n.getTypeDefault(e.type);i?.editorParams&&(t=i.editorParams)}return t?{...e,editorParams:{...t,...e.editorParams}}:e}):e}processRows(e){const t=this.grid;if(this.config.dirtyTracking&&t.getRowId){const i=this.#qt.size;!function(e,t,i){for(const n of t)try{const t=i(n);null==t||e.has(t)||e.set(t,structuredClone(n))}catch{}}(this.#qt,e,e=>{try{return t.getRowId?.(e)}catch{return}}),this.#qt.size>i&&(this.#Nt=!0)}if(-1===this.#St||this.#Rt)return e;const i=this.#_t,n=this.#At;if(!i||!n)return e;const r=[...e];let o=-1;for(let s=0;s<r.length;s++)try{if(t.getRowId?.(r[s])===i){o=s;break}}catch{}return-1===o?(setTimeout(()=>this.cancelActiveRowEdit(),0),r):(r[o]=n,this.#St!==o&&this.#Ut(this.#St,o),r)}afterRender(){const e=this.grid;if(-1!==this.#St&&this.#At&&!this.#Rt&&e._rows[this.#St]!==this.#At){const t=e._rows.indexOf(this.#At);if(-1===t)return void setTimeout(()=>this.cancelActiveRowEdit(),0);this.#Ut(this.#St,t)}if(this.#Pt&&(this.#Pt=!1,this.#jt(e)),-1!==this.#Ht){const t=this.#Ht;this.#Ht=-1,e.animateRow?.(t,"change")}if(this.#Nt&&(this.#Nt=!1,this.emit("baselines-captured",{count:this.#qt.size})),!this.#Rt&&0!==this.#Mt.size)for(const t of this.#Mt){const[i,n]=t.split(":"),r=parseInt(i,10),o=parseInt(n,10),s=e.findRenderedRowElement?.(r);if(!s)continue;const l=s.querySelector(`.cell[data-col="${o}"]`);if(!l||l.classList.contains("editing"))continue;const a=e._rows[r],d=e._visibleColumns[o];a&&d&&this.#Yt(a,r,d,o,l,!0)}}afterCellRender(e){if(!this.#Rt)return;const{row:t,rowIndex:i,column:n,colIndex:r,cellElement:o}=e;n.editable&&(o.classList.contains("editing")||this.#Yt(t,i,n,r,o,!0))}afterRowRender(e){if(!this.config.dirtyTracking)return;const t=this.gridElement,i=t.getRowId?.(e.row);if(!i)return;const n=this.#Gt.has(i),r=!n&&this.#Bt.has(i)&&Ht(this.#qt,i,e.row),o=e.rowElement;o.classList.toggle("tbw-row-dirty",r),o.classList.toggle("tbw-row-new",n);if(this.#qt.has(i)){const t=o.querySelectorAll(".cell[data-field]");for(let n=0;n<t.length;n++){const r=t[n],o=r.getAttribute("data-field");o&&r.classList.toggle("tbw-cell-dirty",Dt(this.#qt,i,e.row,o))}}else{const e=o.querySelectorAll(".tbw-cell-dirty");for(let t=0;t<e.length;t++)e[t].classList.remove("tbw-cell-dirty")}}onScrollRender(){this.afterRender()}get changedRows(){const e=[];for(const t of this.#Lt){const i=this.grid.getRow(t);i&&e.push(i)}return e}get changedRowIds(){return Array.from(this.#Lt)}get activeEditRow(){return this.#St}get activeEditCol(){return this.#kt}isRowEditing(e){return this.#St===e}isCellEditing(e,t){return this.#Mt.has(`${e}:${t}`)}isRowChanged(e){const t=this.grid,i=t._rows[e];if(!i)return!1;try{const e=t.getRowId?.(i);return!!e&&this.#Lt.has(e)}catch{return!1}}isRowChangedById(e){return this.#Lt.has(e)}isDirty(e){if(!this.config.dirtyTracking)return!1;if(this.#Gt.has(e))return!0;const t=this.grid.getRow(e);return!!t&&Ht(this.#qt,e,t)}isPristine(e){return!this.isDirty(e)}get dirty(){if(!this.config.dirtyTracking)return!1;if(this.#Gt.size>0)return!0;const e=this.grid;for(const[t,i]of this.#qt){const i=e._getRowEntry(t)?.row;if(i&&Ht(this.#qt,t,i))return!0}return!1}get pristine(){return!this.dirty}markAsPristine(e){if(!this.config.dirtyTracking)return;const t=this.grid.getRow(e);t&&(Ot(this.#qt,e,t),this.#Gt.delete(e),this.#Lt.delete(e),this.#Bt.delete(e),this.emit("dirty-change",{rowId:e,row:t,original:t,type:"pristine"}))}markAsNew(e){if(!this.config.dirtyTracking)return;this.#Gt.add(e),this.#Bt.add(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.#Lt.add(e),this.#Bt.add(e),this.emit("dirty-change",{rowId:e,row:t,original:Ft(this.#qt,e),type:"modified"}))}markAllPristine(){if(!this.config.dirtyTracking)return;const e=this.grid;for(const[t]of this.#qt){const i=e._getRowEntry(t)?.row;i&&Ot(this.#qt,t,i)}this.#Gt.clear(),this.#Lt.clear(),this.#Bt.clear()}getOriginalRow(e){if(this.config.dirtyTracking)return Ft(this.#qt,e)}hasBaseline(e){return!!this.config.dirtyTracking&&this.#qt.has(e)}getDirtyRows(){if(!this.config.dirtyTracking)return[];const e=[],t=this.grid;for(const[i,n]of this.#qt){const r=t._getRowEntry(i);r&&Ht(this.#qt,i,r.row)&&e.push({id:i,original:structuredClone(n),current:r.row})}for(const i of this.#Gt){const n=t._getRowEntry(i);n&&e.push({id:i,original:void 0,current:n.row})}return e}get dirtyRowIds(){if(!this.config.dirtyTracking)return[];const e=[],t=this.grid;for(const[i]of this.#qt){const n=t._getRowEntry(i);n&&Ht(this.#qt,i,n.row)&&e.push(i)}for(const i of this.#Gt)e.push(i);return e}revertRow(e){if(!this.config.dirtyTracking)return;const t=this.grid.getRow(e);if(!t)return;qt(this.#qt,e,t)&&(this.#Lt.delete(e),this.#Bt.delete(e),this.emit("dirty-change",{rowId:e,row:t,original:Ft(this.#qt,e),type:"reverted"}),this.requestRender())}revertAll(){if(!this.config.dirtyTracking)return;const e=this.grid;for(const[t]of this.#qt){const i=e._getRowEntry(t);i&&qt(this.#qt,t,i.row)}this.#Lt.clear(),this.#Bt.clear(),this.requestRender()}setInvalid(e,t,i=""){let n=this.#Dt.get(e);n||(n=new Map,this.#Dt.set(e,n)),n.set(t,i),this.#Xt(e,t,!0)}clearInvalid(e,t){const i=this.#Dt.get(e);i&&(i.delete(t),0===i.size&&this.#Dt.delete(e)),this.#Xt(e,t,!1)}clearRowInvalid(e){const t=this.#Dt.get(e);if(t){const i=Array.from(t.keys());this.#Dt.delete(e),i.forEach(t=>this.#Xt(e,t,!1))}}clearAllInvalid(){const e=Array.from(this.#Dt.entries());this.#Dt.clear(),e.forEach(([e,t])=>{t.forEach((t,i)=>this.#Xt(e,i,!1))})}isCellInvalid(e,t){return this.#Dt.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#Dt.get(e)?.get(t)}hasInvalidCells(e){const t=this.#Dt.get(e);return!!t&&t.size>0}getInvalidFields(e){return new Map(this.#Dt.get(e)??[])}#Xt(e,t,i){const n=this.grid,r=n._visibleColumns?.findIndex(e=>e.field===t);if(-1===r||void 0===r)return;const o=n._rows,s=o?.findIndex(t=>{try{return n.getRowId?.(t)===e}catch{return!1}});if(-1===s||void 0===s)return;const l=n.findRenderedRowElement?.(s),a=l?.querySelector(`.cell[data-col="${r}"]`);if(a)if(i){a.setAttribute("data-invalid","true");const i=this.#Dt.get(e)?.get(t);i&&a.setAttribute("title",i)}else a.removeAttribute("data-invalid"),a.removeAttribute("title")}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#Lt.clear(),this.#Bt.clear(),this.#Zt(),e||this.emit("changed-rows-reset",{rows:t,ids:i});const n=this.grid;n._rowPool?.forEach(e=>e.classList.remove("changed"))}beginCellEdit(e,t){const i=this.grid,n=i._visibleColumns.findIndex(e=>e.field===t);if(-1===n)return;const r=i._visibleColumns[n];if(!r?.editable)return;const o=i.findRenderedRowElement?.(e),s=o?.querySelector(`.cell[data-col="${n}"]`);s&&(this.#Ft=!0,this.#Qt(e,n,s))}beginBulkEdit(e){const t=this.grid;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return;const i=t._columns?.some(e=>e.editable);if(!i)return;const n=t.findRenderedRowElement?.(e);if(!n)return;this.#Ft=!1;const r=t._rows[e];this.#Jt(e,r),Array.from(n.children).forEach((i,n)=>{const o=t._visibleColumns[n];if(o?.editable){const t=i;t.classList.contains("editing")||this.#Yt(r,e,o,n,t,!0)}}),setTimeout(()=>{let e=n.querySelector(`.cell[data-col="${t._focusCol}"]`);if(e?.classList.contains("editing")||(e=n.querySelector(".cell.editing")),e?.classList.contains("editing")){const t=e.querySelector(D);try{t?.focus({preventScroll:!0})}catch{}}},0)}commitActiveRowEdit(){-1!==this.#St&&this.#Vt(this.#St,!1)}cancelActiveRowEdit(){-1!==this.#St&&this.#Vt(this.#St,!0)}#Ut(e,t){this.#St=t;const i=new Set,n=`${e}:`;for(const s of this.#Mt)s.startsWith(n)?i.add(`${t}:${s.substring(n.length)}`):i.add(s);this.#Mt.clear();for(const s of i)this.#Mt.add(s);const r=this.#Tt.get(e);void 0!==r&&(this.#Tt.delete(e),this.#Tt.set(t,r));const o=[];for(const[s,l]of this.#It)s.startsWith(n)&&(o.push([`${t}:${s.substring(n.length)}`,l]),this.#It.delete(s));for(const[s,l]of o)this.#It.set(s,l);this.#Zt()}#Qt(e,t,i){const n=this.grid,r=n._rows[e],o=n._visibleColumns[t];r&&o?.editable&&(i.classList.contains("editing")||(this.#St!==e&&this.#Jt(e,r),this.#kt=t,this.#Yt(r,e,o,t,i,!1)))}#$t(){const e=this.grid,t=e._focusRow,i=e._focusCol;if(t<0||i<0)return;const n=e.findRenderedRowElement?.(t),r=n?.querySelector(`.cell[data-col="${i}"]`);if(r?.classList.contains("editing")){const e=r.querySelector(D);e&&(this.#Ot=!1,e.focus(),this.#zt=!0,e instanceof HTMLInputElement&&("text"===e.type||"number"===e.type)&&e.select())}}#Wt(e){const t=this.grid,i=t._rows,n=this.#Rt?t._focusRow:this.#St,r=t._visibleColumns.map((e,t)=>e.editable?t:-1).filter(e=>e>=0);if(0===r.length)return;const o=r.indexOf(t._focusCol)+(e?1:-1);if(o>=0&&o<r.length){t._focusCol=r[o];const e=t.findRenderedRowElement?.(n),i=e?.querySelector(`.cell[data-col="${r[o]}"]`);if(i?.classList.contains("editing")){const e=i.querySelector(D);e?.focus({preventScroll:!0})}return void K(t,{forceHorizontalScroll:!0})}const s=n+(e?1:-1);s>=0&&s<i.length&&(this.#Rt?(t._focusRow=s,t._focusCol=e?r[0]:r[r.length-1],K(t,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const e=t.findRenderedRowElement?.(s),i=e?.querySelector(`.cell[data-col="${t._focusCol}"]`);if(i?.classList.contains("editing")){const e=i.querySelector(D);e?.focus({preventScroll:!0})}},0)):(this.#Vt(n,!1),t._focusRow=s,t._focusCol=e?r[0]:r[r.length-1],this.beginBulkEdit(s),K(t,{forceHorizontalScroll:!0})))}#Zt(){const e=this.grid;e._activeEditRows=this.#St,e._rowEditSnapshots=this.#Tt}#Jt(e,t){if(this.#St!==e){-1!==this.#St&&this.#Vt(this.#St,!1),this.#Tt.set(e,{...t}),this.#St=e,this.#At=t;const i=this.grid;try{this.#_t=i.getRowId?.(t)??void 0}catch{this.#_t=void 0}this.#Zt(),this.#Rt||this.emit("edit-open",{rowIndex:e,rowId:this.#_t??"",row:t})}}#Vt(e,t){if(this.#St!==e)return;const i=this.grid,n=this.#Tt.get(e),r=i.findRenderedRowElement?.(e);let o=this.#_t;const s=o?i._getRowEntry(o):void 0,l=s?.row??this.#At??i._rows[e];if(!o&&l)try{o=i.getRowId?.(l)}catch{}if(!t&&r&&l){r.querySelectorAll(".cell.editing").forEach(t=>{const n=Number(t.getAttribute("data-col"));if(isNaN(n))return;const r=i._visibleColumns[n];if(!r)return;if(t.hasAttribute("data-editor-managed"))return;const o=t.querySelector("input,textarea,select");if(o){const t=r.field,i=l[t],n=Gt(o,r,i);i!==n&&this.#Kt(e,r,n,l)}})}if(t||this.#Rt||!l||this.emit("before-edit-close",{rowIndex:e,rowId:o??"",row:l}),t&&n&&l)Object.keys(n).forEach(e=>{l[e]=n[e]}),o&&(this.#Lt.delete(o),this.#Bt.delete(o),this.clearRowInvalid(o));else if(!t&&l){const t=this.#ei(n,l),i=o?this.#Lt.has(o):t,r=this.emitCancelable("row-commit",{rowIndex:e,rowId:o??"",row:l,oldValue:n,newValue:l,changed:i,changedRows:this.changedRows,changedRowIds:this.changedRowIds});r&&n?(Object.keys(n).forEach(e=>{l[e]=n[e]}),o&&(this.#Lt.delete(o),this.#Bt.delete(o),this.clearRowInvalid(o))):r||(o&&this.config.dirtyTracking&&(Ht(this.#qt,o,l)?this.#Bt.add(o):this.#Bt.delete(o)),t&&this.isAnimationEnabled&&(this.#Ht=e))}this.#Tt.delete(e),this.#St=-1,this.#_t=void 0,this.#At=void 0,this.#kt=-1,this.#Ft=!1,this.#Zt();for(const a of this.#Mt)a.startsWith(`${e}:`)&&this.#Mt.delete(a);for(const a of this.#It.keys())a.startsWith(`${e}:`)&&this.#It.delete(a);this.#Pt=!0,r?(r.querySelectorAll(".cell.editing").forEach(e=>{e.classList.remove("editing"),function(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing")}(e.parentElement)}),i.refreshVirtualWindow(!0)):(this.#jt(i),this.#Pt=!1),!this.#Rt&&l&&this.emit("edit-close",{rowIndex:e,rowId:o??"",row:l,reverted:t})}#Kt(e,t,i,n){const r=t.field;if(!Nt(r))return;const o=n[r];if(o===i)return;const s=this.grid;let l;try{l=this.grid.getRowId(n)}catch{}const a=!l||!this.#Lt.has(l),d=l?e=>this.grid.updateRow(l,e,"cascade"):Bt;let c=!1;const h=l?e=>{c=!0,this.setInvalid(l,r,e??"")}:()=>{};if(this.emitCancelable("cell-commit",{row:n,rowId:l??"",field:r,oldValue:o,value:i,rowIndex:e,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:a,updateRow:d,setInvalid:h}))return;if(l&&!c&&this.isCellInvalid(l,r)&&this.clearInvalid(l,r),n[r]=i,l&&this.#Lt.add(l),this.#Zt(),this.config.dirtyTracking&&l){const e=Ht(this.#qt,l,n);this.emit("dirty-change",{rowId:l,row:n,original:Ft(this.#qt,l),type:e?"modified":"pristine"})}this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:r,oldValue:o,newValue:i});const u=s.findRenderedRowElement?.(e);u&&u.classList.add("changed")}#Yt(e,t,i,n,r,o){if(!i.editable)return;if(r.classList.contains("editing"))return;let s;try{s=this.grid.getRowId(e)}catch{}const l=s?e=>this.grid.updateRow(s,e,"cascade"):Bt,a=Nt(i.field)?e[i.field]:void 0;r.classList.add("editing"),this.#Mt.add(`${t}:${n}`);const d=r.parentElement;d&&function(e){const t=(e.__editingCellCount??0)+1;e.__editingCellCount=t,e.setAttribute("data-has-editing","")}(d);let c=!1;const h=n=>{if(c||!this.#Rt&&-1===this.#St)return;const r=this.grid,o=s?r._getRowEntry(s):void 0,l=o?.row??e,a=o?.index??t;this.#Kt(a,i,n,l)},u=()=>{if(c=!0,Nt(i.field)){const t=this.grid,n=s?t._getRowEntry(s):void 0;(n?.row??e)[i.field]=a}},g=document.createElement("div");g.className="tbw-editor-host",r.innerHTML="",r.appendChild(g),g.addEventListener("keydown",e=>{if("Enter"===e.key){if(this.#Rt){e.stopPropagation(),e.preventDefault();const t=g.querySelector("input,textarea,select");return void(t&&h(Gt(t,i,a)))}if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}e.stopPropagation(),e.preventDefault(),c=!0,this.#Vt(t,!1)}if("Escape"===e.key){if(this.#Rt)return e.stopPropagation(),void e.preventDefault();if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}e.stopPropagation(),e.preventDefault(),u(),this.#Vt(t,!0)}});const p=i,f=p.__editorTemplate,w=function(e,t){if(t.editor)return t.editor;if(t.__editorTemplate)return"template";if(!t.type)return;const i=e.effectiveConfig?.typeDefaults;if(i?.[t.type]?.editor)return i[t.type].editor;const n=e.__frameworkAdapter;if(n?.getTypeDefault){const e=n.getTypeDefault(t.type);if(e?.editor)return e.editor}}(this.grid,p)??Pt(i),m=a,b=`${t}:${i.field}`,v=[];this.#It.set(b,e=>{for(const t of v)t(e)});const y=e=>{v.push(e)};if("template"===w&&f)this.#ti(g,p,e,a,h,u,o,t),y(e=>{const t=g.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if("string"==typeof w){const e=document.createElement(w);e.value=m,e.addEventListener("change",()=>h(e.value)),y(t=>{e.value=t}),g.appendChild(e),o||queueMicrotask(()=>{const e=g.querySelector(D);e?.focus({preventScroll:!0})})}else if("function"==typeof w){const t=w({row:e,rowId:s??"",value:m,field:i.field,column:i,commit:h,cancel:u,updateRow:l,onValueChange:y});if("string"==typeof t)g.innerHTML=t,function(e,t,i,n){const r=e.querySelector("input,textarea,select");r&&(r.addEventListener("blur",()=>{i(Gt(r,t,n))}),r instanceof HTMLInputElement&&"checkbox"===r.type?r.addEventListener("change",()=>i(r.checked)):r instanceof HTMLSelectElement&&r.addEventListener("change",()=>i(Gt(r,t,n))))}(g,i,h,a),y(e=>{const t=g.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if(t instanceof Node){g.appendChild(t);t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?y(e=>{t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??"")}):r.setAttribute("data-editor-managed","")}else!t&&g.hasChildNodes()&&r.setAttribute("data-editor-managed","");o||queueMicrotask(()=>{const e=g.querySelector(D);e?.focus({preventScroll:!0})})}else if(w&&"object"==typeof w){const t=document.createElement("div");t.setAttribute("data-external-editor",""),t.setAttribute("data-field",i.field),g.appendChild(t),r.setAttribute("data-editor-managed","");const n={row:e,rowId:s??"",value:m,field:i.field,column:i,commit:h,cancel:u,updateRow:l,onValueChange:y};if(w.mount)try{w.mount({placeholder:t,context:n,spec:w})}catch(C){console.warn(`[tbw-grid] External editor mount error for column '${i.field}':`,C)}else this.grid.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:t,spec:w,context:n}}))}}#ti(e,t,i,n,r,o,s,l){const a=t.__editorTemplate;if(!a)return;const d=a.cloneNode(!0),c=t.__compiledEditor;c?d.innerHTML=c({row:i,value:n,field:t.field,column:t,commit:r,cancel:o}):d.querySelectorAll("*").forEach(e=>{1===e.childNodes.length&&e.firstChild?.nodeType===Node.TEXT_NODE&&(e.textContent=e.textContent?.replace(/{{\s*value\s*}}/g,null==n?"":String(n)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(e,t)=>{if(!Nt(t))return"";const n=i[t];return null==n?"":String(n)})||"")});const h=d.querySelector("input,textarea,select");if(h){h instanceof HTMLInputElement&&"checkbox"===h.type?h.checked=!!n:h.value=String(n??"");let e=!1;h.addEventListener("blur",()=>{e||r(Gt(h,t,n))}),h.addEventListener("keydown",i=>{const s=i;if("Enter"===s.key){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(s))return}s.stopPropagation(),s.preventDefault(),e=!0,r(Gt(h,t,n)),this.#Vt(l,!1)}if("Escape"===s.key){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(s))return}s.stopPropagation(),s.preventDefault(),o(),this.#Vt(l,!0)}}),h instanceof HTMLInputElement&&"checkbox"===h.type&&h.addEventListener("change",()=>r(h.checked)),s||setTimeout(()=>h.focus({preventScroll:!0}),0)}e.appendChild(d)}#ei(e,t){if(!e)return!1;const i=e,n=t,r=new Set([...Object.keys(i),...Object.keys(n)]);for(const o of r)if(i[o]!==n[o])return!0;return!1}#jt(e){queueMicrotask(()=>{try{const t=e._focusRow,i=e._focusCol,n=e.findRenderedRowElement?.(t);if(n){Array.from(e._bodyEl.querySelectorAll(".cell-focus")).forEach(e=>e.classList.remove("cell-focus"));const r=n.querySelector(`.cell[data-row="${t}"][data-col="${i}"]`);r&&(r.classList.add("cell-focus"),r.setAttribute("aria-selected","true"),r.hasAttribute("tabindex")||r.setAttribute("tabindex","-1"),r.focus({preventScroll:!0}))}}catch{}})}},e.ExportPlugin=class extends rt{name="export";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;performExport(e,t){const i=this.config,n={format:e,fileName:t?.fileName??i.fileName??"export",includeHeaders:t?.includeHeaders??i.includeHeaders,processCell:t?.processCell,processHeader:t?.processHeader,columns:t?.columns,rowIndices:t?.rowIndices},r=at(this.columns,t?.columns,i.onlyVisible);let o;if(t?.rowIndices)o=dt(this.rows,t.rowIndices);else if(i.onlySelected){const e=this.getSelectionState();o=e?.selected?.size?dt(this.rows,[...e.selected]):[...this.rows]}else o=[...this.rows];this.isExportingFlag=!0;let s=n.fileName;try{switch(e){case"csv":{const e=function(e,t,i,n={}){const r=n.delimiter??",",o=n.newline??"\n",s=[],l=n.bom?"\ufeff":"";if(!1!==i.includeHeaders){const e=t.map(e=>{const t=e.header||e.field;return Vt(i.processHeader?i.processHeader(t,e.field):t)});s.push(e.join(r))}for(const a of e){const e=t.map(e=>{let t=a[e.field];return i.processCell&&(t=i.processCell(t,e.field,a)),Vt(t)});s.push(e.join(r))}return l+s.join(o)}(o,r,n,{bom:!0});s=s.endsWith(".csv")?s:`${s}.csv`,function(e,t){$t(new Blob([e],{type:"text/csv;charset=utf-8;"}),t)}(e,s);break}case"excel":{const e=function(e,t,i){let n='<?xml version="1.0" encoding="UTF-8"?>\n<?mso-application progid="Excel.Sheet"?>\n<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"\n xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">\n<Worksheet ss:Name="Sheet1">\n<Table>';if(!1!==i.includeHeaders){n+="\n<Row>";for(const e of t){const t=e.header||e.field;n+=`<Cell><Data ss:Type="String">${Wt(i.processHeader?i.processHeader(t,e.field):t)}</Data></Cell>`}n+="</Row>"}for(const r of e){n+="\n<Row>";for(const e of t){let t=r[e.field];i.processCell&&(t=i.processCell(t,e.field,r));let o="String",s="";null==t?s="":"number"!=typeof t||isNaN(t)?t instanceof Date?(o="DateTime",s=t.toISOString()):s=Wt(String(t)):(o="Number",s=String(t)),n+=`<Cell><Data ss:Type="${o}">${s}</Data></Cell>`}n+="</Row>"}return n+="\n</Table>\n</Worksheet>\n</Workbook>",n}(o,r,n);s=s.endsWith(".xls")?s:`${s}.xls`,function(e,t){const i=t.endsWith(".xls")?t:`${t}.xls`;$t(new Blob([e],{type:"application/vnd.ms-excel;charset=utf-8;"}),i)}(e,s);break}case"json":{const e=o.map(e=>{const t={};for(const i of r){let r=e[i.field];n.processCell&&(r=n.processCell(r,i.field,e)),t[i.field]=r}return t}),t=JSON.stringify(e,null,2);s=s.endsWith(".json")?s:`${s}.json`;$t(new Blob([t],{type:"application/json"}),s);break}}this.lastExportInfo={format:e,timestamp:new Date},this.emit("export-complete",{format:e,fileName:s,rowCount:o.length,columnCount:r.length})}finally{this.isExportingFlag=!1}}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}exportCsv(e){this.performExport("csv",e)}exportExcel(e){this.performExport("excel",e)}exportJson(e){this.performExport("json",e)}isExporting(){return this.isExportingFlag}getLastExport(){return this.lastExportInfo}},e.FilteringPlugin=ei,e.FitModeEnum=t,e.GridCSSVars={COLOR_BG:"--tbw-color-bg",COLOR_FG:"--tbw-color-fg",COLOR_FG_MUTED:"--tbw-color-fg-muted",COLOR_BORDER:"--tbw-color-border",COLOR_ACCENT:"--tbw-color-accent",COLOR_HEADER_BG:"--tbw-color-header-bg",COLOR_HEADER_FG:"--tbw-color-header-fg",COLOR_SELECTION:"--tbw-color-selection",COLOR_ROW_HOVER:"--tbw-color-row-hover",COLOR_ROW_ALT:"--tbw-color-row-alt",ROW_HEIGHT:"--tbw-row-height",HEADER_HEIGHT:"--tbw-header-height",CELL_PADDING:"--tbw-cell-padding",FONT_FAMILY:"--tbw-font-family",FONT_SIZE:"--tbw-font-size",BORDER_RADIUS:"--tbw-border-radius",FOCUS_OUTLINE:"--tbw-focus-outline"},e.GridClasses=ot,e.GridDataAttrs=st,e.GridElement=nt,e.GridSelectors=lt,e.GroupingColumnsPlugin=class extends rt{static manifest={ownedProperties:[{property:"group",level:"column",description:'the "group" column property'},{property:"columnGroups",level:"config",description:'the "columnGroups" config property',isUsed:e=>Array.isArray(e)&&e.length>0}],queries:[{type:"getColumnGrouping",description:"Returns column group metadata for the visibility panel"}]};name="groupingColumns";styles="@layer tbw-plugins{.header-group-row{display:grid;grid-auto-flow:column;background:var(--tbw-grouping-columns-header-bg, var(--tbw-color-header-bg));border-bottom:1px solid var(--tbw-grouping-columns-border, var(--tbw-color-border))}.header-group-cell{display:flex;align-items:center;justify-content:center;padding:var(--tbw-button-padding-sm, .25rem .5rem);font-weight:600;font-size:var(--tbw-font-size-sm, .9em);text-transform:uppercase;letter-spacing:.5px;border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.header-group-cell:last-child{border-right:none}.header-row .cell.grouped{border-top:none}.header-row .cell.group-end{border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.header-row .cell.group-end:last-child{border-right:none}.rows .cell.group-end{border-right:2px solid var(--tbw-grouping-columns-separator, var(--tbw-color-border-strong, var(--tbw-color-border)))}.rows .cell.group-end:last-child{border-right:none}.header-group-row.no-borders{border-bottom:none}.header-group-row.no-borders .header-group-cell{border-right:none}.header-row.no-group-borders .cell.group-end{border-right:1px solid var(--tbw-color-border)}}";get defaultConfig(){return{showGroupBorders:!0,lockGroupOrder:!1}}groups=[];isActive=!1;#ii=new Set;attach(e){super.attach(e),e.addEventListener("column-move",this.#ni,{signal:this.disconnectSignal})}detach(){this.groups=[],this.isActive=!1,this.#ii.clear()}#ni=e=>{if(!this.isActive)return;const t=e,{field:i,columnOrder:n}=t.detail;if(this.config.lockGroupOrder)for(const r of this.groups)if(!r.id.startsWith("__implicit__")&&!this.#ri(r,n))return t.preventDefault(),void this.#oi(i);this.#si(n)};#si(e){this.#ii.clear();const t=this.#li(e);for(const i of this.groups){const n=new Set(i.columns.map(e=>e.field));for(let i=e.length-1;i>=0;i--)if(n.has(e[i])){const n=e[i];n!==t&&this.#ii.add(n);break}}}#li(e){if(0===this.groups.length)return null;for(let t=e.length-1;t>=0;t--){const i=e[t];for(const t of this.groups)if(t.columns.some(e=>e.field===i)){const i=new Set(t.columns.map(e=>e.field));for(let t=e.length-1;t>=0;t--)if(i.has(e[t]))return e[t]}}return null}#ri(e,t){const i=e.columns.map(e=>t.indexOf(e.field)).filter(e=>-1!==e).sort((e,t)=>e-t);return i.length<=1||i.length===i[i.length-1]-i[0]+1}#oi(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.#ai()}#ai(){let e;const t=this.grid?.gridConfig?.columnGroups;if(t&&Array.isArray(t)&&t.length>0)e=t.filter(e=>e.children.length>0).map(e=>({id:e.id,label:e.header,fields:[...e.children]}));else if(this.isActive&&this.groups.length>0){e=this.groups.filter(e=>!e.id.startsWith("__implicit__")).map(e=>({id:e.id,label:e.label??e.id,fields:e.columns.map(e=>e.field)}));const t=this.columns;for(const i of t)if(i.hidden&&i.group){const t="string"==typeof i.group?i.group:i.group.id,n="string"==typeof i.group?i.group:i.group.label??i.group.id,r=e.find(e=>e.id===t);r?r.fields.includes(i.field)||r.fields.push(i.field):e.push({id:t,label:n,fields:[i.field]})}}else{const t=this.columns,i=new Map;for(const e of t){if(!e.group)continue;const t="string"==typeof e.group?e.group:e.group.id,n="string"==typeof e.group?e.group:e.group.label??e.group.id,r=i.get(t);r?r.fields.includes(e.field)||r.fields.push(e.field):i.set(t,{id:t,label:n,fields:[e.field]})}e=Array.from(i.values())}const i=this.grid?.getColumnOrder();if(i&&i.length>0){const t=new Map(i.map((e,t)=>[e,t]));for(const i of e)i.fields.sort((e,i)=>(t.get(e)??1/0)-(t.get(i)??1/0))}return e}static detect(e,t){if(t?.columnGroups&&Array.isArray(t.columnGroups)&&t.columnGroups.length>0)return!0;const i=t?.columns;return!!Array.isArray(i)&&function(e){return e.some(e=>null!=e.group)}(i)}processColumns(e){const t=this.grid?.gridConfig?.columnGroups;let i;if(t&&Array.isArray(t)&&t.length>0){const n=new Map;for(const e of t)for(const t of e.children)n.set(t,{id:e.id,label:e.header});i=e.map(e=>{const t=n.get(e.field);return t&&!e.group?{...e,group:t}:e})}else i=[...e];const n=ti(i);if(0===n.length)return this.isActive=!1,this.groups=[],i;this.isActive=!0,this.groups=n,this.#ii.clear();for(const r of n){const e=r.columns[r.columns.length-1];e?.field&&this.#ii.add(e.field)}return i}afterRender(){if(!this.isActive){const e=this.gridElement?.querySelector(".header"),t=e?.querySelector(".header-group-row");return void(t&&t.remove())}const e=this.gridElement?.querySelector(".header");if(!e)return;const t=e.querySelector(".header-group-row");t&&t.remove();const i=this.visibleColumns,n=ti(i);if(0===n.length)return;this.#ii.clear();for(let s=0;s<n.length;s++){const e=n[s],t=e.columns[e.columns.length-1];t?.field&&s<n.length-1&&this.#ii.add(t.field)}const r=function(e,t){if(0===e.length)return null;const i=document.createElement("div");i.className="header-group-row",i.setAttribute("role","row");for(const n of e){const e=n.columns[0],r=e?t.findIndex(t=>t.field===e.field):-1;if(-1===r)continue;const o=String(n.id).startsWith("__implicit__"),s=o?"":n.label||n.id,l=document.createElement("div");l.className="cell header-group-cell",o&&l.classList.add("implicit-group"),l.setAttribute("data-group",String(n.id)),l.style.gridColumn=`${r+1} / span ${n.columns.length}`,l.textContent=s,i.appendChild(l)}return i}(n,i);if(r){r.classList.toggle("no-borders",!this.config.showGroupBorders);const t=e.querySelector(".header-row");t?e.insertBefore(r,t):e.appendChild(r)}const o=e.querySelector(".header-row");o&&(o.classList.toggle("no-group-borders",!this.config.showGroupBorders),function(e,t){if(!t.length||!e)return;const i=new Map;for(const r of t)for(const e of r.columns)e.field&&i.set(e.field,r.id);const n=Array.from(e.querySelectorAll(".cell[data-field]"));n.forEach(e=>{const t=e.getAttribute("data-field")||"",n=i.get(t);n&&(e.classList.add("grouped"),e.getAttribute("data-group")||e.setAttribute("data-group",n))});for(const r of t){const e=r.columns[r.columns.length-1],t=n.find(t=>t.getAttribute("data-field")===e.field);t&&t.classList.add("group-end")}}(o,n))}afterCellRender(e){this.isActive&&this.config.showGroupBorders&&e.cellElement.classList.toggle("group-end",this.#ii.has(e.column.field))}isGroupingActive(){return this.isActive}getGroups(){return this.groups}getGroupColumns(e){const t=this.groups.find(t=>t.id===e);return t?t.columns:[]}refresh(){this.requestRender()}},e.GroupingRowsPlugin=class extends rt{static manifest={events:[{type:"grouping-state-change",description:"Emitted when groups are expanded/collapsed. Subscribers can react to row visibility changes."}],queries:[{type:"canMoveRow",description:"Returns false for group header rows (cannot be reordered)"}],configRules:[{id:"groupingRows/accordion-defaultExpanded",severity:"warn",message:'"accordion: true" and "defaultExpanded" (non-false) are used together.\n → In accordion mode, only one group can be open at a time.\n → Using defaultExpanded with multiple groups will collapse to one on first toggle.\n → Consider using "defaultExpanded: false" or a single group key/index with accordion mode.',check:e=>!0===e.accordion&&!1!==e.defaultExpanded&&void 0!==e.defaultExpanded&&!("number"==typeof e.defaultExpanded)&&!("string"==typeof e.defaultExpanded)&&(!0===e.defaultExpanded||Array.isArray(e.defaultExpanded)&&e.defaultExpanded.length>1)}]};name="groupingRows";styles="@layer tbw-plugins{.group-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-grouping-rows-bg, var(--tbw-color-panel-bg));font-weight:500;border-bottom:var(--tbw-row-divider);min-height:var(--tbw-row-height)}.group-row .cell{display:flex;align-items:center;padding:var(--tbw-cell-padding, .125rem .5rem)}.group-row:hover{background:var(--tbw-grouping-rows-bg-hover, var(--tbw-color-row-hover))}.group-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-toggle-size, 1.25rem);height:var(--tbw-toggle-size, 1.25rem);margin-right:.25rem;background:none;border:0;font:inherit}.group-toggle:hover{background:var(--tbw-grouping-rows-toggle-hover, var(--tbw-color-row-hover));border-radius:var(--tbw-border-radius, .125rem)}.group-label{display:inline-flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.group-count{color:var(--tbw-grouping-rows-count-color, var(--tbw-color-fg-muted));font-size:var(--tbw-font-size-xs, .85em);font-weight:400}.group-aggregates{display:inline-flex;align-items:center;gap:var(--tbw-spacing-lg, 1rem);margin-left:var(--tbw-spacing-lg, 1rem);font-weight:400;font-size:var(--tbw-font-size-sm, .875em);color:var(--tbw-grouping-rows-aggregate-color, var(--tbw-color-fg-muted))}.group-aggregate{white-space:nowrap}.group-row{padding-left:calc(var(--tbw-group-depth, 0) * var(--tbw-group-indent-width, 1.25em))}.data-grid-row.tbw-group-slide-in{animation:tbw-group-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.data-grid-row.tbw-group-fade-in{animation:tbw-group-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-fade-in{0%{opacity:0}to{opacity:1}}}";get defaultConfig(){return{defaultExpanded:!1,showRowCount:!0,indentWidth:20,aggregators:{},animation:"slide",accordion:!1}}expandedKeys=new Set;flattenedRows=[];isActive=!1;previousVisibleKeys=new Set;keysToAnimate=new Set;hasAppliedDefaultExpanded=!1;get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detach(){this.expandedKeys.clear(),this.flattenedRows=[],this.isActive=!1,this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.hasAppliedDefaultExpanded=!1}getRowHeight(e,t){if(null!=this.config.groupRowHeight)return!0===e.__isGroupRow?this.config.groupRowHeight:void 0}handleQuery(e){if("canMoveRow"===e.type){const t=e.context;if(!0===t?.__isGroupRow)return!1}}static detect(e,t){return"function"==typeof t?.groupOn||"boolean"==typeof t?.enableRowGrouping}processRows(e){const t=this.config;if("function"!=typeof t.groupOn)return this.isActive=!1,this.flattenedRows=[],[...e];const i=ai({rows:[...e],config:t,expanded:new Set});if(0===i.length)return this.isActive=!1,this.flattenedRows=[],[...e];let n;if(!this.hasAppliedDefaultExpanded&&0===this.expandedKeys.size&&!1!==t.defaultExpanded){const e=function(e){return e.filter(e=>"group"===e.kind).map(e=>e.key)}(i);n=function(e,t){if(!0===e)return new Set(t);if(!1===e||null==e)return new Set;if("number"==typeof e){const i=t[e];return i?new Set([i]):new Set}return"string"==typeof e?new Set([e]):Array.isArray(e)?new Set(e):new Set}(t.defaultExpanded??!1,e),n.size>0&&(this.expandedKeys=new Set(n),this.hasAppliedDefaultExpanded=!0)}const r=ai({rows:[...e],config:t,expanded:this.expandedKeys,initialExpanded:n});this.isActive=!0,this.flattenedRows=r,this.keysToAnimate.clear();const o=new Set;return r.forEach((e,t)=>{if("data"===e.kind){const e=`data-${t}`;o.add(e),this.previousVisibleKeys.has(e)||this.keysToAnimate.add(e)}}),this.previousVisibleKeys=o,r.map(e=>{return"group"===e.kind?{__isGroupRow:!0,__groupKey:e.key,__groupValue:e.value,__groupDepth:e.depth,__groupRows:e.rows,__groupExpanded:e.expanded,__groupRowCount:(t=e,"group"!==t.kind?0:t.rows.length),__rowCacheKey:`group:${e.key}`}:e.row;var t})}onCellClick(e){const t=e.row;if(t?.__isGroupRow){const i=e.originalEvent.target;if(i?.closest(".group-toggle"))return this.toggle(t.__groupKey),!0}}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusRow,i=this.rows[t];return i?.__isGroupRow?(e.preventDefault(),this.toggle(i.__groupKey),this.requestRenderWithFocus(),!0):void 0}renderRow(e,t,i){if(!e?.__isGroupRow)return!1;const n=this.config;if(n.groupRowRenderer){const i=()=>{this.toggle(e.__groupKey)},r=n.groupRowRenderer({key:e.__groupKey,value:e.__groupValue,depth:e.__groupDepth,rows:e.__groupRows,expanded:e.__groupExpanded,toggleExpand:i});if(r)return t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),"string"==typeof r?t.innerHTML=r:(t.innerHTML="",t.appendChild(r)),!0}const r=()=>{this.toggle(e.__groupKey)};t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),t.setAttribute("role","row"),t.setAttribute("aria-expanded",String(e.__groupExpanded)),t.style.setProperty("--tbw-group-depth",String(e.__groupDepth||0)),void 0!==n.indentWidth&&t.style.setProperty("--tbw-group-indent-width",`${n.indentWidth}px`),t.style.height="",t.innerHTML="";return!1!==n.fullWidth?this.renderFullWidthGroupRow(e,t,r):this.renderPerColumnGroupRow(e,t,r),!0}afterRender(){const e=this.animationStyle;if(!1===e||0===this.keysToAnimate.size)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const i="fade"===e?"tbw-group-fade-in":"tbw-group-slide-in";for(const n of t.querySelectorAll(".data-grid-row:not(.group-row)")){const e=n.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,r=this.flattenedRows[t],o="data"===r?.kind?`data-${t}`:void 0;o&&this.keysToAnimate.has(o)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}createToggleButton(e,t){const i=document.createElement("button");return i.type="button",i.className="group-toggle"+(e?" expanded":""),i.setAttribute("aria-label",e?"Collapse group":"Expand group"),this.setIcon(i,this.resolveIcon(e?"collapse":"expand")),i.addEventListener("click",e=>{e.stopPropagation(),t()}),i}getGroupLabelText(e,t,i){const n=this.config;return n.formatLabel?n.formatLabel(e,t,i):String(e)}renderFullWidthGroupRow(e,t,i){const n=this.config,r=n.aggregators??{},o=e.__groupRows??[],s=document.createElement("div");s.className="cell group-full",s.style.gridColumn="1 / -1",s.setAttribute("role","gridcell"),s.setAttribute("data-col","0"),s.appendChild(this.createToggleButton(e.__groupExpanded,i));const l=document.createElement("span");if(l.className="group-label",l.textContent=this.getGroupLabelText(e.__groupValue,e.__groupDepth||0,e.__groupKey),s.appendChild(l),!1!==n.showRowCount){const t=document.createElement("span");t.className="group-count",t.textContent=`(${e.__groupRowCount??e.__groupRows?.length??0})`,s.appendChild(t)}const a=Object.entries(r);if(a.length>0){const e=document.createElement("span");e.className="group-aggregates";for(const[t,i]of a){const n=this.columns.find(e=>e.field===t),r=li(i,o,t,n);if(null!=r){const i=document.createElement("span");i.className="group-aggregate",i.setAttribute("data-field",t);const o=n?.header??t;i.textContent=`${o}: ${r}`,e.appendChild(i)}}e.children.length>0&&s.appendChild(e)}t.appendChild(s)}renderPerColumnGroupRow(e,t,i){const n=this.config,r=n.aggregators??{},o=this.columns,s=e.__groupRows??[],l=this.gridElement?.querySelector(".body"),a=l?.style.gridTemplateColumns||"";a&&(t.style.display="grid",t.style.gridTemplateColumns=a);let d=!1;o.forEach((o,l)=>{const a=document.createElement("div");if(a.className="cell group-cell",a.setAttribute("data-col",String(l)),a.setAttribute("role","gridcell"),Qt(o))return a.setAttribute("data-field",o.field),void t.appendChild(a);if(d){const e=r[o.field];if(e){const t=li(e,s,o.field,o);a.textContent=null!=t?String(t):""}else a.textContent=""}else{d=!0,a.appendChild(this.createToggleButton(e.__groupExpanded,i));const t=document.createElement("span"),l=r[o.field];if(l){const i=li(l,s,o.field,o);t.textContent=String(null!=i?i:e.__groupValue)}else t.textContent=this.getGroupLabelText(e.__groupValue,e.__groupDepth||0,e.__groupKey);if(a.appendChild(t),!1!==n.showRowCount){const e=document.createElement("span");e.className="group-count",e.textContent=` (${s.length})`,a.appendChild(e)}}t.appendChild(a)})}expandAll(){this.expandedKeys=function(e){const t=new Set;for(const i of e)"group"===i.kind&&t.add(i.key);return t}(this.flattenedRows),this.emitPluginEvent("grouping-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("grouping-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}toggle(e){const t=!this.expandedKeys.has(e),i=this.config,n=this.flattenedRows.find(t=>"group"===t.kind&&t.key===e);if(i.accordion&&t&&n){const t=new Set;for(const i of this.expandedKeys)if(e.startsWith(i+"||")||i.startsWith(e+"||"))e.startsWith(i+"||")&&t.add(i);else{const e=this.flattenedRows.find(e=>"group"===e.kind&&e.key===i);e&&e.depth!==n.depth&&t.add(i)}t.add(e),this.expandedKeys=t}else this.expandedKeys=function(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),i}(this.expandedKeys,e);this.emit("group-toggle",{key:e,expanded:this.expandedKeys.has(e),value:n?.value,depth:n?.depth??0}),this.emitPluginEvent("grouping-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}expand(e){this.expandedKeys.has(e)||(this.expandedKeys=new Set([...this.expandedKeys,e]),this.requestRender())}collapse(e){if(this.expandedKeys.has(e)){const t=new Set(this.expandedKeys);t.delete(e),this.expandedKeys=t,this.requestRender()}}getGroupState(){const e=this.flattenedRows.filter(e=>"group"===e.kind);return{isActive:this.isActive,expandedCount:this.expandedKeys.size,totalGroups:e.length,expandedKeys:[...this.expandedKeys]}}getRowCount(){return this.flattenedRows.length}refreshGroups(){this.requestRender()}getExpandedGroups(){return[...this.expandedKeys]}getFlattenedRows(){return this.flattenedRows}isGroupingActive(){return this.isActive}setGroupOn(e){this.config.groupOn=e,this.requestRender()}},e.MasterDetailPlugin=hi,e.MultiSortPlugin=class extends rt{name="multiSort";styles='@layer tbw-plugins{.header-cell[data-sort=asc]:after{content:"↑";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.header-cell[data-sort=desc]:after{content:"↓";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-indicator{margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-index{font-size:var(--tbw-font-size-2xs, .7em);background:var(--tbw-multi-sort-badge-bg, var(--tbw-color-panel-bg));color:var(--tbw-multi-sort-badge-color, var(--tbw-color-fg));border-radius:50%;width:var(--tbw-multi-sort-badge-size, 1em);height:var(--tbw-multi-sort-badge-size, 1em);display:inline-flex;align-items:center;justify-content:center;margin-left:var(--tbw-spacing-xs, .125em);font-weight:600}}';get defaultConfig(){return{maxSortColumns:3,showSortIndex:!0}}sortModel=[];cachedSortResult=null;clearCoreSortState(){const e=this.gridElement;e&&(e._sortState=null)}detach(){this.sortModel=[],this.cachedSortResult=null}processRows(e){if(0===this.sortModel.length)return this.cachedSortResult=null,[...e];const t=this.gridElement;if(t&&!t._isGridEditMode&&"number"==typeof t._activeEditRows&&-1!==t._activeEditRows&&this.cachedSortResult&&this.cachedSortResult.length===e.length)return[...this.cachedSortResult];const i=function(e,t,i){return t.length?[...e].sort((e,n)=>{for(const r of t){const t=i.find(e=>e.field===r.field),o=(t?.sortComparator??ui)(e[r.field],n[r.field],e,n);if(0!==o)return"asc"===r.direction?o:-o}return 0}):[...e]}([...e],this.sortModel,[...this.columns]);return this.cachedSortResult=i,i}onHeaderClick(e){const t=this.columns.find(t=>t.field===e.field);if(!t?.sortable)return!1;const i=e.originalEvent.shiftKey,n=this.config.maxSortColumns??3;return this.sortModel=function(e,t,i,n){const r=e.find(e=>e.field===t);return i?r?"asc"===r.direction?e.map(e=>e.field===t?{...e,direction:"desc"}:e):e.filter(e=>e.field!==t):e.length<n?[...e,{field:t,direction:"asc"}]:e:"asc"===r?.direction?[{field:t,direction:"desc"}]:"desc"===r?.direction?[]:[{field:t,direction:"asc"}]}(this.sortModel,e.field,i,n),this.clearCoreSortState(),this.emit("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),this.grid?.requestStateChange?.(),!0}afterRender(){const e=this.gridElement;if(!e)return;const t=!1!==this.config.showSortIndex;e.querySelectorAll(".header-row .cell[data-field]").forEach(e=>{const i=e.getAttribute("data-field");if(!i)return;const n=gi(this.sortModel,i),r=pi(this.sortModel,i),o=e.querySelector(".sort-index");if(o?.remove(),r){const i=e.querySelector('[part~="sort-indicator"], .sort-indicator');i?.remove(),e.setAttribute("data-sort",r);const o=document.createElement("span");o.className="sort-indicator",this.setIcon(o,this.resolveIcon("asc"===r?"sortAsc":"sortDesc"));const s=e.querySelector(".tbw-filter-btn"),l=e.querySelector(".resize-handle"),a=s??l;if(a?e.insertBefore(o,a):e.appendChild(o),t&&this.sortModel.length>1&&void 0!==n){const t=document.createElement("span");t.className="sort-index",t.textContent=String(n),o.nextSibling?e.insertBefore(t,o.nextSibling):e.appendChild(t)}}else{e.removeAttribute("data-sort");const t=e.querySelector('[part~="sort-indicator"], .sort-indicator');t?.remove()}})}getSortModel(){return[...this.sortModel]}setSortModel(e){this.sortModel=[...e],this.clearCoreSortState(),this.emit("sort-change",{sortModel:[...e]}),this.requestRender(),this.grid?.requestStateChange?.()}clearSort(){this.sortModel=[],this.clearCoreSortState(),this.emit("sort-change",{sortModel:[]}),this.requestRender(),this.grid?.requestStateChange?.()}getSortIndex(e){return gi(this.sortModel,e)}getSortDirection(e){return pi(this.sortModel,e)}getColumnState(e){const t=this.sortModel.findIndex(t=>t.field===e);if(-1===t)return;return{sort:{direction:this.sortModel[t].direction,priority:t}}}applyColumnState(e,t){if(!t.sort)return void(this.sortModel=this.sortModel.filter(t=>t.field!==e));const i=this.sortModel.findIndex(t=>t.field===e),n={field:e,direction:t.sort.direction};-1!==i?this.sortModel[i]=n:this.sortModel.splice(t.sort.priority,0,n),this.clearCoreSortState()}},e.PLUGIN_QUERIES={CAN_MOVE_COLUMN:"canMoveColumn",GET_CONTEXT_MENU_ITEMS:"getContextMenuItems"},e.PinnedColumnsPlugin=class extends rt{static manifest={ownedProperties:[{property:"pinned",level:"column",description:'the "pinned" column property',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e},{property:"sticky",level:"column",description:'the "sticky" column property (deprecated, use "pinned")',isUsed:e=>"left"===e||"right"===e||"start"===e||"end"===e}],incompatibleWith:[{name:"groupingColumns",reason:"Pinning reorders columns to the grid edges, but moving a column out of its column group is not supported. The group header layout cannot accommodate members at different positions."}],queries:[{type:xi,description:"Prevents pinned (sticky) columns from being moved/reordered"},{type:"getStickyOffsets",description:"Returns the sticky offsets for left/right pinned columns"},{type:"getContextMenuItems",description:"Contributes pin/unpin items to the header context menu"}]};name="pinnedColumns";get defaultConfig(){return{}}isApplied=!1;leftOffsets=new Map;rightOffsets=new Map;#di=[];detach(){this.leftOffsets.clear(),this.rightOffsets.clear(),this.isApplied=!1,this.#di=[]}static detect(e,t){const i=t?.columns;return!!Array.isArray(i)&&vi(i)}processColumns(e){const t=[...e];if(this.isApplied=vi(t),!this.isApplied)return t;const i=this.gridElement;return function(e,t="ltr"){const i=[],n=[],r=[];for(const o of e){const e=fi(o);e?"left"===wi(e,t)?i.push(o):r.push(o):n.push(o)}return[...i,...n,...r]}(t,i?M(i):"ltr")}afterRender(){if(!this.isApplied)return;const e=this.grid,t=[...this.columns];if(!vi(t))return Ci(e),void(this.isApplied=!1);queueMicrotask(()=>{yi(e,t)})}handleQuery(e){switch(e.type){case xi:return null==fi(e.context)&&void 0;case"getStickyOffsets":return{left:Object.fromEntries(this.leftOffsets),right:Object.fromEntries(this.rightOffsets)};case"getContextMenuItems":{const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field)return;if(i.meta?.lockPinning)return;const n=this.grid?.getPluginByName("groupingColumns");if(n?.isGroupingActive())return;const r=[];return null!=fi(i)?r.push({id:"pinned/unpin",label:"Unpin Column",icon:"📌",order:40,action:()=>this.setPinPosition(i.field,void 0)}):(r.push({id:"pinned/pin-left",label:"Pin Left",icon:"⬅",order:40,action:()=>this.setPinPosition(i.field,"left")}),r.push({id:"pinned/pin-right",label:"Pin Right",icon:"➡",order:41,action:()=>this.setPinPosition(i.field,"right")})),r}default:return}}setPinPosition(e,t){const i=this.columns;if(!i?.length)return;const n=i.findIndex(t=>t.field===e);if(-1===n)return;const r=this.grid;if(t){0===this.#di.length&&(this.#di=i.map(e=>e.field));const n=i.map(i=>{if(i.field!==e)return i;const n={...i};return n.pinned=t,delete n.sticky,n});r.columns=n}else{const t={...i[n]};delete t.pinned,delete t.sticky;const o=[...i];o.splice(n,1);const s=this.#di.indexOf(e);if(s>=0){let e=o.length;for(let t=0;t<o.length;t++){if(fi(o[t]))continue;if(this.#di.indexOf(o[t].field)>s){e=t;break}}o.splice(e,0,t)}else o.splice(Math.min(n,o.length),0,t);o.some(e=>null!=fi(e))||(this.#di=[]),r.columns=o}}refreshStickyOffsets(){const e=[...this.columns];yi(this.grid,e)}getLeftPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>mi(e,t))}([...this.columns],M(this.grid))}getRightPinnedColumns(){return function(e,t="ltr"){return e.filter(e=>bi(e,t))}([...this.columns],M(this.grid))}clearStickyPositions(){Ci(this.grid)}getHorizontalScrollOffsets(e,t){if(!this.isApplied)return;let i=0,n=0;if(e){const t=e.querySelectorAll(".sticky-left"),r=e.querySelectorAll(".sticky-right");t.forEach(e=>{i+=e.offsetWidth}),r.forEach(e=>{n+=e.offsetWidth})}else{this.grid.querySelectorAll(".header-row .cell").forEach(e=>{e.classList.contains("sticky-left")?i+=e.offsetWidth:e.classList.contains("sticky-right")&&(n+=e.offsetWidth)})}const r=t?.classList.contains("sticky-left")||t?.classList.contains("sticky-right");return{left:i,right:n,skipScroll:r}}},e.PinnedRowsPlugin=class extends rt{name="pinnedRows";styles="@layer tbw-plugins{.tbw-footer{flex-shrink:0;z-index:var(--tbw-z-layer-pinned-rows, 20);background:var(--tbw-color-panel-bg)}.tbw-pinned-rows{display:flex;align-items:center;justify-content:space-between;padding:var(--tbw-button-padding, var(--tbw-spacing-md, .5rem) var(--tbw-spacing-lg, .75rem));background:var(--tbw-pinned-rows-bg, var(--tbw-color-panel-bg));border-top:1px solid var(--tbw-pinned-rows-border, var(--tbw-color-border));font-size:var(--tbw-font-size-xs, .75rem);color:var(--tbw-pinned-rows-color, var(--tbw-color-fg-muted));min-height:32px;box-sizing:border-box;min-width:fit-content}.tbw-pinned-rows-left,.tbw-pinned-rows-center,.tbw-pinned-rows-right{display:flex;align-items:center;gap:var(--tbw-spacing-xl, 1rem)}.tbw-pinned-rows-left{justify-content:flex-start}.tbw-pinned-rows-center{justify-content:center;flex:1}.tbw-pinned-rows-right{justify-content:flex-end}.tbw-status-panel{white-space:nowrap}.tbw-aggregation-rows{min-width:fit-content;background:var(--tbw-aggregation-bg, var(--tbw-color-header-bg))}.tbw-aggregation-rows-top{border-bottom:1px solid var(--tbw-aggregation-border, var(--tbw-color-border))}.tbw-aggregation-rows-bottom{border-top:1px solid var(--tbw-aggregation-border, var(--tbw-color-border))}.tbw-aggregation-row{display:grid;grid-template-columns:var(--tbw-column-template);font-size:var(--tbw-aggregation-font-size, .8em);font-weight:var(--tbw-aggregation-font-weight, 600)}.tbw-aggregation-cell{padding:var(--tbw-cell-padding, .125rem .5rem);min-height:var(--tbw-row-height, 1.75rem);display:block;align-items:center;align-content:center;border-right:1px solid var(--tbw-color-border-cell);overflow:hidden;text-overflow:ellipsis;white-space:var(--tbw-cell-white-space, nowrap)}.tbw-aggregation-cell:last-child{border-right:0}.tbw-aggregation-cell-full{grid-column:1 / -1;border-right:0;display:flex;align-items:center;gap:var(--tbw-spacing-lg, .75rem)}.tbw-aggregation-label{white-space:nowrap}.tbw-aggregation-aggregates{display:flex;align-items:center;gap:var(--tbw-spacing-lg, .75rem);font-weight:400;opacity:.85}.tbw-aggregation-aggregate{white-space:nowrap}}";get defaultConfig(){return{position:"bottom",showRowCount:!0,showSelectedCount:!0,showFilteredCount:!0}}infoBarElement=null;topAggregationContainer=null;bottomAggregationContainer=null;footerWrapper=null;detach(){this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null),this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null)}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-scroll-area")??e.querySelector(".tbw-grid-content")??e.children[0];if(!t)return;this.footerWrapper&&!t.contains(this.footerWrapper)&&(this.footerWrapper=null,this.bottomAggregationContainer=null,this.infoBarElement=null),this.topAggregationContainer&&!t.contains(this.topAggregationContainer)&&(this.topAggregationContainer=null),this.infoBarElement&&!t.contains(this.infoBarElement)&&(this.infoBarElement=null);const i=this.getSelectionState(),n=this.getFilterState(),r=Li(this.sourceRows,this.columns,this.grid,i,n),o=this.config.aggregationRows||[],s=o.filter(e=>"top"===e.position),l=o.filter(e=>"top"!==e.position);if(s.length>0){if(!this.topAggregationContainer){this.topAggregationContainer=Ri("top");const i=e.querySelector(".header");i&&i.nextSibling?t.insertBefore(this.topAggregationContainer,i.nextSibling):t.appendChild(this.topAggregationContainer)}Si(this.topAggregationContainer,s,this.visibleColumns,this.sourceRows,this.config.fullWidth)}else this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null);const a=!1!==this.config.showRowCount||this.config.showSelectedCount&&r.selectedRows>0||this.config.showFilteredCount&&r.filteredRows!==r.totalRows||this.config.customPanels&&this.config.customPanels.length>0,d=a&&"top"!==this.config.position,c=l.length>0||d;if(a&&"top"===this.config.position)if(this.infoBarElement){const e=Ei(this.config,r);this.infoBarElement.replaceWith(e),this.infoBarElement=e}else this.infoBarElement=Ei(this.config,r),t.insertBefore(this.infoBarElement,t.firstChild);else"top"===this.config.position&&this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null);c?(this.footerWrapper||(this.footerWrapper=document.createElement("div"),this.footerWrapper.className="tbw-footer",t.appendChild(this.footerWrapper)),this.footerWrapper.innerHTML="",l.length>0&&(this.bottomAggregationContainer||(this.bottomAggregationContainer=Ri("bottom")),this.footerWrapper.appendChild(this.bottomAggregationContainer),Si(this.bottomAggregationContainer,l,this.visibleColumns,this.sourceRows,this.config.fullWidth)),d&&(this.infoBarElement=Ei(this.config,r),this.footerWrapper.appendChild(this.infoBarElement))):this.cleanupFooter()}cleanup(){this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null),this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null)}cleanupFooter(){this.footerWrapper&&(this.footerWrapper.remove(),this.footerWrapper=null),this.bottomAggregationContainer&&(this.bottomAggregationContainer.remove(),this.bottomAggregationContainer=null),this.infoBarElement&&"top"!==this.config.position&&(this.infoBarElement.remove(),this.infoBarElement=null)}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}getFilterState(){try{return this.grid?.getPluginState?.("filtering")??null}catch{return null}}refresh(){this.requestRender()}getContext(){const e=this.getSelectionState(),t=this.getFilterState();return Li(this.rows,this.columns,this.grid,e,t)}addPanel(e){this.config.customPanels||(this.config.customPanels=[]),this.config.customPanels.push(e),this.requestRender()}removePanel(e){this.config.customPanels&&(this.config.customPanels=this.config.customPanels.filter(t=>t.id!==e),this.requestRender())}addAggregationRow(e){this.config.aggregationRows||(this.config.aggregationRows=[]),this.config.aggregationRows.push(e),this.requestRender()}removeAggregationRow(e){this.config.aggregationRows&&(this.config.aggregationRows=this.config.aggregationRows.filter(t=>t.id!==e),this.requestRender())}},e.PivotPlugin=$i,e.PluginEvents={SELECTION_CHANGE:"selection-change",TREE_EXPAND:"tree-expand",FILTER_CHANGE:"filter-change",SORT_MODEL_CHANGE:"sort-model-change",EXPORT_START:"export-start",EXPORT_COMPLETE:"export-complete",CLIPBOARD_COPY:"clipboard-copy",CLIPBOARD_PASTE:"clipboard-paste",CONTEXT_MENU_OPEN:"context-menu-open",CONTEXT_MENU_CLOSE:"context-menu-close",HISTORY_CHANGE:"history-change",SERVER_LOADING:"server-loading",SERVER_ERROR:"server-error",COLUMN_VISIBILITY_CHANGE:"column-visibility-change",COLUMN_REORDER:"column-reorder",DETAIL_EXPAND:"detail-expand",GROUP_EXPAND:"group-expand"},e.PluginManager=it,e.PrintPlugin=class extends rt{name="print";version="1.0.0";styles=".tbw-print-header,.tbw-print-footer{display:none}@media print{tbw-grid{overflow:visible!important;height:auto!important;border:none!important;border-radius:0!important;color-scheme:light only;-webkit-print-color-adjust:exact;print-color-adjust:exact}tbw-grid .tbw-grid-content{overflow:visible!important;height:auto!important;max-height:none!important}tbw-grid .tbw-scroll-area{overflow:visible!important;height:auto!important;max-height:none!important}tbw-grid .rows-body{overflow:visible!important;height:auto!important;max-height:none!important}tbw-grid .rows-container,tbw-grid .rows-viewport,tbw-grid .rows{overflow:visible!important;height:auto!important;max-height:none!important;transform:none!important}tbw-grid .rows-viewport .rows{position:static!important}tbw-grid .resize-handle,tbw-grid [part=sort-indicator],tbw-grid .tbw-filter-btn,tbw-grid .tool-panel,tbw-grid .tool-panel-content,tbw-grid .tbw-shell-header,tbw-grid .shell-toolbar,tbw-grid .tool-panel-toggle,tbw-grid [data-print-hide],tbw-grid .expander-cell,tbw-grid .tree-toggle,tbw-grid .context-menu,tbw-grid .faux-vscroll{display:none!important}tbw-grid .tbw-print-header{display:flex;justify-content:space-between;align-items:baseline;padding:var(--tbw-spacing-md, .5em) 0;margin-bottom:var(--tbw-spacing-md, .5em);border-bottom:2px solid var(--tbw-print-border, var(--tbw-color-border-strong));font-family:inherit}.tbw-print-header-title{font-size:1.25em;font-weight:700}.tbw-print-header-timestamp{font-size:var(--tbw-font-size-sm, .875em);color:var(--tbw-print-muted, var(--tbw-color-fg-muted))}tbw-grid .tbw-print-footer{display:block;margin-top:var(--tbw-spacing-md, .5em);padding-top:var(--tbw-spacing-md, .5em);border-top:1px solid var(--tbw-print-border, var(--tbw-color-border));font-size:var(--tbw-font-size-xs, .75em);color:var(--tbw-print-muted, var(--tbw-color-fg-muted));text-align:end}tbw-grid .data-grid-row{break-inside:avoid;page-break-inside:avoid}tbw-grid .cell{border:1px solid var(--tbw-print-cell-border, var(--tbw-color-border))!important}tbw-grid .header-row,tbw-grid .data-grid-row{padding-inline-end:1px}tbw-grid .data-grid-row:hover,tbw-grid .cell:hover{background:inherit!important}@page{margin:1cm}@page{tbw-grid.print-landscape{size:landscape}}@page{tbw-grid.print-portrait{size:portrait}}}";#ci=!1;#hi=null;#ui=null;#gi=null;#pi=null;#fi=null;#wi=null;get#mi(){return this.grid}isPrinting(){return this.#ci}async print(e){if(this.#ci)return void console.warn("[PrintPlugin] Print already in progress");const t=this.gridElement;if(!t)return void console.warn("[PrintPlugin] Grid not available");const i={...Ui,...this.config,...e},n=this.rows.length;let r=n,o=!1;if(i.warnThreshold>0&&n>i.warnThreshold){const e=i.maxRows>0?`\n\nNote: Output will be limited to ${i.maxRows.toLocaleString()} rows.`:"";if(!confirm(`This grid has ${n.toLocaleString()} rows. Printing large datasets may cause performance issues or browser slowdowns.${e}\n\nClick OK to continue, or Cancel to abort.`))return}i.maxRows>0&&n>i.maxRows&&(r=i.maxRows,o=!0),this.#ci=!0;const s=performance.now();this.emit("print-start",{rowCount:r,limitApplied:o,originalRowCount:n});try{const e=this.#mi;this.#ui={bypassThreshold:e._virtualization?.bypassThreshold??24},this.#bi(),o&&(this.#gi=this.sourceRows,this.grid.rows=this.sourceRows.slice(0,r),await new Promise(e=>setTimeout(e,50))),(i.includeTitle||i.includeTimestamp)&&this.#vi(i),await this.#yi(),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.#Ci(i):await this.#xi(),this.emit("print-complete",{success:!0,rowCount:r,duration:Math.round(performance.now()-s)})}catch(l){console.error("[PrintPlugin] Print failed:",l),this.emit("print-complete",{success:!1,rowCount:0,duration:Math.round(performance.now()-s)})}finally{this.#Ei(),this.#ci=!1}}#vi(e){const t=this.gridElement;if(t){if(this.#pi=document.createElement("div"),this.#pi.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.#pi.appendChild(i)}if(e.includeTimestamp){const e=document.createElement("div");e.className="tbw-print-header-timestamp",e.textContent=`Printed: ${(new Date).toLocaleString()}`,this.#pi.appendChild(e)}t.insertBefore(this.#pi,t.firstChild),this.#fi=document.createElement("div"),this.#fi.className="tbw-print-footer",this.#fi.textContent=`Page generated from ${window.location.hostname}`,t.appendChild(this.#fi)}}async#yi(){const e=this.#mi;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#xi(){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#Ci(e){const t=this.gridElement;t&&await Ki(t,{orientation:e.orientation})}#bi(){const e=this.columns;if(e){this.#hi=new Map;for(const t of e)t.printHidden&&t.field&&(this.#hi.set(t.field,!t.hidden),this.grid.setColumnVisible(t.field,!1))}}#Ri(){if(this.#hi){for(const[e,t]of this.#hi)this.grid.setColumnVisible(e,t);this.#hi=null}}#Ei(){const e=this.gridElement;if(!e)return;this.#Ri(),e.classList.remove("print-portrait","print-landscape"),null!==this.#wi&&(e.style.transform="",e.style.transformOrigin="",e.style.width="",this.#wi=null),this.#pi&&(this.#pi.remove(),this.#pi=null),this.#fi&&(this.#fi.remove(),this.#fi=null);const t=this.#mi;this.#ui&&t._virtualization&&(t._virtualization.bypassThreshold=this.#ui.bypassThreshold,t.refreshVirtualWindow(!0),this.#ui=null),null!==this.#gi&&(this.grid.rows=this.#gi,this.#gi=null)}afterRender(){this.config?.button&&!this.#Si&&(this.#_i(),this.#Si=!0)}#Si=!1;#_i(){const e=this.#mi;e.registerToolbarContent?.({id:"print-button",order:900,render:e=>{const t=document.createElement("button");t.className="tbw-toolbar-btn tbw-print-btn",t.title="Print grid",t.type="button";const i=this.resolveIcon("print")||"🖨️";this.setIcon(t,i),t.addEventListener("click",()=>{this.print()},{signal:this.disconnectSignal}),e.appendChild(t)}})}},e.ROW_DRAG_HANDLE_FIELD=Yi,e.RenderPhase=he,e.ReorderPlugin=class extends rt{name="reorder";styles='@layer tbw-plugins{.header-row>.cell[draggable=true]{cursor:grab;position:relative}.header-row>.cell.dragging{opacity:.5;cursor:grabbing}.header-row>.cell.drop-before:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.header-row>.cell.drop-after:after{content:"";position:absolute;right:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.cell.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}@keyframes reorder-fade-in{0%{opacity:0}to{opacity:1}}.cell.fade-animating{animation:reorder-fade-in var(--tbw-animation-duration, .2s) ease-out backwards}}';get defaultConfig(){return{animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}get animationDuration(){return void 0!==this.config.animationDuration?this.config.animationDuration:super.animationDuration}isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;canMoveColumnWithPlugins(e){if(!e||!function(e){const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}(e))return!1;return!this.grid.query("canMoveColumn",e).includes(!1)}clearDragClasses(){this.gridElement?.querySelectorAll(".header-row > .cell").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-reorder-request",e=>{const t=e.detail;t?.field&&"number"==typeof t.toIndex&&this.moveColumn(t.field,t.toIndex)},{signal:this.disconnectSignal})}detach(){this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}afterRender(){const e=this.gridElement;if(!e)return;e.querySelectorAll(".header-row > .cell").forEach(e=>{const t=e,i=t.getAttribute("data-field");if(!i)return;const n=this.columns.find(e=>e.field===i);this.canMoveColumnWithPlugins(n)?(t.draggable=!0,t.getAttribute("data-dragstart-bound")||(t.setAttribute("data-dragstart-bound","true"),t.addEventListener("dragstart",e=>{const n=this.getColumnOrder().indexOf(i);this.isDragging=!0,this.draggedField=i,this.draggedIndex=n,e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",i)),t.classList.add("dragging")}),t.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses()}),t.addEventListener("dragover",e=>{if(e.preventDefault(),!this.isDragging||this.draggedField===i)return;const n=t.getBoundingClientRect(),r=n.left+n.width/2,o=this.getColumnOrder().indexOf(i);this.dropIndex=e.clientX<r?o:o+1,t.classList.add("drop-target"),t.classList.toggle("drop-before",e.clientX<r),t.classList.toggle("drop-after",e.clientX>=r)}),t.addEventListener("dragleave",()=>{t.classList.remove("drop-target","drop-before","drop-after")}),t.addEventListener("drop",e=>{e.preventDefault();const t=this.draggedField,i=this.draggedIndex,n=this.dropIndex;if(!this.isDragging||null===t||null===i||null===n)return;const r=n>i?n-1:n,o=ji(this.getColumnOrder(),i,r),s={field:t,fromIndex:i,toIndex:r,columnOrder:o};this.emitCancelable("column-move",s)||this.updateColumnOrder(o)}))):t.draggable=!1})}onKeyDown(e){if(!e.altKey||"ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;const t=this.grid,i=t._focusCol,n=t._visibleColumns;if(i<0||i>=n.length)return;const r=n[i];if(!this.canMoveColumnWithPlugins(r))return;const o=this.getColumnOrder(),s=o.indexOf(r.field);if(-1===s)return;const l="ArrowLeft"===e.key?s-1:s+1;if(l<0||l>=o.length)return;const a=n.find(e=>e.field===o[l]);return this.canMoveColumnWithPlugins(a)?(this.moveColumn(r.field,l),t._focusCol=l,K(this.grid),e.preventDefault(),e.stopPropagation(),!0):void 0}getColumnOrder(){return this.grid.getColumnOrder()}moveColumn(e,t){const i=this.getColumnOrder(),n=i.indexOf(e);if(-1===n)return;const r=ji(i,n,t);this.emitCancelable("column-move",{field:e,fromIndex:n,toIndex:t,columnOrder:r})||this.updateColumnOrder(r)}setColumnOrder(e){this.updateColumnOrder(e)}resetColumnOrder(){const e=this.columns.map(e=>e.field);this.updateColumnOrder(e)}captureHeaderPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const i=t.getAttribute("data-field");i&&e.set(i,t.getBoundingClientRect().left)}),e}animateFLIP(e){const t=this.gridElement;if(!t||0===e.size)return;const i=new Map;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const n=t.getAttribute("data-field");if(!n)return;const r=e.get(n);if(void 0===r)return;const o=r-t.getBoundingClientRect().left;Math.abs(o)>1&&i.set(n,o)}),0===i.size)return;const n=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=i.get(e.getAttribute("data-field")??"");if(void 0!==t){const i=e;i.style.transform=`translateX(${t}px)`,n.push(i)}}),0===n.length)return;this.gridElement.offsetHeight;const r=this.animationDuration;requestAnimationFrame(()=>{n.forEach(e=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{n.forEach(e=>{e.style.transform="",e.classList.remove("flip-animating")})},r+50)})}animateFade(e){const t=this.gridElement;if(!t)return void e();const i=this.captureHeaderPositions();e();const n=new Set;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(!t)return;const r=i.get(t);if(void 0===r)return;const o=e.getBoundingClientRect().left;Math.abs(r-o)>1&&n.add(t)}),0===n.size)return;const r=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(t&&n.has(t)){const t=e;t.classList.add("fade-animating"),r.push(t)}}),0===r.length)return;const o=this.animationDuration;setTimeout(()=>{r.forEach(e=>e.classList.remove("fade-animating"))},o+50)}updateColumnOrder(e){const t=this.animationType;if("flip"===t&&this.gridElement){const t=this.captureHeaderPositions();this.grid.setColumnOrder(e),requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(t)})}else"fade"===t?this.animateFade(()=>this.grid.setColumnOrder(e)):this.grid.setColumnOrder(e);this.grid.requestStateChange?.()}},e.ResponsivePlugin=class extends rt{name="responsive";version="1.0.0";styles='tbw-grid[data-responsive-animate] .data-grid-row,tbw-grid[data-responsive-animate] .data-grid-row>.cell{transition:opacity var(--tbw-responsive-duration, .2s) ease-out,transform var(--tbw-responsive-duration, .2s) ease-out}tbw-grid[data-responsive][data-responsive-animate] .data-grid-row{animation:responsive-card-enter var(--tbw-responsive-duration, .2s) ease-out}@keyframes responsive-card-enter{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}tbw-grid[data-responsive] .header{display:none!important}tbw-grid[data-responsive] .footer-row{display:none}tbw-grid[data-responsive] .tbw-scroll-area{overflow-x:hidden;min-width:0!important}tbw-grid[data-responsive] .rows-body-wrapper{min-width:0!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row){display:block!important;grid-template-columns:none!important;padding:var(--tbw-cell-padding);padding-inline-start:var(--tbw-spacing-xl);border-bottom:1px solid var(--tbw-color-border);min-height:auto!important;height:auto!important;contain:none!important;content-visibility:visible!important;background:var(--tbw-color-bg);position:relative}tbw-grid[data-responsive] .data-grid-row:not(.group-row):nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid[data-responsive] .data-grid-row:not(.group-row):hover{background:var(--tbw-color-row-hover)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]{background:var(--tbw-color-selection)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]:before{content:"";position:absolute;inset-inline-start:0;top:0;bottom:0;width:4px;background:var(--tbw-color-accent)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell{display:flex!important;justify-content:space-between;align-items:center;padding:var(--tbw-spacing-xs) var(--tbw-spacing-md);width:100%!important;min-width:0!important;min-height:auto!important;height:auto!important;line-height:1.5!important;position:static!important;left:auto!important;right:auto!important;border:none!important;border-bottom:none!important;border-inline-end:none!important;background:transparent!important;white-space:normal!important;overflow:visible!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:before{content:attr(data-header) ": ";font-weight:600;color:var(--tbw-color-header-fg);flex-shrink:0;margin-inline-end:var(--tbw-spacing-md);min-width:100px}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:after{content:none}tbw-grid[data-responsive] .cell[data-utility]{display:none!important}tbw-grid[data-responsive] .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .cell[data-responsive-value-only]:before{display:none!important}tbw-grid:not([data-responsive]) .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .tbw-footer,tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows{display:none!important}tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows,tbw-grid[data-responsive] .tbw-aggregation-row{min-width:0!important}tbw-grid[data-responsive] .data-grid-row.responsive-card{display:block!important;padding:var(--tbw-cell-padding);border-bottom:1px solid var(--tbw-color-border)}tbw-grid[data-responsive] .data-grid-row.responsive-card>*{width:100%}tbw-grid[data-responsive] .data-grid-row.responsive-card .cell:before{display:none}';static manifest={incompatibleWith:[{name:"groupingRows",reason:"Responsive card layout does not yet support row grouping. The variable row heights (cards vs group headers) cause scroll calculation issues."}],queries:[{type:"isCardMode",description:"Returns whether the grid is currently in responsive card mode"}]};#K;#Ai=!1;#ki;#Ti=!1;#Li=0;#Mi=new Set;#Ii=new Set;#Pi=null;#Hi=[];isResponsive(){return this.#Ai}setResponsive(e){e!==this.#Ai&&(this.#Ai=e,this.#Di(),this.emit("responsive-change",{isResponsive:e,width:this.#Li,breakpoint:this.config.breakpoint??0}))}setBreakpoint(e){this.config.breakpoint=e,this.#zi(this.#Li)}setCardRenderer(e){this.config.cardRenderer=e,this.#Ai&&this.requestRender()}getWidth(){return this.#Li}getActiveBreakpoint(){return this.#Pi}attach(e){super.attach(e),this.#Oi(),this.#Fi(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#Hi=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#K=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#Li=t,clearTimeout(this.#ki),this.#ki=setTimeout(()=>{this.#zi(t)},this.config.debounceMs??100)}),this.#K.observe(this.gridElement)}#Oi(){const e=this.grid;if(!e||"function"!=typeof e.querySelector)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const i=e;if(i.__frameworkAdapter?.parseResponsiveCardElement){const e=i.__frameworkAdapter.parseResponsiveCardElement(t);e&&(this.config={...this.config,cardRenderer:e})}const n=t.getAttribute("breakpoint"),r=t.getAttribute("card-row-height"),o=t.getAttribute("hidden-columns"),s=t.getAttribute("hide-header"),l=t.getAttribute("debounce-ms"),a={};if(null!==n){const e=parseInt(n,10);isNaN(e)||(a.breakpoint=e)}if(null!==r&&(a.cardRowHeight="auto"===r?"auto":parseInt(r,10)),null!==o&&(a.hiddenColumns=o.split(",").map(e=>e.trim()).filter(e=>e.length>0)),null!==s&&(a.hideHeader="false"!==s),null!==l){const e=parseInt(l,10);isNaN(e)||(a.debounceMs=e)}const d=t.innerHTML.trim();!d||this.config.cardRenderer||i.__frameworkAdapter?.parseResponsiveCardElement||(a.cardRenderer=e=>{const t=y(C(d,{value:e,row:e})),i=document.createElement("div");return i.className="tbw-responsive-card-content",i.innerHTML=t,i}),Object.keys(a).length>0&&(this.config={...this.config,...a})}#Fi(e){if(this.#Mi.clear(),this.#Ii.clear(),e)for(const t of e)"string"==typeof t?this.#Mi.add(t):t.showValue?this.#Ii.add(t.field):this.#Mi.add(t.field)}detach(){this.#K?.disconnect(),this.#K=void 0,clearTimeout(this.#ki),this.#ki=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#Ai}afterRender(){this.#qi();if(!(this.#Hi.length>0?null!==this.#Pi:this.#Ai))return;const e=this.#Mi.size>0,t=this.#Ii.size>0;if(!e&&!t)return;const i=this.gridElement.querySelectorAll(".cell[data-field]");for(const n of i){const e=n.getAttribute("data-field");e&&(this.#Mi.has(e)?(n.setAttribute("data-responsive-hidden",""),n.removeAttribute("data-responsive-value-only")):this.#Ii.has(e)?(n.setAttribute("data-responsive-value-only",""),n.removeAttribute("data-responsive-hidden")):(n.removeAttribute("data-responsive-hidden"),n.removeAttribute("data-responsive-value-only")))}}#zi(e){if(this.#Hi.length>0)return void this.#Ni(e);const t=this.config.breakpoint??0;0!==t||this.#Ti||(this.#Ti=!0,console.warn("[tbw-grid:ResponsivePlugin] No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count."));const i=t>0&&e<t;i!==this.#Ai&&(this.#Ai=i,this.#Di(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#Ni(e){let t=null;for(const i of this.#Hi)e<=i.maxWidth&&(t=i);if(t!==this.#Pi){this.#Pi=t,t?.hiddenColumns?this.#Fi(t.hiddenColumns):this.#Fi(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#Ai&&(this.#Ai=i,this.#Di()),this.emit("responsive-change",{isResponsive:this.#Ai,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#Gi;#Di(){this.gridElement.toggleAttribute("data-responsive",this.#Ai);const e=!1!==this.config.animate;this.gridElement.toggleAttribute("data-responsive-animate",e),this.config.animationDuration&&this.gridElement.style.setProperty("--tbw-responsive-duration",`${this.config.animationDuration}ms`);const t=this.grid;if(this.#Ai){t._virtualization&&(this.#Gi=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.#Gi&&this.#Gi>0&&t._virtualization&&(t._virtualization.rowHeight=this.#Gi,this.#Gi=void 0),this.#Bi=void 0,this.#Vi=void 0,this.#$i=void 0}}renderRow(e,t,i){if(!this.#Ai||!this.config.cardRenderer)return;if(e.__isGroupRow)return;t.replaceChildren();const n=this.config.cardRenderer(e,i);t.className="data-grid-row responsive-card";const r=this.config.cardRowHeight??"auto";return t.style.height="auto"!==r?`${r}px`:"auto",t.appendChild(n),!0}onKeyDown(e){if(!this.#Ai)return!1;if(this.config.cardRenderer){if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return!1}const t=this.rows.length-1,i=this.visibleColumns.length-1;switch(e.key){case"ArrowDown":if(this.grid._focusCol<i)return this.grid._focusCol+=1,e.preventDefault(),K(this.grid),!0;if(this.grid._focusRow<t)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),K(this.grid),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),K(this.grid),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=i,e.preventDefault(),K(this.grid),!0;break;case"ArrowRight":if(this.grid._focusRow<t)return this.grid._focusRow+=1,e.preventDefault(),K(this.grid),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),K(this.grid),!0}return!1}#Bi;#Vi;#$i;#Wi(){if(this.#Bi&&this.#Bi>0)return this.#Bi;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#Ki(){return this.#Vi&&this.#Vi>0?this.#Vi:this.#Gi??28}#Ui(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}#ji(){let e=0,t=0;for(const i of this.rows)i.__isGroupRow?e++:t++;return{groupCount:e,cardCount:t}}getExtraHeight(){if(!this.#Ai||!this.config.cardRenderer)return 0;if(!this.#Ui())return 0;const e=this.#Gi??28,t=this.#Ki(),i=this.#Wi(),{groupCount:n,cardCount:r}=this.#ji();return n*Math.max(0,t-e)+r*Math.max(0,i-e)}getExtraHeightBefore(e){if(!this.#Ai||!this.config.cardRenderer)return 0;if(!this.#Ui())return 0;const t=this.#Gi??28,i=this.#Ki(),n=this.#Wi(),r=Math.max(0,i-t),o=Math.max(0,n-t);let s=0,l=0;const a=this.rows,d=Math.min(e,a.length);for(let c=0;c<d;c++)a[c].__isGroupRow?s++:l++;return s*r+l*o}getRowHeight(e,t){if(this.#Ai&&this.config.cardRenderer)return e.__isGroupRow?this.#Ki():this.#Wi()}#Yi(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#Xi=!1;#qi(){if(!this.#Ai||!this.config.cardRenderer)return;let e=!1;const t=this.grid,i=this.#Ui(),n=this.#Yi();if(n!==this.#$i&&(this.#$i=n,e=!0),i){const t=this.gridElement.querySelector(".data-grid-row.group-row");if(t){const i=t.getBoundingClientRect().height;i>0&&i!==this.#Vi&&(this.#Vi=i,e=!0)}}const r=this.gridElement.querySelector(".data-grid-row.responsive-card");if(r){const n=r.getBoundingClientRect().height;n>0&&n!==this.#Bi&&(this.#Bi=n,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=n))}e&&!this.#Xi&&(this.#Xi=!0,queueMicrotask(()=>{this.#Xi=!1,this.grid&&this.#Ai&&this.grid.refreshVirtualWindow?.(!0,!0)}))}},e.RowReorderPlugin=class extends rt{name="rowReorder";styles='@layer tbw-plugins{[data-field=__tbw_row_drag]{display:flex;align-items:center;justify-content:center}.dg-row-drag-handle{display:flex;align-items:center;justify-content:center;min-width:1em;min-height:1em;cursor:grab;-webkit-user-select:none;user-select:none;color:var(--tbw-row-reorder-handle-color, var(--tbw-color-fg-muted));transition:color var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease);font-size:var(--tbw-font-size, 1em);letter-spacing:-2px}.dg-row-drag-handle:hover{color:var(--tbw-row-reorder-handle-hover, var(--tbw-color-fg))}.dg-row-drag-handle:active{cursor:grabbing}.data-grid-row.dragging{opacity:.6}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before{content:"";position:absolute;top:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.drop-target.drop-after:after{content:"";position:absolute;bottom:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.keyboard-moving{background-color:var(--tbw-row-reorder-moving-bg, var(--tbw-focus-background));box-shadow:0 0 0 1px var(--tbw-row-reorder-moving-border, var(--tbw-color-accent)) inset}.data-grid-row.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}}';get defaultConfig(){return{enableKeyboard:!0,showDragHandle:!0,dragHandlePosition:"left",dragHandleWidth:40,debounceMs:150,animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}isDragging=!1;draggedRowIndex=null;dropRowIndex=null;pendingMove=null;debounceTimer=null;lastFocusCol=0;detach(){this.clearDebounceTimer(),this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.pendingMove=null}processColumns(e){if(!this.config.showDragHandle)return[...e];const t={field:Yi,header:"",width:this.config.dragHandleWidth??40,resizable:!1,sortable:!1,filterable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0},viewRenderer:()=>{const e=document.createElement("div");return e.className="dg-row-drag-handle",e.setAttribute("aria-label","Drag to reorder"),e.setAttribute("role","button"),e.setAttribute("tabindex","-1"),e.draggable=!0,this.setIcon(e,this.resolveIcon("dragHandle")),e}};return"right"===this.config.dragHandlePosition?[...e,t]:[t,...e]}afterRender(){if(!this.config.showDragHandle)return;const e=this.gridElement;if(!e)return;e.querySelectorAll(".dg-row-drag-handle").forEach(e=>{const t=e;if(t.getAttribute("data-drag-bound"))return;t.setAttribute("data-drag-bound","true");const i=t.closest(".data-grid-row");i&&this.setupHandleDragListeners(t,i)});e.querySelectorAll(".data-grid-row").forEach(e=>{const t=e;t.getAttribute("data-drop-bound")||(t.setAttribute("data-drop-bound","true"),this.setupRowDropListeners(t))})}onKeyDown(e){if(!this.config.enableKeyboard)return;if(!e.ctrlKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key)return;const t=this.grid,i=t._focusRow,n=t._rows??this.sourceRows;if(i<0||i>=n.length)return;const r="ArrowUp"===e.key?"up":"down",o="up"===r?i-1:i+1;if(o<0||o>=n.length)return;const s=n[i];return!this.config.canMove||this.config.canMove(s,i,o,r)?(this.handleKeyboardMove(s,i,o,r,t._focusCol),e.preventDefault(),e.stopPropagation(),!0):void 0}onCellClick(){this.flushPendingMove()}moveRow(e,t){const i=[...this.sourceRows];if(e<0||e>=i.length)return;if(t<0||t>=i.length)return;if(e===t)return;const n=t<e?"up":"down",r=i[e];this.config.canMove&&!this.config.canMove(r,e,t,n)||this.executeMove(r,e,t,"keyboard")}canMoveRow(e,t){const i=this.sourceRows;if(e<0||e>=i.length)return!1;if(t<0||t>=i.length)return!1;if(e===t)return!1;if(!this.config.canMove)return!0;const n=t<e?"up":"down";return this.config.canMove(i[e],e,t,n)}setupHandleDragListeners(e,t){e.addEventListener("dragstart",e=>{const i=this.getRowIndex(t);i<0||(this.isDragging=!0,this.draggedRowIndex=i,e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",String(i))),t.classList.add("dragging"))}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.clearDragClasses()})}setupRowDropListeners(e){e.addEventListener("dragover",t=>{if(t.preventDefault(),!this.isDragging||null===this.draggedRowIndex)return;const i=this.getRowIndex(e);if(i<0||i===this.draggedRowIndex)return;const n=e.getBoundingClientRect(),r=n.top+n.height/2,o=t.clientY<r;this.dropRowIndex=o?i:i+1,e.classList.add("drop-target"),e.classList.toggle("drop-before",o),e.classList.toggle("drop-after",!o)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",e=>{e.preventDefault();const t=this.draggedRowIndex;let i=this.dropRowIndex;if(this.isDragging&&null!==t&&null!==i&&(i>t&&i--,t!==i)){const e=this.sourceRows[t],n=i<t?"up":"down";this.config.canMove&&!this.config.canMove(e,t,i,n)||this.executeMove(e,t,i,"drag")}})}handleKeyboardMove(e,t,i,n,r){this.pendingMove?this.pendingMove.currentIndex=i:this.pendingMove={originalIndex:t,currentIndex:i,row:e},this.lastFocusCol=r;const o=this.grid,s=[...o._rows??this.sourceRows],[l]=s.splice(t,1);s.splice(i,0,l),o._rows=s,o._focusRow=i,o._focusCol=r,o.refreshVirtualWindow(!0),K(o),this.clearDebounceTimer(),this.debounceTimer=setTimeout(()=>{this.flushPendingMove()},this.config.debounceMs??300)}flushPendingMove(){if(this.clearDebounceTimer(),!this.pendingMove)return;const{originalIndex:e,currentIndex:t,row:i}=this.pendingMove;if(this.pendingMove=null,e===t)return;const n={row:i,fromIndex:e,toIndex:t,rows:[...this.sourceRows],source:"keyboard"};if(this.emitCancelable("row-move",n)){const i=[...this.sourceRows],[n]=i.splice(t,1);i.splice(e,0,n);const r=this.grid;r._rows=i,r._focusRow=e,r._focusCol=this.lastFocusCol,r.refreshVirtualWindow(!0),K(r)}}executeMove(e,t,i,n){const r=[...this.sourceRows],[o]=r.splice(t,1);r.splice(i,0,o);const s={row:e,fromIndex:t,toIndex:i,rows:r,source:n};if(!this.emitCancelable("row-move",s))if("flip"===this.animationType&&this.gridElement){const e=this.captureRowPositions();this.grid.rows=r,requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(e,t,i)})}else this.grid.rows=r}captureRowPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".data-grid-row").forEach(t=>{const i=this.getRowIndex(t);i>=0&&e.set(i,t.getBoundingClientRect().top)}),e}animateFLIP(e,t,i){const n=this.gridElement;if(!n||0===e.size)return;const r=Math.min(t,i),o=Math.max(t,i),s=[];if(n.querySelectorAll(".data-grid-row").forEach(n=>{const l=n,a=this.getRowIndex(l);if(a<0||a<r||a>o)return;let d;d=a===i?t:t<i?a+1:a-1;const c=e.get(d);if(void 0===c)return;const h=c-l.getBoundingClientRect().top;Math.abs(h)>1&&s.push({el:l,deltaY:h})}),0===s.length)return;s.forEach(({el:e,deltaY:t})=>{e.style.transform=`translateY(${t}px)`}),n.offsetHeight;const l=this.animationDuration;requestAnimationFrame(()=>{s.forEach(({el:e})=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{s.forEach(({el:e})=>{e.style.transform="",e.classList.remove("flip-animating")})},l+50)})}getRowIndex(e){const t=e.querySelector(".cell[data-row]");return t?parseInt(t.getAttribute("data-row")??"-1",10):-1}clearDragClasses(){this.gridElement?.querySelectorAll(".data-grid-row").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}},e.SelectionPlugin=class extends rt{static manifest={queries:[{type:"getSelection",description:"Get the current selection state"},{type:"selectRows",description:"Select specific rows by index (row mode only)"},{type:"getSelectedRowIndices",description:"Get sorted array of selected row indices"},{type:"getSelectedRows",description:"Get actual row objects for the current selection (works in all modes)"}],configRules:[{id:"selection/range-dblclick",severity:"warn",message:'"triggerOn: \'dblclick\'" has no effect when mode is "range".\n → Range selection uses drag interaction (mousedown → mousemove), not click events.\n → The "triggerOn" option only affects "cell" and "row" selection modes.',check:e=>"range"===e.mode&&"dblclick"===e.triggerOn}]};name="selection";styles='@layer tbw-plugins{tbw-grid.selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}tbw-grid:has(.selection){-webkit-user-select:none;user-select:none}tbw-grid .data-grid-row.row-focus{background-color:var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%));outline:none;position:relative}tbw-grid .data-grid-row.row-focus:after{content:"";position:absolute;inset:0;pointer-events:none;border-width:0;border-style:var(--tbw-selection-border-style, var(--tbw-border-style));border-color:var(--tbw-range-border-color, var(--tbw-color-accent));border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width));border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width));z-index:1}tbw-grid .data-grid-row.row-focus+.data-grid-row.row-focus:after{border-top-width:0}tbw-grid .data-grid-row.row-focus:has(+.data-grid-row.row-focus):after{border-bottom-width:0}tbw-grid[data-selection-mode=row] .cell-focus,tbw-grid[data-selection-mode=row] .row-focus,tbw-grid[data-selection-mode=range] .cell-focus{outline:none}tbw-grid .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg);position:relative}tbw-grid .data-grid-row>.cell.selected:after{content:"";position:absolute;inset:0;pointer-events:none;border:0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1}tbw-grid .data-grid-row>.cell.selected.top:after{border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.bottom:after{border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.first:after{border-left-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.last:after{border-right-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row[data-selectable=false].row-focus{background-color:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row>.cell[data-selectable=false].selected{background-color:var(--tbw-selection-warning-bg, rgba(from var(--tbw-color-error) r g b / 50%))}tbw-grid .tbw-selection-summary{font-size:var(--tbw-font-size-sm, .8125rem);color:var(--tbw-color-fg-muted);white-space:nowrap}tbw-grid .data-grid-row>.cell[data-field=__tbw_checkbox],tbw-grid .header-row>.cell[data-field=__tbw_checkbox]{text-align:center;cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .tbw-select-row-checkbox{pointer-events:none;margin:0;cursor:pointer}tbw-grid .tbw-checkbox-header{display:flex;justify-content:center;align-items:center;height:100%}tbw-grid .tbw-select-all-checkbox{margin:0;cursor:pointer}}';get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0}}selected=new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;selectedCell=null;lastSyncedFocusRow=-1;lastSyncedFocusCol=-1;explicitSelection=!1;isSelectionEnabled(){return!1!==this.config.enabled&&!1!==this.grid.effectiveConfig?.selectable}checkSelectable(e,t){const{isSelectable:i}=this.config;if(!i)return!0;const n=this.rows[e];if(!n)return!1;return i(n,e,void 0!==t?this.visibleColumns[t]:void 0,t)}isRowSelectable(e){return this.checkSelectable(e)}isCellSelectable(e,t){return this.checkSelectable(e,t)}attach(e){super.attach(e),this.on("filter-applied",()=>this.clearSelectionSilent()),this.on("grouping-state-change",()=>this.clearSelectionSilent()),this.on("tree-state-change",()=>this.clearSelectionSilent())}handleQuery(e){return"getSelection"===e.type?this.getSelection():"getSelectedRowIndices"===e.type?this.getSelectedRowIndices():"getSelectedRows"===e.type?this.getSelectedRows():"selectRows"===e.type?(this.selectRows(e.context),!0):void 0}detach(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.pendingKeyboardUpdate=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1}clearSelectionSilent(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedCell=null,this.lastSelected=null,this.anchor=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,this.requestAfterRender()}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{rowIndex:t,colIndex:i,originalEvent:n}=e,{mode:r,triggerOn:o="click"}=this.config;if(n.type!==o)return!1;const s=e.column,l=s&&Jt(s);if("cell"===r){if(l)return!1;if(!this.isCellSelectable(t,i))return!1;const e=this.selectedCell;return e&&e.row===t&&e.col===i||(this.selectedCell={row:t,col:i},this.emit("selection-change",this.#Zi()),this.requestAfterRender()),!1}if("row"===r){if(!this.isRowSelectable(t))return!1;const e=!1!==this.config.multiSelect,i=n.shiftKey&&e,r=(n.ctrlKey||n.metaKey)&&e,o=!0===s?.meta?.checkboxColumn;if(i&&null!==this.anchor){const e=Math.min(this.anchor,t),i=Math.max(this.anchor,t);r||this.selected.clear();for(let t=e;t<=i;t++)this.isRowSelectable(t)&&this.selected.add(t)}else if(r||o&&e)this.selected.has(t)?this.selected.delete(t):this.selected.add(t),this.anchor=t;else{if(1===this.selected.size&&this.selected.has(t))return!1;this.selected.clear(),this.selected.add(t),this.anchor=t}return this.lastSelected=t,this.explicitSelection=!0,this.emit("selection-change",this.#Zi()),this.requestAfterRender(),!1}if("range"===r){if(l)return!1;if(!this.isCellSelectable(t,i))return!1;const e=n.shiftKey,r=(n.ctrlKey||n.metaKey)&&!1!==this.config.multiSelect;if(e&&this.cellAnchor){const e=tn(this.cellAnchor,{row:t,col:i}),n=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(n&&nn(n,e))return!1;r?this.ranges.length>0?this.ranges[this.ranges.length-1]=e:this.ranges.push(e):this.ranges=[e],this.activeRange=e}else if(r){const e={startRow:t,startCol:i,endRow:t,endCol:i};this.ranges.push(e),this.activeRange=e,this.cellAnchor={row:t,col:i}}else{const e={startRow:t,startCol:i,endRow:t,endCol:i};if(1===this.ranges.length&&nn(this.ranges[0],e))return!1;this.ranges=[e],this.activeRange=e,this.cellAnchor={row:t,col:i}}return this.emit("selection-change",this.#Zi()),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.#Zi()),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.#Zi()),this.requestAfterRender()}),!1;if("row"===t){const t=!1!==this.config.multiSelect;if("ArrowUp"===e.key||"ArrowDown"===e.key){const i=e.shiftKey&&t;return i&&null===this.anchor&&(this.anchor=this.grid._focusRow),queueMicrotask(()=>{const e=this.grid._focusRow;if(i&&null!==this.anchor){this.selected.clear();const t=Math.min(this.anchor,e),i=Math.max(this.anchor,e);for(let e=t;e<=i;e++)this.isRowSelectable(e)&&this.selected.add(e)}else this.isRowSelectable(e)?(this.selected.clear(),this.selected.add(e),this.anchor=e):this.selected.clear();this.lastSelected=e,this.explicitSelection=!0,this.emit("selection-change",this.#Zi()),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&&Jt(e.column))return;if(!this.isCellSelectable(e.rowIndex,e.colIndex))return;if(e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const t=e.rowIndex,i=e.colIndex,n=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&!1!==this.config.multiSelect,r={startRow:t,startCol:i,endRow:t,endCol:i};return!n&&1===this.ranges.length&&nn(this.ranges[0],r)?(this.cellAnchor={row:t,col:i},!0):(this.cellAnchor={row:t,col:i},n||(this.ranges=[]),this.ranges.push(r),this.activeRange=r,this.emit("selection-change",this.#Zi()),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&&Jt(i)){const e=this.visibleColumns.findIndex(e=>!Jt(e));e>=0&&(t=e)}const n=tn(this.cellAnchor,{row:e.rowIndex,col:t}),r=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return r&&nn(r,n)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=n:this.ranges.push(n),this.activeRange=n,this.emit("selection-change",this.#Zi()),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===rn))return e;const t=this.#Qi(),i=e.findIndex(Qt),n=i>=0?i+1:0;return[...e.slice(0,n),t,...e.slice(n)]}return e}#Qi(){return{field:rn,header:"",width:32,resizable:!1,sortable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0,checkboxColumn:!0},headerRenderer:()=>{const e=document.createElement("div");if(e.className="tbw-checkbox-header",!1===this.config.multiSelect)return e;const t=document.createElement("input");return t.type="checkbox",t.className="tbw-select-all-checkbox",t.addEventListener("click",e=>{e.stopPropagation(),e.target.checked?this.selectAll():this.clearSelection()}),e.appendChild(t),e},renderer:e=>{const t=document.createElement("input");t.type="checkbox",t.className="tbw-select-row-checkbox";const i=e.cellEl;if(i){const e=parseInt(i.getAttribute("data-row")??"-1",10);e>=0&&(t.checked=this.selected.has(e))}return t}}}#Ji(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const t=e.closest(".cell"),i=t?T(t):-1;i>=0&&(e.checked=this.selected.has(i))});const t=e.querySelector(".tbw-select-all-checkbox");if(t){const e=this.rows.length;let i=0;if(this.config.isSelectable)for(let t=0;t<e;t++)this.isRowSelectable(t)&&i++;else i=e;const n=i>0&&this.selected.size>=i,r=this.selected.size>0;t.checked=n,t.indeterminate=r&&!n}}#en(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.#Zi()))))}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.#Zi()))}}}#tn(){const e=this.gridElement;if(!e)return;const{mode:t}=this.config,i=!!this.config.isSelectable;e.querySelectorAll(".cell").forEach(e=>{e.classList.remove("selected","top","bottom","first","last"),i&&e.removeAttribute("data-selectable")});const n=e.querySelectorAll(".data-grid-row");if(n.forEach(e=>{e.classList.remove("selected","row-focus"),i&&e.removeAttribute("data-selectable")}),"row"===t&&(L(e),n.forEach(e=>{const t=T(e.querySelector(".cell[data-row]"));t>=0&&(i&&!this.isRowSelectable(t)&&e.setAttribute("data-selectable","false"),this.selected.has(t)&&e.classList.add("selected","row-focus"))}),this.config.checkbox&&this.#Ji(e)),("cell"===t||"range"===t)&&i){e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),i=parseInt(e.getAttribute("data-col")??"-1",10);t>=0&&i>=0&&(this.isCellSelectable(t,i)||e.setAttribute("data-selectable","false"))})}if("range"===t&&this.ranges.length>0){L(e);const t=this.ranges.map(Xi),i=(e,i)=>{for(const n of t)if(e>=n.startRow&&e<=n.endRow&&i>=n.startCol&&i<=n.endCol)return!0;return!1};e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),n=parseInt(e.getAttribute("data-col")??"-1",10);if(t>=0&&n>=0){const r=this.visibleColumns[n];if(r&&Jt(r))return;i(t,n)&&(e.classList.add("selected"),i(t-1,n)||e.classList.add("top"),i(t+1,n)||e.classList.add("bottom"),i(t,n-1)||e.classList.add("first"),i(t,n+1)||e.classList.add("last"))}})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.children[0],{mode:i}=this.config;if(this.pendingKeyboardUpdate&&"range"===i){const{shiftKey:e}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const t=this.grid._focusRow,i=this.grid._focusCol;if(e&&this.cellAnchor){const e=tn(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.#Zi())}this.#en(i),this.grid.setAttribute("data-selection-mode",i),t&&t.classList.toggle("selecting",this.isDragging),this.#tn()}onScrollRender(){this.isSelectionEnabled()&&this.#tn()}getSelection(){return{mode:this.config.mode,ranges:this.#Zi().ranges,anchor:this.cellAnchor}}getSelectedCells(){return function(e){const t=new Map;for(const i of e)for(const e of en(i))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return Ji(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.#Zi()),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.#Zi()),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.#Zi()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const{mode:e}=this.config,t=this.rows;if("row"===e)return this.getSelectedRowIndices().filter(e=>e>=0&&e<t.length).map(e=>t[e]);if("cell"===e&&this.selectedCell){const{row:e}=this.selectedCell;return e>=0&&e<t.length?[t[e]]:[]}if("range"===e&&this.ranges.length>0){const e=new Set;for(const i of this.ranges){const n=Math.max(0,Math.min(i.startRow,i.endRow)),r=Math.min(t.length-1,Math.max(i.startRow,i.endRow));for(let t=n;t<=r;t++)e.add(t)}return[...e].sort((e,t)=>e-t).map(e=>t[e])}return[]}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.emit("selection-change",{mode:this.config.mode,ranges:[]}),this.requestAfterRender()}setRanges(e){this.ranges=e.map(e=>({startRow:e.from.row,startCol:e.from.col,endRow:e.to.row,endCol:e.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",{mode:this.config.mode,ranges:Qi(this.ranges)}),this.requestAfterRender()}#Zi(){return function(e,t,i){if("cell"===e&&t.selectedCell)return{mode:e,ranges:[{from:{row:t.selectedCell.row,col:t.selectedCell.col},to:{row:t.selectedCell.row,col:t.selectedCell.col}}]};if("row"===e&&t.selected.size>0){const n=[...t.selected].sort((e,t)=>e-t),r=[];let o=n[0],s=o;for(let e=1;e<n.length;e++)n[e]===s+1?s=n[e]:(r.push({from:{row:o,col:0},to:{row:s,col:i-1}}),o=n[e],s=o);return r.push({from:{row:o,col:0},to:{row:s,col:i-1}}),{mode:e,ranges:r}}return"range"===e&&t.ranges.length>0?{mode:e,ranges:Qi(t.ranges)}:{mode:e,ranges:[]}}(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}},e.ServerSidePlugin=class extends rt{name="serverSide";get defaultConfig(){return{pageSize:100,cacheBlockSize:100,maxConcurrentRequests:2}}dataSource=null;totalRowCount=0;loadedBlocks=new Map;loadingBlocks=new Set;lastRequestId=0;scrollDebounceTimer;detach(){this.dataSource=null,this.totalRowCount=0,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.lastRequestId=0,this.scrollDebounceTimer&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=void 0)}loadRequiredBlocks(){if(!this.dataSource)return;const e=this.grid,t=this.config.cacheBlockSize??100,i={startRow:e._virtualization.start,endRow:e._virtualization.end},n=function(e,t,i){const n=on(e,i),r=on(t-1,i),o=[];for(let s=n;s<=r;s++)o.push(s);return o}(i.startRow,i.endRow,t);for(const r of n)if(!this.loadedBlocks.has(r)&&!this.loadingBlocks.has(r)){if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2))break;this.loadingBlocks.add(r),sn(this.dataSource,r,t,{}).then(e=>{this.loadedBlocks.set(r,e.rows),this.totalRowCount=e.totalRowCount,this.loadingBlocks.delete(r),this.requestRender(),this.loadRequiredBlocks()}).catch(()=>{this.loadingBlocks.delete(r)})}}processRows(e){if(!this.dataSource)return[...e];const t=[];for(let i=0;i<this.totalRowCount;i++){const e=ln(i,this.config.cacheBlockSize??100,this.loadedBlocks);t.push(e??{__loading:!0,__index:i})}return t}onScroll(e){this.dataSource&&(this.loadRequiredBlocks(),this.scrollDebounceTimer&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.loadRequiredBlocks()},100))}setDataSource(e){this.dataSource=e,this.loadedBlocks.clear(),this.loadingBlocks.clear();sn(e,0,this.config.cacheBlockSize??100,{}).then(e=>{this.loadedBlocks.set(0,e.rows),this.totalRowCount=e.totalRowCount,this.requestRender()})}refresh(){this.dataSource&&(this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.requestRender())}purgeCache(){this.loadedBlocks.clear()}getTotalRowCount(){return this.totalRowCount}isRowLoaded(e){const t=on(e,this.config.cacheBlockSize??100);return this.loadedBlocks.has(t)}getLoadedBlockCount(){return this.loadedBlocks.size}},e.TreePlugin=class extends rt{static manifest={events:[{type:"tree-state-change",description:"Emitted when tree expansion state changes (toggle, expand all, collapse all)"}],queries:[{type:"canMoveRow",description:"Returns false for rows with children (parent nodes cannot be reordered)"}]};name="tree";styles="@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-inline-end:none!important;padding:0;display:flex;align-items:center;justify-content:flex-start}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1 / 3}tbw-grid .tree-cell-wrapper{display:inline-flex;align-items:center;padding-inline-start:calc(var(--tbw-tree-depth, 0) * var(--tbw-tree-indent-width, var(--tbw-tree-toggle-size, 1.25em)))}tbw-grid .tree-expander{display:flex;align-items:center;justify-content:flex-start;width:100%;height:100%;box-sizing:border-box}tbw-grid .tree-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-tree-toggle-size, 1.25em);height:var(--tbw-tree-toggle-size, 1.25em);flex-shrink:0}tbw-grid .tree-toggle:hover{color:var(--tbw-tree-accent, var(--tbw-color-accent))}tbw-grid .tree-spacer{width:var(--tbw-tree-toggle-size, 1.25em);display:inline-block;flex-shrink:0}tbw-grid .data-grid-row.tbw-tree-slide-in{animation:tbw-tree-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .data-grid-row.tbw-tree-fade-in{animation:tbw-tree-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-tree-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}@keyframes tbw-tree-fade-in{0%{opacity:0}to{opacity:1}}}";get defaultConfig(){return{childrenField:"children",autoDetect:!0,defaultExpanded:!1,indentWidth:20,showExpandIcons:!0,animation:"slide"}}expandedKeys=new Set;initialExpansionDone=!1;flattenedRows=[];rowKeyMap=new Map;previousVisibleKeys=new Set;keysToAnimate=new Set;sortState=null;detach(){this.expandedKeys.clear(),this.initialExpansionDone=!1,this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.sortState=null}handleQuery(e){if("canMoveRow"===e.type){const t=e.context,i=this.config.childrenField??"children",n=t?.[i];if(Array.isArray(n)&&n.length>0)return!1}}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detect(e){if(!this.config.autoDetect)return!1;const t=e,i=this.config.childrenField??function(e){if(!Array.isArray(e)||0===e.length)return null;const t=["children","items","nodes","subRows","nested"];for(const i of e)if(i&&"object"==typeof i)for(const e of t){const t=i[e];if(Array.isArray(t)&&t.length>0)return e}return null}(t)??"children";return gn(t,i)}processRows(e){const t=e;if(!gn(t,this.config.childrenField??"children"))return this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),[...e];let i=this.withStableKeys(t);this.sortState&&(i=this.sortTree(i,this.sortState.field,this.sortState.direction)),this.config.defaultExpanded&&!this.initialExpansionDone&&(this.expandedKeys=cn(i,this.config),this.initialExpansionDone=!0),this.flattenedRows=this.flattenTree(i,this.expandedKeys),this.rowKeyMap.clear(),this.keysToAnimate.clear();const n=new Set;for(const r of this.flattenedRows)this.rowKeyMap.set(r.key,r),n.add(r.key),!this.previousVisibleKeys.has(r.key)&&r.depth>0&&this.keysToAnimate.add(r.key);return this.previousVisibleKeys=n,this.flattenedRows.map(e=>({...e.data,__treeKey:e.key,__treeDepth:e.depth,__treeHasChildren:e.hasChildren,__treeExpanded:e.isExpanded}))}withStableKeys(e,t=null){const i=this.config.childrenField??"children";return e.map((e,n)=>{const r=e.__stableKey,o=void 0!==e.id?String(e.id):r??(t?`${t}-${n}`:String(n)),s=e[i],l=Array.isArray(s)&&s.length>0;return{...e,__stableKey:o,...l?{[i]:this.withStableKeys(s,o)}:{}}})}flattenTree(e,t,i=0){const n=this.config.childrenField??"children",r=[];for(const o of e){const e=o.__stableKey??String(o.id??"?"),s=o[n],l=Array.isArray(s)&&s.length>0,a=t.has(e);r.push({key:e,data:o,depth:i,hasChildren:l,isExpanded:a,parentKey:i>0&&e.substring(0,e.lastIndexOf("-"))||null}),l&&a&&r.push(...this.flattenTree(s,t,i+1))}return r}sortTree(e,t,i){const n=this.config.childrenField??"children";return[...e].sort((e,n)=>{const r=e[t],o=n[t];return null==r&&null==o?0:null==r?-1:null==o?1:r>o?i:r<o?-i:0}).map(e=>{const r=e[n];return Array.isArray(r)&&r.length>0?{...e,[n]:this.sortTree(r,t,i)}:e})}processColumns(e){if(0===this.flattenedRows.length)return[...e];const t=[...e];if(0===t.length)return t;const i=t[0],n=i.viewRenderer,r=()=>this.config,o=this.setIcon.bind(this),s=this.resolveIcon.bind(this);return t[0]={...i,viewRenderer:e=>{const{row:t,value:i}=e,{showExpandIcons:l=!0,indentWidth:a}=r(),d=t,c=d.__treeDepth??0,h=document.createElement("span");if(h.className="tree-cell-wrapper",h.style.setProperty("--tbw-tree-depth",String(c)),void 0!==a&&h.style.setProperty("--tbw-tree-indent-width",`${a}px`),l)if(d.__treeHasChildren){const e=document.createElement("span");e.className="tree-toggle"+(d.__treeExpanded?" expanded":""),o(e,s(d.__treeExpanded?"collapse":"expand")),e.setAttribute("data-tree-key",String(d.__treeKey??"")),h.appendChild(e)}else{const e=document.createElement("span");e.className="tree-spacer",h.appendChild(e)}const u=document.createElement("span");if(u.className="tree-content",n){const t=n(e);t instanceof Node?u.appendChild(t):"string"==typeof t&&(u.innerHTML=t)}else u.textContent=null!=i?String(i):"";return h.appendChild(u),h}},t}onCellClick(e){const t=e.originalEvent?.target;if(!t?.classList.contains("tree-toggle"))return!1;const i=t.getAttribute("data-tree-key");if(!i)return!1;const n=this.rowKeyMap.get(i);return!!n&&(this.expandedKeys=dn(this.expandedKeys,i),this.emit("tree-expand",{key:i,row:n.data,expanded:this.expandedKeys.has(i),depth:n.depth}),this.requestRender(),!0)}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusRow,i=this.flattenedRows[t];return i?.hasChildren?(e.preventDefault(),this.expandedKeys=dn(this.expandedKeys,i.key),this.emit("tree-expand",{key:i.key,row:i.data,expanded:this.expandedKeys.has(i.key),depth:i.depth}),this.requestRenderWithFocus(),!0):void 0}onHeaderClick(e){if(0===this.flattenedRows.length||!e.column.sortable)return!1;const{field:t}=e.column;this.sortState&&this.sortState.field===t?1===this.sortState.direction?this.sortState={field:t,direction:-1}:this.sortState=null:this.sortState={field:t,direction:1};const i=this.grid;return void 0!==i._sortState&&(i._sortState=this.sortState?{...this.sortState}:null),this.emit("sort-change",{field:t,direction:this.sortState?.direction??0}),this.requestRender(),!0}afterRender(){const e=this.animationStyle;if(!1===e||0===this.keysToAnimate.size)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const i="fade"===e?"tbw-tree-fade-in":"tbw-tree-slide-in";for(const n of t.querySelectorAll(".data-grid-row")){const e=n.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,r=this.flattenedRows[t]?.key;r&&this.keysToAnimate.has(r)&&(n.classList.add(i),n.addEventListener("animationend",()=>n.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}expand(e){this.expandedKeys.add(e),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}toggle(e){this.expandedKeys=dn(this.expandedKeys,e),this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}expandAll(){this.expandedKeys=cn(this.rows,this.config),this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("tree-state-change",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}getExpandedKeys(){return[...this.expandedKeys]}getFlattenedRows(){return[...this.flattenedRows]}getRowByKey(e){return this.rowKeyMap.get(e)?.data}expandToKey(e){this.expandedKeys=un(this.rows,e,this.config,this.expandedKeys),this.requestRender()}},e.UndoRedoPlugin=class extends rt{static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];#in=!1;#nn=null;#rn(e,t){const i=this.rows[e.rowIndex];if(i){try{const n=this.grid.getRowId(i);if(n)return void this.grid.updateRow(n,{[e.field]:t})}catch{}i[e.field]=t}}#on(e){const t=this.grid,i=t._visibleColumns?.findIndex(t=>t.field===e.field)??-1;if(i<0)return;t._focusRow=e.rowIndex,t._focusCol=i;const n=t.findRenderedRowElement?.(e.rowIndex);if(!n)return;const r=n.querySelector(`.cell[data-col="${i}"]`);if(r?.classList.contains("editing")){const e=r.querySelector(D);e?.focus({preventScroll:!0})}}#sn(e,t){if(this.#in=!0,"compound"===e.type){const i="undo"===t?[...e.actions].reverse():e.actions;for(const e of i)this.#rn(e,"undo"===t?e.oldValue:e.newValue)}else this.#rn(e,"undo"===t?e.oldValue:e.newValue);this.#in=!1}#ln(e){const t="compound"===e.type?e.actions[e.actions.length-1]:e;t&&this.#on(t)}attach(e){super.attach(e),this.on("cell-edit-committed",e=>{this.#in||this.recordEdit(e.rowIndex,e.field,e.oldValue,e.newValue)})}detach(){this.undoStack=[],this.redoStack=[],this.#nn=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=fn({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#sn(t.action,"undo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.emit("undo",{action:t.action,type:"undo"}),this.#ln(t.action),this.requestRenderWithFocus()),!0}if(i){e.preventDefault();const t=wn({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#sn(t.action,"redo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.emit("redo",{action:t.action,type:"redo"}),this.#ln(t.action),this.requestRenderWithFocus()),!0}return!1}recordEdit(e,t,i,n){const r=function(e,t,i,n){return{type:"cell-edit",rowIndex:e,field:t,oldValue:i,newValue:n,timestamp:Date.now()}}(e,t,i,n);if(this.#nn)return void this.#nn.push(r);const o=pn({undoStack:this.undoStack,redoStack:this.redoStack},r,this.config.maxHistorySize??100);this.undoStack=o.undoStack,this.redoStack=o.redoStack}beginTransaction(){if(this.#nn)throw new Error("UndoRedoPlugin: Transaction already in progress. Call endTransaction() first.");this.#nn=[]}endTransaction(){const e=this.#nn;if(!e)throw new Error("UndoRedoPlugin: No transaction in progress. Call beginTransaction() first.");if(this.#nn=null,0===e.length)return;const t=1===e.length?e[0]:{type:"compound",actions:e,timestamp:Date.now()};const i=pn({undoStack:this.undoStack,redoStack:this.redoStack},t,this.config.maxHistorySize??100);this.undoStack=i.undoStack,this.redoStack=i.redoStack}undo(){const e=fn({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#sn(e.action,"undo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.#ln(e.action),this.requestRenderWithFocus()),e.action}redo(){const e=wn({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#sn(e.action,"redo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.#ln(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.#nn=null}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}},e.VisibilityPlugin=bn,e.builtInSort=Q,e.createGrid=function(e){const t=document.createElement("tbw-grid");return e&&(t.gridConfig=e),t},e.defaultComparator=Z,e.defaultEditorFor=Pt,e.defaultPasteHandler=ut,e.getUniqueValuesBatch=Xt,e.printGridIsolated=Ki,e.queryGrid=function(e,t=document){return t.querySelector(e)},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=grid.all.umd.js.map