@toolbox-web/grid 0.2.7 → 0.2.8

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.
@@ -1,4 +1,4 @@
1
- (function(C,J){typeof exports=="object"&&typeof module<"u"?J(exports):typeof define=="function"&&define.amd?define(["exports"],J):(C=typeof globalThis<"u"?globalThis:C||self,J(C.TbwGrid={}))})(this,(function(C){"use strict";const J=':root{color-scheme:light dark}:host{--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-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, #adacac);--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: inherit;--tbw-font-size-header: var(--tbw-font-size);--tbw-font-weight-header: bold;--tbw-cell-padding-header: 2px 8px;--tbw-cell-padding: 2px 8px;--tbw-cell-padding-input: 2px 6px;--tbw-row-height: 28px;--tbw-header-height: 30px;--tbw-cell-white-space: nowrap;--tbw-border-radius: 4px;--tbw-border-input: 1px solid var(--tbw-color-border-strong);--tbw-border-header: 1px solid var(--tbw-color-border-header);--tbw-row-divider: 1px solid 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: 2px solid 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: 6px;--tbw-resize-handle-color: transparent;--tbw-resize-handle-color-hover: var(--tbw-color-accent);--tbw-resize-handle-border-radius: 0;--tbw-scrollbar-thumb: var(--tbw-color-border-strong);--tbw-scrollbar-track: var(--tbw-color-bg);--tbw-transition-duration: .12s;--tbw-transition-ease: ease;--tbw-animation-duration: .2s;--tbw-animation-easing: ease-out;--tbw-animation-enabled: 1;--tbw-editing-bg: var(--tbw-color-selection);--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-sort-indicator-color: var(--tbw-color-fg-muted);--tbw-sort-indicator-active-color: var(--tbw-color-accent);--tbw-header-text-transform: none;--tbw-header-letter-spacing: normal;--tbw-color-header-separator: var(--tbw-color-border-cell);--tbw-checkbox-size: 16px;--tbw-density-scale: 1}:host{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);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}:host,:host *{box-sizing:border-box}:host .header{display:block;flex-shrink:0;z-index:var(--tbw-z-layer-header, 30);background:var(--tbw-color-header-bg);overflow:visible}:host .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)}:host .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))}:host .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)}:host .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:hidden;min-width:0}:host .header-row>.cell>span:first-child{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}:host .header-row>.cell>span[part~=sort-indicator]{flex-shrink:0;opacity:.6}:host .header-row>.cell:last-child{border-right:0}:host .header-group-cell:not(:last-child),:host .header-row>.cell.grouped.group-end:not(:last-child){border-right:2px solid var(--tbw-color-border)}:host .tbw-grid-root{display:flex;flex-direction:column;height:100%}:host .rows-body-wrapper{flex:1;min-height:0;display:flex;flex-direction:row;width:100%;min-width:fit-content}:host .rows-body{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:visible}:host .rows-container{display:flex;flex-direction:row;flex:1;min-height:0;overflow:visible}:host .rows-viewport{flex:1;min-width:0;position:relative;display:block;overflow:clip}:host .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)}:host .faux-vscroll-spacer{width:1px}:host .rows-viewport .rows{position:absolute;top:0;left:0;min-width:100%;will-change:transform;z-index:var(--tbw-z-layer-rows, 1)}:host .data-grid-row{display:grid;grid-template-columns:var(--tbw-column-template);contain:layout style}:host .data-grid-row:has(.editing){background:var(--tbw-editing-bg)}:host .selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}:host .data-grid-row>.cell.selected:focus-visible,:host .data-grid-row>.cell:focus-visible:not(.cell-focus){outline:none}:host .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);line-height:calc(var(--tbw-row-height) - 5px);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}:host .data-grid-row>.cell>*{overflow:hidden;text-overflow:ellipsis;white-space:inherit;min-width:0}:host .data-grid-row>.cell:last-child{border-right:0}:host .data-grid-row>.cell[data-type=boolean]{text-align:center}:host .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}:host .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex}:host .data-grid-row>.cell.editing input:not([type=checkbox]),:host .data-grid-row>.cell.editing select,:host .data-grid-row>.cell.editing textarea{width:100%;height:100%;max-width: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)}:host .data-grid-row:nth-child(2n){background:var(--tbw-color-row-alt)}:host .data-grid-row:hover{background:var(--tbw-color-row-hover)}:host .sortable{cursor:pointer;-webkit-user-select:none;user-select:none}:host .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)}:host .resize-handle:hover{background:var(--tbw-resize-handle-color-hover)}:host .cell-focus,:host .row-focus{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}:host .group-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-color-row-alt);font-weight:500;border-bottom:var(--tbw-row-divider);min-height:var(--tbw-row-height)}:host .group-row .cell{display:flex;align-items:center;padding:var(--tbw-cell-padding, 2px 8px)}:host .group-row .group-toggle{background:none;border:0;cursor:pointer;padding:0 4px 0 0;font:inherit}:host .group-row .group-count{margin-left:4px;opacity:.7}:host .sticky-left,:host .sticky-right{position:sticky;z-index:25}:host .header-row>.cell.sticky-left,:host .header-row>.cell.sticky-right{background:var(--tbw-color-header-bg);z-index:35}:host .data-grid-row>.cell.sticky-left,:host .data-grid-row>.cell.sticky-right{background:var(--tbw-color-panel-bg)}:host .sticky-left{box-shadow:1px 0 0 var(--tbw-color-border)}:host .sticky-right{box-shadow:-1px 0 0 var(--tbw-color-border)}.grid-container{position:relative;width:100%;height:100%}.grid-placeholder{padding:2rem;text-align:center;color:var(--tbw-color-fg);opacity:.6}:host{--tbw-shell-header-height: 44px;--tbw-shell-header-bg: var(--tbw-color-panel-bg);--tbw-shell-header-border: var(--tbw-color-border);--tbw-shell-title-font-size: 14px;--tbw-shell-title-font-weight: 600;--tbw-tool-panel-width: 280px;--tbw-tool-panel-bg: var(--tbw-color-panel-bg);--tbw-tool-panel-border: var(--tbw-color-border);--tbw-tool-panel-header-height: 40px;--tbw-tool-panel-transition: var(--tbw-animation-duration) var(--tbw-animation-easing);--tbw-toolbar-button-size: 32px;--tbw-toolbar-button-gap: 4px}:host .tbw-grid-root.has-shell{display:flex;flex-direction:column;height:100%}:host .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}:host .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}:host .tbw-shell-content{flex:1;display:flex;align-items:center;gap:12px;min-width:0;overflow:hidden}:host .tbw-shell-toolbar{display:flex;align-items:center;gap:var(--tbw-toolbar-button-gap);flex-shrink:0}:host .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)}:host .tbw-toolbar-btn:hover{background:var(--tbw-color-row-hover)}:host .tbw-toolbar-btn:focus-visible{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}:host .tbw-toolbar-btn.active{background:var(--tbw-focus-background);border-color:var(--tbw-color-accent)}:host .tbw-toolbar-btn:disabled{opacity:.5;cursor:not-allowed}:host .tbw-toolbar-separator{width:1px;height:20px;background:var(--tbw-color-border);margin:0 4px}:host .tbw-shell-body{position:relative;display:flex;flex:1;min-height:0;overflow:visible}:host .tbw-grid-content{flex:1;min-width:0;min-height:0;display:flex;flex-direction:row;overflow:hidden}:host .tbw-scroll-area{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow-x:auto;overflow-y:hidden}:host .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)}:host .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)}:host .tbw-tool-panel.open{width:var(--tbw-tool-panel-width)}:host .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)}:host .tbw-tool-panel-resize[data-handle-position=left]{left:0}:host .tbw-tool-panel-resize[data-handle-position=right]{right:0}:host .tbw-tool-panel-resize:hover,:host .tbw-tool-panel-resize.resizing{background:var(--tbw-color-accent)}:host .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}:host .tbw-tool-panel-title{font-weight:600;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}:host .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}:host .tbw-tool-panel-close:hover{background:var(--tbw-color-row-hover);color:var(--tbw-color-fg)}:host .tbw-tool-panel-content{flex:1;overflow:auto}:host .tbw-accordion{display:flex;flex-direction:column;gap:0}:host .tbw-accordion-section{border-bottom:1px solid var(--tbw-tool-panel-border)}:host .tbw-accordion-section:last-child{border-bottom:none}:host .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:left;cursor:pointer;-webkit-user-select:none;user-select:none}:host .tbw-accordion-header:hover{background:var(--tbw-color-row-hover)}:host .tbw-accordion-section.single .tbw-accordion-header{cursor:default}:host .tbw-accordion-section.single .tbw-accordion-header:hover{background:transparent}:host .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}:host .tbw-accordion-section.expanded .tbw-accordion-chevron{transform:rotate(90deg)}:host .tbw-accordion-icon{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;font-size:14px;flex-shrink:0}:host .tbw-accordion-title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}:host .tbw-accordion-content{display:none}:host .tbw-accordion-section.expanded .tbw-accordion-content{display:block}:host .tbw-quick-filter-input{flex:1;max-width:300px;height:28px;padding:0 8px;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:13px}:host .tbw-quick-filter-input:focus{outline:none;border-color:var(--tbw-color-accent)}:host .tbw-selection-summary{font-size:13px;color:var(--tbw-color-fg-muted);white-space:nowrap}@media(prefers-reduced-motion:reduce){:host([data-animation-mode="reduced-motion"]){--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}}:host([data-animation-mode="off"]){--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}:host .tbw-expanding{animation:tbw-expand var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}:host .tbw-collapsing{animation:tbw-collapse var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}@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)}}:host .tbw-fade-in{animation:tbw-fade-in var(--tbw-animation-duration) var(--tbw-animation-easing) forwards}:host .tbw-fade-out{animation:tbw-fade-out var(--tbw-animation-duration) var(--tbw-animation-easing) forwards}@keyframes tbw-fade-in{0%{opacity:0}to{opacity:1}}@keyframes tbw-fade-out{0%{opacity:1}to{opacity:0}}:host .tbw-flip-animating{will-change:transform;z-index:1}:host .tbw-toggle-icon{display:inline-flex;align-items:center;justify-content:center;transition:transform var(--tbw-animation-duration) var(--tbw-animation-easing)}:host .tbw-toggle-icon.tbw-expanded{transform:rotate(90deg)}';function Mt(o){const e=new Map;return o._sortState&&e.set(o._sortState.field,{direction:o._sortState.direction===1?"asc":"desc",priority:0}),e}function He(o,e){const t=o._columns,n=Mt(o);return{columns:t.map((i,r)=>{const s={field:i.field,order:r,visible:!0},l=i;l.__renderedWidth!==void 0?s.width=l.__renderedWidth:i.width!==void 0&&(s.width=typeof i.width=="string"?parseFloat(i.width):i.width);const a=n.get(i.field);a&&(s.sort=a);for(const c of e)if(c.getColumnState){const d=c.getColumnState(i.field);d&&Object.assign(s,d)}return s})}}function It(o,e,t,n){if(!e.columns||e.columns.length===0)return;const i=new Map(e.columns.map(l=>[l.field,l])),r=t.map(l=>{const a=i.get(l.field);if(!a)return l;const c={...l};return a.width!==void 0&&(c.width=a.width,c.__renderedWidth=a.width),a.visible!==void 0&&(c.hidden=!a.visible),c});r.sort((l,a)=>{const c=i.get(l.field)?.order??1/0,d=i.get(a.field)?.order??1/0;return c-d}),o._columns=r;const s=e.columns.filter(l=>l.sort!==void 0).sort((l,a)=>(l.sort?.priority??0)-(a.sort?.priority??0));if(s.length>0){const l=s[0];l.sort&&(o._sortState={field:l.field,direction:l.sort.direction==="asc"?1:-1})}else o._sortState=null;for(const l of n)if(l.applyColumnState)for(const a of e.columns)l.applyColumnState(a.field,a)}function Ht(o,e,t){let n=null;return()=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{n=null;const i=He(o,e());t(i)},100)}}const $={STRETCH:"stretch",FIXED:"fixed"},Ne={mode:"reduced-motion",duration:200,easing:"ease-out"},I={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰"};function Nt(o){return o==null?"string":typeof o=="number"?"number":typeof o=="boolean"?"boolean":o instanceof Date||typeof o=="string"&&/\d{4}-\d{2}-\d{2}/.test(o)&&!isNaN(Date.parse(o))?"date":"string"}function Oe(o,e){if(e&&e.length){const r={};return e.forEach(s=>{s.type&&(r[s.field]=s.type)}),{columns:e,typeMap:r}}const t=o[0]||{},n=Object.keys(t).map(r=>{const s=t[r],l=Nt(s);return{field:r,header:r.charAt(0).toUpperCase()+r.slice(1),type:l}}),i={};return n.forEach(r=>{i[r.field]=r.type||"string"}),{columns:n,typeMap:i}}const Ot=/{{\s*([^}]+)\s*}}/g,H="__DG_EMPTY__",Dt=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,zt=/__(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/,Ft=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"]),De=/^on\w+$/i,qt=new Set(["href","src","action","formaction","data","srcdoc","xlink:href","poster","srcset"]),Bt=/^\s*(javascript|vbscript|data|blob):/i;function ie(o){if(!o||typeof o!="string")return"";if(o.indexOf("<")===-1)return o;const e=document.createElement("template");return e.innerHTML=o,Kt(e.content),e.innerHTML}function Kt(o){const e=[],t=o.querySelectorAll("*");for(const n of t){const i=n.tagName.toLowerCase();if(Ft.has(i)){e.push(n);continue}if((i==="svg"||n.namespaceURI==="http://www.w3.org/2000/svg")&&Array.from(n.attributes).some(l=>De.test(l.name)||l.name==="href"||l.name==="xlink:href")){e.push(n);continue}const r=[];for(const s of n.attributes){const l=s.name.toLowerCase();if(De.test(l)){r.push(s.name);continue}if(qt.has(l)&&Bt.test(s.value)){r.push(s.name);continue}if(l==="style"&&/expression\s*\(|javascript:|behavior\s*:/i.test(s.value)){r.push(s.name);continue}}r.forEach(s=>n.removeAttribute(s))}e.forEach(n=>n.remove())}function ze(o,e){if(!o||o.indexOf("{{")===-1)return o;const t=[],n=o.replace(Ot,(l,a)=>{const c=Vt(a,e);return t.push({expr:a.trim(),result:c}),c}),i=$t(n),r=t.length&&t.every(l=>l.result===""||l.result===H);return/Reflect\.|\bProxy\b|ownKeys\(/.test(o)||r?"":i}function Vt(o,e){if(o=(o||"").trim(),!o||/\b(Reflect|Proxy|ownKeys)\b/.test(o))return H;if(o==="value")return e.value==null?H:String(e.value);if(o.startsWith("row.")&&!/[()?]/.test(o)&&!o.includes(":")){const n=o.slice(4),i=e.row?e.row[n]:void 0;return i==null?H:String(i)}if(o.length>80||!Dt.test(o)||zt.test(o))return H;const t=o.match(/\./g);if(t&&t.length>1)return H;try{const i=new Function("value","row",`return (${o});`)(e.value,e.row),r=i==null?"":String(i);return/Reflect|Proxy|ownKeys/.test(r)?H:r||H}catch{return H}}function $t(o){return o&&o.replace(new RegExp(H,"g"),"").replace(/Reflect\.[^<>{}\s]+/g,"").replace(/\bProxy\b/g,"").replace(/ownKeys\([^)]*\)/g,"")}function Gt(o){if(/Reflect|Proxy|ownKeys/.test(o.textContent||"")){if(Array.from(o.childNodes).forEach(e=>{e.nodeType===Node.TEXT_NODE&&/Reflect|Proxy|ownKeys/.test(e.textContent||"")&&(e.textContent="")}),/Reflect|Proxy|ownKeys/.test(o.textContent||"")){if(/Reflect|Proxy|ownKeys/.test(o.textContent||""))for(;o.firstChild;)o.removeChild(o.firstChild);o.textContent=(o.textContent||"").replace(/Reflect|Proxy|ownKeys/g,"")}(o.textContent||"").trim().length===0&&(o.textContent="")}}function Fe(o){const e=/Reflect\.|\bProxy\b|ownKeys\(/.test(o),t=n=>e?"":ze(o,n);return t.__blocked=e,t}function Wt(o){return Array.from(o.querySelectorAll("tbw-grid-column")).map(t=>{const n=t.getAttribute("field")||"";if(!n)return null;const i=t.getAttribute("type")||void 0,s=i&&new Set(["number","string","date","boolean","select","typeahead"]).has(i)?i:void 0,l=t.getAttribute("header")||void 0,a=t.hasAttribute("sortable"),c=t.hasAttribute("editable"),d={field:n,type:s,header:l,sortable:a,editable:c};t.hasAttribute("resizable")&&(d.resizable=!0),t.hasAttribute("sizable")&&(d.resizable=!0);const u=t.getAttribute("options");u&&(d.options=u.split(",").map(g=>{const[w,y]=g.includes(":")?g.split(":"):[g.trim(),g.trim()];return{value:w.trim(),label:y?.trim()||w.trim()}}));const f=t.querySelector("tbw-grid-column-view"),h=t.querySelector("tbw-grid-column-editor"),p=t.querySelector("tbw-grid-column-header");return f&&(d.__viewTemplate=f),h&&(d.__editorTemplate=h),p&&(d.__headerTemplate=p),d}).filter(t=>!!t)}function Ut(o,e){if((!o||!o.length)&&(!e||!e.length))return[];if(!o||!o.length)return e||[];if(!e||!e.length)return o;const t={};e.forEach(i=>t[i.field]=i);const n=o.map(i=>{const r=t[i.field];if(!r)return i;const s={...i};return r.header&&!s.header&&(s.header=r.header),r.type&&!s.type&&(s.type=r.type),s.sortable=i.sortable||r.sortable,(i.resizable===!0||r.resizable===!0)&&(s.resizable=!0),s.editable=i.editable||r.editable,r.__viewTemplate&&(s.__viewTemplate=r.__viewTemplate),r.__editorTemplate&&(s.__editorTemplate=r.__editorTemplate),r.__headerTemplate&&(s.__headerTemplate=r.__headerTemplate),delete t[i.field],s});return Object.keys(t).forEach(i=>n.push(t[i])),n}function le(o,e){try{o.part?.add?.(e)}catch{}const t=o.getAttribute("part");t?t.split(/\s+/).includes(e)||o.setAttribute("part",t+" "+e):o.setAttribute("part",e)}function jt(o){o.__lightDomColumnsCache||(o.__originalColumnNodes=Array.from(o.querySelectorAll("tbw-grid-column")),o.__lightDomColumnsCache=o.__originalColumnNodes.length?Wt(o):[]);const e=o.__lightDomColumnsCache,t=Ut(o._columns,e);t.forEach(i=>{i.__viewTemplate&&!i.__compiledView&&(i.__compiledView=Fe(i.__viewTemplate.innerHTML)),i.__editorTemplate&&!i.__compiledEditor&&(i.__compiledEditor=Fe(i.__editorTemplate.innerHTML))});const{columns:n}=Oe(o._rows,t);o._columns=n}function qe(o){const e=o.effectiveConfig?.fitMode||o.fitMode||$.STRETCH;if(e!==$.STRETCH&&e!==$.FIXED||o.__didInitialAutoSize||!o.isConnected)return;const t=o._headerRowEl?.children||[];if(!t.length)return;let n=!1;o._visibleColumns.forEach((i,r)=>{if(i.width)return;const s=t[r];let l=s?s.scrollWidth:0;for(const a of o._rowPool){const c=a.children[r];if(c){const d=c.scrollWidth;d>l&&(l=d)}}l>0&&(i.width=l+2,i.__autoSized=!0,n=!0)}),n&&B(o),o.__didInitialAutoSize=!0}function B(o){(o.effectiveConfig?.fitMode||o.fitMode||$.STRETCH)===$.STRETCH?o._gridTemplate=o._visibleColumns.map(t=>{if(t.width)return`${t.width}px`;const n=t.minWidth;return n!=null?`minmax(${n}px, 1fr)`:"1fr"}).join(" ").trim():o._gridTemplate=o._visibleColumns.map(t=>t.width?`${t.width}px`:"max-content").join(" "),o.style.setProperty("--tbw-column-template",o._gridTemplate)}function Xt(o){switch(o.type){case"number":return e=>{const t=document.createElement("input");return t.type="number",t.value=e.value!=null?String(e.value):"",t.addEventListener("blur",()=>e.commit(t.value===""?null:Number(t.value))),t.addEventListener("keydown",n=>{n.key==="Enter"&&e.commit(t.value===""?null:Number(t.value)),n.key==="Escape"&&e.cancel()}),t.focus(),t};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.focus(),t};case"date":return e=>{const t=document.createElement("input");return t.type="date",e.value instanceof Date&&(t.valueAsDate=e.value),t.addEventListener("change",()=>e.commit(t.valueAsDate)),t.addEventListener("keydown",n=>{n.key==="Escape"&&e.cancel()}),t.focus(),t};case"select":case"typeahead":return e=>{const t=document.createElement("select");e.column.multi&&(t.multiple=!0),(typeof e.column.options=="function"?e.column.options():e.column.options||[]).forEach(r=>{const s=document.createElement("option");s.value=String(r.value),s.textContent=r.label,(e.column.multi&&Array.isArray(e.value)&&e.value.includes(r.value)||!e.column.multi&&e.value===r.value)&&(s.selected=!0),t.appendChild(s)});const i=()=>{if(e.column.multi){const r=[];Array.from(t.selectedOptions).forEach(s=>{r.push(s.value)}),e.commit(r)}else e.commit(t.value)};return t.addEventListener("change",i),t.addEventListener("blur",i),t.addEventListener("keydown",r=>{r.key==="Escape"&&e.cancel()}),t.focus(),t};default:return e=>{const t=document.createElement("input");return t.type="text",t.value=e.value!=null?String(e.value):"",t.addEventListener("blur",()=>e.commit(t.value)),t.addEventListener("keydown",n=>{n.key==="Enter"&&e.commit(t.value),n.key==="Escape"&&e.cancel()}),t.focus(),t}}}function Yt(o,e){if(o._dispatchKeyDown?.(e))return;const t=o._rows.length-1,n=o._visibleColumns.length-1,i=o._activeEditRows!==void 0&&o._activeEditRows!==-1,s=o._visibleColumns[o._focusCol]?.type,l=e.composedPath?e.composedPath():[],a=l&&l.length?l[0]:e.target,c=d=>{if(!d)return!1;const u=d.tagName;return!!(u==="INPUT"||u==="SELECT"||u==="TEXTAREA"||d.isContentEditable)};if(!(c(a)&&(e.key==="Home"||e.key==="End"))&&!(c(a)&&(e.key==="ArrowUp"||e.key==="ArrowDown")&&a.tagName==="INPUT"&&a.type==="number")&&!(c(a)&&(e.key==="ArrowLeft"||e.key==="ArrowRight"))&&!(c(a)&&(e.key==="Enter"||e.key==="Escape"))&&!(i&&(s==="select"||s==="typeahead")&&(e.key==="ArrowDown"||e.key==="ArrowUp"))){switch(e.key){case"Tab":{e.preventDefault(),!e.shiftKey?o._focusCol<n?o._focusCol+=1:(typeof o.commitActiveRowEdit=="function"&&o.commitActiveRowEdit(),o._focusRow<t&&(o._focusRow+=1,o._focusCol=0)):o._focusCol>0?o._focusCol-=1:o._focusRow>0&&(typeof o.commitActiveRowEdit=="function"&&o._activeEditRows===o._focusRow&&o.commitActiveRowEdit(),o._focusRow-=1,o._focusCol=n),D(o);return}case"ArrowDown":i&&typeof o.commitActiveRowEdit=="function"&&o.commitActiveRowEdit(),o._focusRow=Math.min(t,o._focusRow+1),e.preventDefault();break;case"ArrowUp":i&&typeof o.commitActiveRowEdit=="function"&&o.commitActiveRowEdit(),o._focusRow=Math.max(0,o._focusRow-1),e.preventDefault();break;case"ArrowRight":o._focusCol=Math.min(n,o._focusCol+1),e.preventDefault();break;case"ArrowLeft":o._focusCol=Math.max(0,o._focusCol-1),e.preventDefault();break;case"Home":(e.ctrlKey||e.metaKey)&&(i&&typeof o.commitActiveRowEdit=="function"&&o.commitActiveRowEdit(),o._focusRow=0),o._focusCol=0,e.preventDefault(),D(o,{forceScrollLeft:!0});return;case"End":(e.ctrlKey||e.metaKey)&&(i&&typeof o.commitActiveRowEdit=="function"&&o.commitActiveRowEdit(),o._focusRow=t),o._focusCol=n,e.preventDefault(),D(o,{forceScrollRight:!0});return;case"PageDown":o._focusRow=Math.min(t,o._focusRow+20),e.preventDefault();break;case"PageUp":o._focusRow=Math.max(0,o._focusRow-20),e.preventDefault();break;case"Enter":return typeof o.beginBulkEdit=="function"?o.beginBulkEdit(o._focusRow):o.dispatchEvent(new CustomEvent("activate-cell",{detail:{row:o._focusRow,col:o._focusCol}})),D(o);default:return}D(o)}}function D(o,e){if(o._virtualization?.enabled){const{rowHeight:s,container:l,viewportEl:a}=o._virtualization,c=l,d=a?.clientHeight??c?.clientHeight??0;if(c&&d>0){const u=o._focusRow*s;u<c.scrollTop?c.scrollTop=u:u+s>c.scrollTop+d&&(c.scrollTop=u-d+s)}}o._activeEditRows!==void 0&&o._activeEditRows!==-1||o.refreshVirtualWindow(!1),Array.from(o._bodyEl.querySelectorAll(".cell-focus")).forEach(s=>s.classList.remove("cell-focus")),Array.from(o._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(s=>{s.setAttribute("aria-selected","false")});const n=o._focusRow,i=o._virtualization.start??0,r=o._virtualization.end??o._rows.length;if(n>=i&&n<r){const s=o._bodyEl.querySelectorAll(".data-grid-row")[n-i],l=s?.children[o._focusCol];if(l){l.classList.add("cell-focus"),l.setAttribute("aria-selected","true");const a=o.shadowRoot?.querySelector(".tbw-scroll-area");if(a&&l)if(e?.forceScrollLeft)a.scrollLeft=0;else if(e?.forceScrollRight)a.scrollLeft=a.scrollWidth-a.clientWidth;else{const c=o._getHorizontalScrollOffsets?.(s??void 0,l)??{left:0,right:0};if(!c.skipScroll){const d=l.getBoundingClientRect(),u=a.getBoundingClientRect(),f=d.left-u.left+a.scrollLeft,h=f+d.width,p=a.scrollLeft+c.left,g=a.scrollLeft+a.clientWidth-c.right;f<p?a.scrollLeft=f-c.left:h>g&&(a.scrollLeft=h-a.clientWidth+c.right)}}if(o._activeEditRows!==void 0&&o._activeEditRows!==-1&&l.classList.contains("editing")){const c=l.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');if(c&&document.activeElement!==c)try{c.focus()}catch{}}else if(!l.contains(document.activeElement)){l.hasAttribute("tabindex")||l.setAttribute("tabindex","-1");try{l.focus({preventScroll:!0})}catch{}}}}}const Zt="__cellDisplayCache",Jt="__cellCacheEpoch";function ae(o){o[Zt]=void 0,o[Jt]=void 0,o.__hasSpecialColumns=void 0}function Qt(o,e,t,n,i){const r=Math.max(0,t-e),s=o._bodyEl,l=o._visibleColumns,a=l.length;let c=o.__cachedHeaderRowCount;for(c===void 0&&(c=o.shadowRoot?.querySelector(".header-group-row")?2:1,o.__cachedHeaderRowCount=c);o._rowPool.length<r;){const u=document.createElement("div");u.className="data-grid-row",u.setAttribute("role","row"),u.addEventListener("click",f=>Be(o,f,u,!1)),u.addEventListener("dblclick",f=>Be(o,f,u,!0)),o._rowPool.push(u)}if(o._rowPool.length>r){for(let u=r;u<o._rowPool.length;u++){const f=o._rowPool[u];f.parentNode===s&&f.remove()}o._rowPool.length=r}const d=i&&o.__hasRenderRowPlugins!==!1;for(let u=0;u<r;u++){const f=e+u,h=o._rows[f],p=o._rowPool[u];if(p.setAttribute("aria-rowindex",String(f+c+1)),d&&i(h,p,f)){p.__epoch=n,p.__rowDataRef=h,p.parentNode!==s&&s.appendChild(p);continue}const g=p.__epoch,w=p.__rowDataRef,y=p.children.length,T=g===n&&y===a,A=w!==h;let b=!1;if(T&&A){for(let E=0;E<a;E++)if(l[E].externalView&&!p.querySelector(`.cell[data-col="${E}"] [data-external-view]`)){b=!0;break}}if(!T||b){const E=p.querySelector(".cell.editing"),v=o._activeEditRows===f;if(E&&!v)p.__isCustomRow&&(p.className="data-grid-row",p.setAttribute("role","row"),p.__isCustomRow=!1),G(o,p,h,f),p.__epoch=n,p.__rowDataRef=h;else if(E&&v)ce(o,p,h,f),p.__rowDataRef=h;else if(p.__isCustomRow&&(p.className="data-grid-row",p.setAttribute("role","row"),p.__isCustomRow=!1),G(o,p,h,f),p.__epoch=n,p.__rowDataRef=h,v){const x=p.children;for(let _=0;_<x.length;_++){const k=o._visibleColumns[_];k&&k.editable&&O(o,h,f,k,x[_])}}}else if(A){const E=p.querySelector(".cell.editing"),v=o._activeEditRows===f;if(E&&!v)G(o,p,h,f),p.__epoch=n,p.__rowDataRef=h;else if(ce(o,p,h,f),p.__rowDataRef=h,v&&!E){const x=p.children;for(let _=0;_<x.length;_++){const k=o._visibleColumns[_];k&&k.editable&&O(o,h,f,k,x[_])}}}else{const E=p.querySelector(".cell.editing"),v=o._activeEditRows===f;if(E&&!v)G(o,p,h,f),p.__epoch=n,p.__rowDataRef=h;else if(ce(o,p,h,f),v&&!E){const x=p.children;for(let _=0;_<x.length;_++){const k=o._visibleColumns[_];k&&k.editable&&O(o,h,f,k,x[_])}}}const m=o._changedRowIndices.has(f),S=p.classList.contains("changed");m!==S&&p.classList.toggle("changed",m),p.parentNode!==s&&s.appendChild(p)}}function ce(o,e,t,n){const i=e.children,r=o._visibleColumns,s=r.length,l=i.length,a=s<l?s:l,c=o._focusRow,d=o._focusCol;let u=o.__hasSpecialColumns;if(u===void 0){u=!1;for(let h=0;h<s;h++){const p=r[h];if(p.__viewTemplate||p.__compiledView||p.viewRenderer||p.externalView||p.format||p.type==="date"||p.type==="boolean"){u=!0;break}}o.__hasSpecialColumns=u}const f=String(n);if(!u){for(let h=0;h<a;h++){const p=i[h],g=t[r[h].field];p.textContent=g==null?"":String(g),p.getAttribute("data-row")!==f&&p.setAttribute("data-row",f);const w=c===n&&d===h,y=p.classList.contains("cell-focus");w!==y&&(p.classList.toggle("cell-focus",w),p.setAttribute("aria-selected",String(w)))}return}for(let h=0;h<a;h++)if(r[h].externalView&&!i[h].querySelector("[data-external-view]")){G(o,e,t,n);return}for(let h=0;h<a;h++){const p=r[h],g=i[h];g.getAttribute("data-row")!==f&&g.setAttribute("data-row",f);const w=c===n&&d===h,y=g.classList.contains("cell-focus");if(w!==y&&(g.classList.toggle("cell-focus",w),g.setAttribute("aria-selected",String(w))),g.classList.contains("editing"))continue;if(p.viewRenderer){const A=t[p.field],b=p.viewRenderer({row:t,value:A,field:p.field,column:p});typeof b=="string"?g.innerHTML=ie(b):b?(g.innerHTML="",g.appendChild(b)):g.textContent=A==null?"":String(A);continue}if(p.__viewTemplate||p.__compiledView||p.externalView)continue;const R=t[p.field];let T;if(p.format)try{const A=p.format(R,t);T=A==null?"":String(A)}catch{T=R==null?"":String(R)}else if(p.type==="date"){if(R==null||R==="")T="";else if(R instanceof Date)T=isNaN(R.getTime())?"":R.toLocaleDateString();else{const A=new Date(R);T=isNaN(A.getTime())?"":A.toLocaleDateString()}g.textContent=T}else if(p.type==="boolean"){const A=!!R;g.innerHTML=`<span role="checkbox" aria-checked="${A}" aria-label="${A}">${A?"&#x1F5F9;":"&#9744;"}</span>`}else T=R==null?"":String(R),g.textContent=T}}function G(o,e,t,n){e.innerHTML="";const i=o._visibleColumns,r=i.length,s=o._focusRow,l=o._focusCol,a=o.effectiveConfig?.editOn||o.editOn,c=o,d=document.createDocumentFragment();for(let u=0;u<r;u++){const f=i[u],h=document.createElement("div");h.className="cell",le(h,"cell"),h.setAttribute("role","gridcell"),h.setAttribute("aria-colindex",String(u+1)),h.setAttribute("data-col",String(u)),h.setAttribute("data-row",String(n)),h.setAttribute("data-field",f.field),f.type,f.type&&h.setAttribute("data-type",f.type);let p=t[f.field];const g=f.format;if(g)try{p=g(p,t)}catch{}const w=f.__compiledView,y=f.__viewTemplate,R=f.viewRenderer,T=f.externalView;let A=!1;if(R){const b=R({row:t,value:p,field:f.field,column:f});typeof b=="string"?(h.innerHTML=ie(b),A=!0):b?h.appendChild(b):h.textContent=p==null?"":String(p)}else if(T){const b=T,m=document.createElement("div");m.setAttribute("data-external-view",""),m.setAttribute("data-field",f.field),h.appendChild(m);const S={row:t,value:p,field:f.field,column:f};if(b.mount)try{b.mount({placeholder:m,context:S,spec:b})}catch{}else queueMicrotask(()=>{try{c.dispatchEvent(new CustomEvent("mount-external-view",{bubbles:!0,composed:!0,detail:{placeholder:m,spec:b,context:S}}))}catch{}});m.setAttribute("data-mounted","")}else if(w){const b=w({row:t,value:p,field:f.field,column:f}),m=w.__blocked;h.innerHTML=m?"":ie(b),A=!0,m&&(h.textContent="",h.setAttribute("data-blocked-template",""))}else if(y){const b=y.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(b)?(h.textContent="",h.setAttribute("data-blocked-template","")):(h.innerHTML=ie(ze(b,{row:t,value:p})),A=!0)}else if(f.type==="date")if(p==null||p==="")h.textContent="";else{let b=null;if(p instanceof Date)b=p;else if(typeof p=="number"||typeof p=="string"){const m=new Date(p);isNaN(m.getTime())||(b=m)}h.textContent=b?b.toLocaleDateString():""}else if(f.type==="boolean"){const b=!!p;h.innerHTML=`<span role="checkbox" aria-checked="${b}" aria-label="${b}">${b?"&#x1F5F9;":"&#9744;"}</span>`}else h.textContent=p==null?"":String(p);if(A){Gt(h);const b=h.textContent||"";/Proxy|Reflect\.ownKeys/.test(b)&&(h.textContent=b.replace(/Proxy|Reflect\.ownKeys/g,"").trim(),/Proxy|Reflect\.ownKeys/.test(h.textContent||"")&&(h.textContent=""))}h.hasAttribute("data-blocked-template")&&(h.textContent||"").trim().length&&(h.textContent=""),f.editable?(h.tabIndex=0,h.addEventListener("mousedown",()=>{if(h.classList.contains("editing"))return;const b=Number(h.getAttribute("data-row")),m=Number(h.getAttribute("data-col"));isNaN(b)||isNaN(m)||(o._focusRow=b,o._focusCol=m,D(o))}),a==="click"?h.addEventListener("click",b=>{if(h.classList.contains("editing"))return;b.stopPropagation();const m=Number(h.getAttribute("data-row")),S=Number(h.getAttribute("data-col"));if(isNaN(m)||isNaN(S))return;const E=o._rows[m],v=o._visibleColumns[S];!E||!v||(o._focusRow=m,o._focusCol=S,O(o,E,m,v,h))}):h.addEventListener("dblclick",b=>{b.stopPropagation();const m=Number(h.getAttribute("data-row"));if(isNaN(m))return;const S=o._rows[m];if(!S)return;W(o,m,S);const E=o.findRenderedRowElement?.(m);if(E){const v=E.children;for(let x=0;x<v.length;x++){const _=o._visibleColumns[x];_&&_.editable&&O(o,S,m,_,v[x])}}}),h.addEventListener("keydown",b=>{const m=Number(h.getAttribute("data-row")),S=Number(h.getAttribute("data-col"));if(isNaN(m)||isNaN(S))return;const E=o._rows[m],v=o._visibleColumns[S];if(!(!E||!v)){if((v.type==="select"||v.type==="typeahead")&&!h.classList.contains("editing")&&b.key==="Enter"){b.preventDefault(),o._activeEditRows!==m&&W(o,m,E),O(o,E,m,v,h),setTimeout(()=>{const x=h.querySelector("select");try{x?.showPicker?.()}catch{}x?.focus()},0);return}if(v.type==="boolean"&&b.key===" "&&!h.classList.contains("editing")){b.preventDefault(),o._activeEditRows!==m&&W(o,m,E);const x=!E[v.field];ue(o,m,v,x,E),h.innerHTML=`<span role="checkbox" aria-checked="${x}" aria-label="${x}">${x?"&#x1F5F9;":"&#9744;"}</span>`;return}if(b.key==="Enter"&&!h.classList.contains("editing")){b.preventDefault(),b.stopPropagation(),o._focusRow=m,o._focusCol=S,typeof o.beginBulkEdit=="function"?o.beginBulkEdit(m):O(o,E,m,v,h);return}if(b.key==="F2"&&!h.classList.contains("editing")){b.preventDefault(),O(o,E,m,v,h);return}}})):f.type==="boolean"&&(h.hasAttribute("tabindex")||(h.tabIndex=0)),s===n&&l===u?(h.classList.add("cell-focus"),h.setAttribute("aria-selected","true")):h.setAttribute("aria-selected","false"),d.appendChild(h)}e.appendChild(d)}function Be(o,e,t,n){if(e.target?.closest(".resize-handle"))return;const i=t.querySelector(".cell[data-row]");if(!i)return;const r=Number(i.getAttribute("data-row"));if(isNaN(r))return;const s=o._rows[r];if(!s||o._dispatchRowClick?.(e,r,s,t))return;const l=e.target?.closest(".cell[data-col]");if(l){if(l.classList.contains("editing"))return;const c=Number(l.getAttribute("data-col"));if(!isNaN(c)){if(o._dispatchCellClick?.(e,r,c,l))return;o._focusRow=r,o._focusCol=c,D(o)}}if(t.querySelector(".cell.editing")){const c=t.querySelectorAll(".cell.editing");if(!n)return;c.forEach(d=>d.classList.remove("editing"))}const a=o.effectiveConfig?.editOn||o.editOn||"doubleClick";if(a==="click"||a==="doubleClick"&&n)W(o,r,s);else return;Array.from(t.children).forEach((c,d)=>{const u=o._visibleColumns[d];u&&u.editable&&O(o,s,r,u,c)}),l&&queueMicrotask(()=>{const c=t.querySelector(`.cell[data-col="${o._focusCol}"]`);if(c?.classList.contains("editing")){const d=c.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');try{d?.focus()}catch{}}})}function de(o){return!(o==="__proto__"||o==="constructor"||o==="prototype")}function W(o,e,t){o._activeEditRows!==e&&(o._rowEditSnapshots.set(e,{...t}),o._activeEditRows=e)}function K(o,e,t){if(o._activeEditRows!==e)return;const n=o._rowEditSnapshots.get(e),i=o._rows[e],r=o.findRenderedRowElement?.(e);if(!t&&r&&i&&r.querySelectorAll(".cell.editing").forEach(l=>{const a=Number(l.getAttribute("data-col"));if(isNaN(a))return;const c=o._visibleColumns[a];if(!c)return;const d=l.querySelector("input,textarea,select");if(d){let u;d instanceof HTMLInputElement&&d.type==="checkbox"?u=d.checked:(u=d.value,c.type==="number"&&u!==""&&(u=Number(u))),i[c.field]!==u&&ue(o,e,c,u,i)}}),t&&n&&i)Object.keys(n).forEach(s=>i[s]=n[s]),o._changedRowIndices.delete(e),ae(o);else if(!t){const s=o._changedRowIndices.has(e);o.dispatchEvent(new CustomEvent("row-commit",{detail:{rowIndex:e,row:i,changed:s,changedRows:o.changedRows,changedRowIndices:o.changedRowIndices}}))}o._rowEditSnapshots.delete(e),o._activeEditRows=-1,r&&(G(o,r,o._rows[e],e),o._changedRowIndices.has(e)?r.classList.add("changed"):r.classList.remove("changed")),queueMicrotask(()=>{try{const s=o._focusRow,l=o._focusCol,a=o.findRenderedRowElement?.(s);if(a){Array.from(o._bodyEl.querySelectorAll(".cell-focus")).forEach(d=>d.classList.remove("cell-focus"));const c=a.querySelector(`.cell[data-row="${s}"][data-col="${l}"]`);c&&(c.classList.add("cell-focus"),c.setAttribute("aria-selected","true"),c.hasAttribute("tabindex")||c.setAttribute("tabindex","-1"),c.focus({preventScroll:!0}))}}catch{}})}function ue(o,e,t,n,i){const r=t.field;if(!de(r)||i[r]===n)return;i[r]=n;const l=!o._changedRowIndices.has(e);o._changedRowIndices.add(e);const a=o.findRenderedRowElement?.(e);a&&a.classList.add("changed"),o.dispatchEvent(new CustomEvent("cell-commit",{detail:{row:i,field:r,value:n,rowIndex:e,changedRows:o.changedRows,changedRowIndices:o.changedRowIndices,firstTimeForRow:l}}))}function O(o,e,t,n,i){if(!n.editable||(o._activeEditRows!==t&&W(o,t,e),i.classList.contains("editing")))return;const r=de(n.field)?e[n.field]:void 0;i.classList.add("editing");let s=!1;const l=h=>{s||o._activeEditRows===-1||ue(o,t,n,h,e)},a=()=>{s=!0,e[n.field]=de(n.field)?r:void 0;const h=i.querySelector("input,textarea,select");h&&(typeof HTMLInputElement<"u"&&h instanceof HTMLInputElement&&h.type==="checkbox"?h.checked=!!r:"value"in h&&(h.value=r??""))},c=document.createElement("div");c.style.display="contents",i.innerHTML="",i.appendChild(c),c.addEventListener("keydown",h=>{h.key==="Enter"&&(h.stopPropagation(),h.preventDefault(),s=!0,K(o,t,!1)),h.key==="Escape"&&(h.stopPropagation(),h.preventDefault(),a(),K(o,t,!0))});const d=n.__editorTemplate,u=n.editor||(d?"template":Xt(n)),f=r;if(u==="template"&&d){const h=d.cloneNode(!0),p=n.__compiledEditor;p?h.innerHTML=p({row:e,value:r,field:n.field,column:n}):h.querySelectorAll("*").forEach(w=>{w.childNodes.length===1&&w.firstChild?.nodeType===Node.TEXT_NODE&&(w.textContent=w.textContent?.replace(/{{\s*value\s*}}/g,r==null?"":String(r)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(y,R)=>{const T=e[R];return T==null?"":String(T)})||"")});const g=h.querySelector("input,textarea,select");if(g){const w=typeof HTMLInputElement<"u";w&&g instanceof HTMLInputElement&&g.type==="checkbox"?g.checked=!!r:"value"in g&&(g.value=r??""),g.addEventListener("blur",()=>{const y=w&&g instanceof HTMLInputElement&&g.type==="checkbox"?g.checked:g.value;l(y)}),g.addEventListener("keydown",y=>{if(y.key==="Enter"){y.stopPropagation(),y.preventDefault(),s=!0;const R=w&&g instanceof HTMLInputElement&&g.type==="checkbox"?g.checked:g.value;l(R),K(o,t,!1)}y.key==="Escape"&&(y.stopPropagation(),y.preventDefault(),a(),K(o,t,!0))}),w&&g instanceof HTMLInputElement&&g.type==="checkbox"&&g.addEventListener("change",()=>{const y=g.checked;l(y)}),setTimeout(()=>g.focus(),0)}c.appendChild(h)}else if(typeof u=="string"){const h=document.createElement(u);h.value=f,h.addEventListener("change",()=>l(h.value)),c.appendChild(h)}else if(typeof u=="function"){const h=u({row:e,value:f,field:n.field,column:n,commit:l,cancel:a});typeof h=="string"?c.innerHTML=h:c.appendChild(h)}else if(u&&typeof u=="object"){const h=document.createElement("div");h.setAttribute("data-external-editor",""),h.setAttribute("data-field",n.field),c.appendChild(h);const p={row:e,value:f,field:n.field,column:n,commit:l,cancel:a};if(u.mount)try{u.mount({placeholder:h,context:p,spec:u})}catch{}else o.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:h,spec:u,context:p}}))}}function Ke(o,e){return o==null&&e==null?0:o==null?-1:e==null||o>e?1:o<e?-1:0}function Ve(o,e,t){const i=t.find(l=>l.field===e.field)?.sortComparator??Ke,{field:r,direction:s}=e;return[...o].sort((l,a)=>i(l[r],a[r],l,a)*s)}function $e(o,e,t,n){o._rows=e,o.__rowRenderEpoch++,o._rowPool.forEach(i=>i.__epoch=-1),U(o),o.refreshVirtualWindow(!0),o.dispatchEvent(new CustomEvent("sort-change",{detail:{field:t.field,direction:n}})),o.requestStateChange?.()}function Ge(o,e){!o._sortState||o._sortState.field!==e.field?(o._sortState||(o.__originalOrder=o._rows.slice()),We(o,e,1)):o._sortState.direction===1?We(o,e,-1):(o._sortState=null,o.__rowRenderEpoch++,o._rowPool.forEach(n=>n.__epoch=-1),o._rows=o.__originalOrder.slice(),U(o),o._headerRowEl?.querySelectorAll('[role="columnheader"].sortable')?.forEach(n=>{n.getAttribute("aria-sort")?(n.getAttribute("aria-sort")==="ascending"||n.getAttribute("aria-sort")==="descending")&&(o._sortState||n.setAttribute("aria-sort","none")):n.setAttribute("aria-sort","none")}),o.refreshVirtualWindow(!0),o.dispatchEvent(new CustomEvent("sort-change",{detail:{field:e.field,direction:0}})),o.requestStateChange?.())}function We(o,e,t){o._sortState={field:e.field,direction:t};const n={field:e.field,direction:t},i=o._columns,s=(o.effectiveConfig?.sortHandler??Ve)(o._rows,n,i);s&&typeof s.then=="function"?s.then(l=>{$e(o,l,e,t)}):$e(o,s,e,t)}function eo(o,e){typeof e=="string"?o.textContent=e:e instanceof HTMLElement&&(o.innerHTML="",o.appendChild(e.cloneNode(!0)))}function U(o){o._headerRowEl=o.findHeaderRow();const e=o._headerRowEl;e.innerHTML="",o._visibleColumns.forEach((t,n)=>{const i=document.createElement("div");i.className="cell",le(i,"header-cell"),i.setAttribute("role","columnheader"),i.setAttribute("aria-colindex",String(n+1)),i.setAttribute("data-field",t.field),i.setAttribute("data-col",String(n));const r=t.__headerTemplate;if(r)Array.from(r.childNodes).forEach(s=>i.appendChild(s.cloneNode(!0)));else{const s=t.header||t.field,l=document.createElement("span");l.textContent=s,i.appendChild(l)}if(t.sortable){i.classList.add("sortable"),i.tabIndex=0;const s=document.createElement("span");le(s,"sort-indicator");const l=o._sortState?.field===t.field?o._sortState.direction:0,a={...I,...o.icons},c=l===1?a.sortAsc:l===-1?a.sortDesc:a.sortNone;eo(s,c),i.appendChild(s),i.setAttribute("aria-sort",l===0?"none":l===1?"ascending":"descending"),i.addEventListener("click",d=>{o._resizeController?.isResizing||o._dispatchHeaderClick?.(d,n,i)||Ge(o,t)}),i.addEventListener("keydown",d=>{if(d.key==="Enter"||d.key===" "){if(d.preventDefault(),o._dispatchHeaderClick?.(d,n,i))return;Ge(o,t)}})}if(t.resizable){i.style.position="relative";const s=document.createElement("div");s.className="resize-handle",s.setAttribute("aria-hidden","true"),s.addEventListener("mousedown",l=>{l.stopPropagation(),l.preventDefault(),o._resizeController.start(l,n,i)}),s.addEventListener("dblclick",l=>{l.stopPropagation(),l.preventDefault(),o._resizeController.resetColumn(n)}),i.appendChild(s)}e.appendChild(i)}),e.querySelectorAll(".cell.sortable").forEach(t=>{t.getAttribute("aria-sort")||t.setAttribute("aria-sort","none")}),e.children.length>0?(e.setAttribute("role","row"),e.setAttribute("aria-rowindex","1")):(e.removeAttribute("role"),e.removeAttribute("aria-rowindex"))}function to(o){let e=null,t=null,n=null,i=null;const r=a=>{if(!e)return;const c=a.clientX-e.startX,d=Math.max(40,e.startWidth+c),u=o._visibleColumns[e.colIndex];u.width=d,u.__userResized=!0,u.__renderedWidth=d,t==null&&(t=requestAnimationFrame(()=>{t=null,o.updateTemplate?.()})),o.dispatchEvent(new CustomEvent("column-resize",{detail:{field:u.field,width:d}}))};let s=!1;const l=()=>{const a=e!==null;a&&(s=!0,requestAnimationFrame(()=>{s=!1})),window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",l),n!==null&&(document.documentElement.style.cursor=n,n=null),i!==null&&(document.body.style.userSelect=i,i=null),e=null,a&&o.requestStateChange&&o.requestStateChange()};return{get isResizing(){return e!==null||s},start(a,c,d){a.preventDefault();const u=d.getBoundingClientRect();e={startX:a.clientX,colIndex:c,startWidth:u.width},window.addEventListener("mousemove",r),window.addEventListener("mouseup",l),n===null&&(n=document.documentElement.style.cursor),document.documentElement.style.cursor="e-resize",i===null&&(i=document.body.style.userSelect),document.body.style.userSelect="none"},resetColumn(a){const c=o._visibleColumns[a];c&&(c.__userResized=!1,c.__renderedWidth=void 0,c.width=c.__originalWidth,o.updateTemplate?.(),o.requestStateChange?.(),o.dispatchEvent(new CustomEvent("column-resize-reset",{detail:{field:c.field,width:c.width}})))},dispose(){l()}}}function Q(o){return o?typeof o=="string"?o:o.outerHTML:""}function oo(){return{toolPanels:new Map,headerContents:new Map,toolbarButtons:new Map,lightDomButtons:[],lightDomHeaderContent:[],isPanelOpen:!1,expandedSections:new Set,headerContentCleanups:new Map,panelCleanups:new Map,toolbarButtonCleanups:new Map,activePanel:null,activePanelCleanup:null}}function no(o,e){return!!(o?.header?.title||o?.header?.toolbarButtons?.length||e.toolPanels.size>0||e.headerContents.size>0||e.toolbarButtons.size>0||e.lightDomButtons.length>0||e.lightDomHeaderContent.length>0)}function io(o,e,t="☰"){const n=o?.header?.title??"",i=!!n,r=Q(t),s=o?.header?.toolbarButtons??[],l=s.length>0,a=e.toolbarButtons.size>0,c=e.lightDomButtons.length>0,d=e.toolPanels.size>0,f=(l||a||c)&&d,h=[...s].sort((w,y)=>(w.order??100)-(y.order??100)),p=[...e.toolbarButtons.values()].sort((w,y)=>(w.order??100)-(y.order??100));let g="";for(const w of h)w.icon&&w.action&&(g+=`<button class="tbw-toolbar-btn" data-btn="${w.id}" title="${w.label}" aria-label="${w.label}"${w.disabled?" disabled":""}>${w.icon}</button>`);for(const w of p)w.icon&&w.action&&(g+=`<button class="tbw-toolbar-btn" data-btn="${w.id}" title="${w.label}" aria-label="${w.label}"${w.disabled?" disabled":""}>${w.icon}</button>`);for(const w of h)(w.element||w.render)&&(g+=`<div class="tbw-toolbar-btn-slot" data-btn-slot="${w.id}"></div>`);for(const w of p)(w.element||w.render)&&(g+=`<div class="tbw-toolbar-btn-slot" data-btn-slot="${w.id}"></div>`);if(c&&(g+='<slot name="toolbar"></slot>'),f&&(g+='<div class="tbw-toolbar-separator"></div>'),d){const w=e.isPanelOpen;g+=`<button class="tbw-toolbar-btn${w?" active":""}" data-panel-toggle title="Settings" aria-label="Toggle settings panel" aria-pressed="${w}" aria-controls="tbw-tool-panel">${r}</button>`}return`
1
+ (function(C,J){typeof exports=="object"&&typeof module<"u"?J(exports):typeof define=="function"&&define.amd?define(["exports"],J):(C=typeof globalThis<"u"?globalThis:C||self,J(C.TbwGrid={}))})(this,(function(C){"use strict";const J=':root{color-scheme:light dark}:host{--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-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, #adacac);--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: inherit;--tbw-font-size-header: var(--tbw-font-size);--tbw-font-weight-header: bold;--tbw-cell-padding-header: 2px 8px;--tbw-cell-padding: 2px 8px;--tbw-cell-padding-input: 2px 6px;--tbw-row-height: 28px;--tbw-header-height: 30px;--tbw-cell-white-space: nowrap;--tbw-border-radius: 4px;--tbw-border-input: 1px solid var(--tbw-color-border-strong);--tbw-border-header: 1px solid var(--tbw-color-border-header);--tbw-row-divider: 1px solid 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: 2px solid 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: 6px;--tbw-resize-handle-color: transparent;--tbw-resize-handle-color-hover: var(--tbw-color-accent);--tbw-resize-handle-border-radius: 0;--tbw-scrollbar-thumb: var(--tbw-color-border-strong);--tbw-scrollbar-track: var(--tbw-color-bg);--tbw-transition-duration: .12s;--tbw-transition-ease: ease;--tbw-animation-duration: .2s;--tbw-animation-easing: ease-out;--tbw-animation-enabled: 1;--tbw-editing-bg: var(--tbw-color-selection);--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-sort-indicator-color: var(--tbw-color-fg-muted);--tbw-sort-indicator-active-color: var(--tbw-color-accent);--tbw-header-text-transform: none;--tbw-header-letter-spacing: normal;--tbw-color-header-separator: var(--tbw-color-border-cell);--tbw-checkbox-size: 16px;--tbw-density-scale: 1}:host{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);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}:host,:host *{box-sizing:border-box}:host .header{display:block;flex-shrink:0;z-index:var(--tbw-z-layer-header, 30);background:var(--tbw-color-header-bg);overflow:visible}:host .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)}:host .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))}:host .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)}:host .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:hidden;min-width:0}:host .header-row>.cell>span:first-child{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}:host .header-row>.cell>span[part~=sort-indicator]{flex-shrink:0;opacity:.6}:host .header-row>.cell:last-child{border-right:0}:host .header-group-cell:not(:last-child),:host .header-row>.cell.grouped.group-end:not(:last-child){border-right:2px solid var(--tbw-color-border)}:host .tbw-grid-root{display:flex;flex-direction:column;height:100%}:host .rows-body-wrapper{flex:1;min-height:0;display:flex;flex-direction:row;width:100%;min-width:fit-content}:host .rows-body{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:visible}:host .rows-container{display:flex;flex-direction:row;flex:1;min-height:0;overflow:visible}:host .rows-viewport{flex:1;min-width:0;position:relative;display:block;overflow:clip}:host .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)}:host .faux-vscroll-spacer{width:1px}:host .rows-viewport .rows{position:absolute;top:0;left:0;min-width:100%;will-change:transform;z-index:var(--tbw-z-layer-rows, 1)}:host .data-grid-row{display:grid;grid-template-columns:var(--tbw-column-template);contain:layout style}:host .data-grid-row:has(.editing){background:var(--tbw-editing-bg)}:host .selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}:host .data-grid-row>.cell.selected:focus-visible,:host .data-grid-row>.cell:focus-visible:not(.cell-focus){outline:none}:host .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);line-height:calc(var(--tbw-row-height) - 5px);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}:host .data-grid-row>.cell>*{overflow:hidden;text-overflow:ellipsis;white-space:inherit;min-width:0}:host .data-grid-row>.cell:last-child{border-right:0}:host .data-grid-row>.cell[data-type=boolean]{text-align:center}:host .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}:host .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex}:host .data-grid-row>.cell.editing input:not([type=checkbox]),:host .data-grid-row>.cell.editing select,:host .data-grid-row>.cell.editing textarea{width:100%;height:100%;max-width: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)}:host .data-grid-row:nth-child(2n){background:var(--tbw-color-row-alt)}:host .data-grid-row:hover{background:var(--tbw-color-row-hover)}:host .sortable{cursor:pointer;-webkit-user-select:none;user-select:none}:host .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)}:host .resize-handle:hover{background:var(--tbw-resize-handle-color-hover)}:host .cell-focus,:host .row-focus{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}:host .group-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-color-row-alt);font-weight:500;border-bottom:var(--tbw-row-divider);min-height:var(--tbw-row-height)}:host .group-row .cell{display:flex;align-items:center;padding:var(--tbw-cell-padding, 2px 8px)}:host .group-row .group-toggle{background:none;border:0;cursor:pointer;padding:0 4px 0 0;font:inherit}:host .group-row .group-count{margin-left:4px;opacity:.7}:host .sticky-left,:host .sticky-right{position:sticky;z-index:25}:host .header-row>.cell.sticky-left,:host .header-row>.cell.sticky-right{background:var(--tbw-color-header-bg);z-index:35}:host .data-grid-row>.cell.sticky-left,:host .data-grid-row>.cell.sticky-right{background:var(--tbw-color-panel-bg)}:host .sticky-left{box-shadow:1px 0 0 var(--tbw-color-border)}:host .sticky-right{box-shadow:-1px 0 0 var(--tbw-color-border)}.grid-container{position:relative;width:100%;height:100%}.grid-placeholder{padding:2rem;text-align:center;color:var(--tbw-color-fg);opacity:.6}:host{--tbw-shell-header-height: 44px;--tbw-shell-header-bg: var(--tbw-color-panel-bg);--tbw-shell-header-border: var(--tbw-color-border);--tbw-shell-title-font-size: 14px;--tbw-shell-title-font-weight: 600;--tbw-tool-panel-width: 280px;--tbw-tool-panel-bg: var(--tbw-color-panel-bg);--tbw-tool-panel-border: var(--tbw-color-border);--tbw-tool-panel-header-height: 40px;--tbw-tool-panel-transition: var(--tbw-animation-duration) var(--tbw-animation-easing);--tbw-toolbar-button-size: 32px;--tbw-toolbar-button-gap: 4px}:host .tbw-grid-root.has-shell{display:flex;flex-direction:column;height:100%}:host .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}:host .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}:host .tbw-shell-content{flex:1;display:flex;align-items:center;gap:12px;min-width:0;overflow:hidden}:host .tbw-shell-toolbar{display:flex;align-items:center;gap:var(--tbw-toolbar-button-gap);flex-shrink:0}:host .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)}:host .tbw-toolbar-btn:hover{background:var(--tbw-color-row-hover)}:host .tbw-toolbar-btn:focus-visible{outline:var(--tbw-focus-outline);outline-offset:var(--tbw-focus-outline-offset)}:host .tbw-toolbar-btn.active{background:var(--tbw-focus-background);border-color:var(--tbw-color-accent)}:host .tbw-toolbar-btn:disabled{opacity:.5;cursor:not-allowed}:host .tbw-toolbar-separator{width:1px;height:20px;background:var(--tbw-color-border);margin:0 4px}:host .tbw-shell-body{position:relative;display:flex;flex:1;min-height:0;overflow:visible}:host .tbw-grid-content{flex:1;min-width:0;min-height:0;display:flex;flex-direction:row;overflow:hidden}:host .tbw-scroll-area{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow-x:auto;overflow-y:hidden}:host .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)}:host .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)}:host .tbw-tool-panel.open{width:var(--tbw-tool-panel-width)}:host .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)}:host .tbw-tool-panel-resize[data-handle-position=left]{left:0}:host .tbw-tool-panel-resize[data-handle-position=right]{right:0}:host .tbw-tool-panel-resize:hover,:host .tbw-tool-panel-resize.resizing{background:var(--tbw-color-accent)}:host .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}:host .tbw-tool-panel-title{font-weight:600;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}:host .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}:host .tbw-tool-panel-close:hover{background:var(--tbw-color-row-hover);color:var(--tbw-color-fg)}:host .tbw-tool-panel-content{flex:1;overflow:auto}:host .tbw-accordion{display:flex;flex-direction:column;gap:0}:host .tbw-accordion-section{border-bottom:1px solid var(--tbw-tool-panel-border)}:host .tbw-accordion-section:last-child{border-bottom:none}:host .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:left;cursor:pointer;-webkit-user-select:none;user-select:none}:host .tbw-accordion-header:hover{background:var(--tbw-color-row-hover)}:host .tbw-accordion-section.single .tbw-accordion-header{cursor:default}:host .tbw-accordion-section.single .tbw-accordion-header:hover{background:transparent}:host .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}:host .tbw-accordion-section.expanded .tbw-accordion-chevron{transform:rotate(90deg)}:host .tbw-accordion-icon{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;font-size:14px;flex-shrink:0}:host .tbw-accordion-title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}:host .tbw-accordion-content{display:none}:host .tbw-accordion-section.expanded .tbw-accordion-content{display:block}:host .tbw-quick-filter-input{flex:1;max-width:300px;height:28px;padding:0 8px;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:13px}:host .tbw-quick-filter-input:focus{outline:none;border-color:var(--tbw-color-accent)}:host .tbw-selection-summary{font-size:13px;color:var(--tbw-color-fg-muted);white-space:nowrap}@media(prefers-reduced-motion:reduce){:host([data-animation-mode="reduced-motion"]){--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}}:host([data-animation-mode="off"]){--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}:host .tbw-expanding{animation:tbw-expand var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}:host .tbw-collapsing{animation:tbw-collapse var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}@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)}}:host .tbw-fade-in{animation:tbw-fade-in var(--tbw-animation-duration) var(--tbw-animation-easing) forwards}:host .tbw-fade-out{animation:tbw-fade-out var(--tbw-animation-duration) var(--tbw-animation-easing) forwards}@keyframes tbw-fade-in{0%{opacity:0}to{opacity:1}}@keyframes tbw-fade-out{0%{opacity:1}to{opacity:0}}:host .tbw-flip-animating{will-change:transform;z-index:1}:host .tbw-toggle-icon{display:inline-flex;align-items:center;justify-content:center;transition:transform var(--tbw-animation-duration) var(--tbw-animation-easing)}:host .tbw-toggle-icon.tbw-expanded{transform:rotate(90deg)}';function Mt(o){const e=new Map;return o._sortState&&e.set(o._sortState.field,{direction:o._sortState.direction===1?"asc":"desc",priority:0}),e}function He(o,e){const t=o._columns,n=Mt(o);return{columns:t.map((i,r)=>{const s={field:i.field,order:r,visible:!0},l=i;l.__renderedWidth!==void 0?s.width=l.__renderedWidth:i.width!==void 0&&(s.width=typeof i.width=="string"?parseFloat(i.width):i.width);const a=n.get(i.field);a&&(s.sort=a);for(const c of e)if(c.getColumnState){const d=c.getColumnState(i.field);d&&Object.assign(s,d)}return s})}}function It(o,e,t,n){if(!e.columns||e.columns.length===0)return;const i=new Map(e.columns.map(l=>[l.field,l])),r=t.map(l=>{const a=i.get(l.field);if(!a)return l;const c={...l};return a.width!==void 0&&(c.width=a.width,c.__renderedWidth=a.width),a.visible!==void 0&&(c.hidden=!a.visible),c});r.sort((l,a)=>{const c=i.get(l.field)?.order??1/0,d=i.get(a.field)?.order??1/0;return c-d}),o._columns=r;const s=e.columns.filter(l=>l.sort!==void 0).sort((l,a)=>(l.sort?.priority??0)-(a.sort?.priority??0));if(s.length>0){const l=s[0];l.sort&&(o._sortState={field:l.field,direction:l.sort.direction==="asc"?1:-1})}else o._sortState=null;for(const l of n)if(l.applyColumnState)for(const a of e.columns)l.applyColumnState(a.field,a)}function Ht(o,e,t){let n=null;return()=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{n=null;const i=He(o,e());t(i)},100)}}const $={STRETCH:"stretch",FIXED:"fixed"},Ne={mode:"reduced-motion",duration:200,easing:"ease-out"},I={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰"};function Nt(o){return o==null?"string":typeof o=="number"?"number":typeof o=="boolean"?"boolean":o instanceof Date||typeof o=="string"&&/\d{4}-\d{2}-\d{2}/.test(o)&&!isNaN(Date.parse(o))?"date":"string"}function De(o,e){if(e&&e.length){const r={};return e.forEach(s=>{s.type&&(r[s.field]=s.type)}),{columns:e,typeMap:r}}const t=o[0]||{},n=Object.keys(t).map(r=>{const s=t[r],l=Nt(s);return{field:r,header:r.charAt(0).toUpperCase()+r.slice(1),type:l}}),i={};return n.forEach(r=>{i[r.field]=r.type||"string"}),{columns:n,typeMap:i}}const Dt=/{{\s*([^}]+)\s*}}/g,H="__DG_EMPTY__",Ot=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,zt=/__(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/,Ft=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"]),Oe=/^on\w+$/i,qt=new Set(["href","src","action","formaction","data","srcdoc","xlink:href","poster","srcset"]),Bt=/^\s*(javascript|vbscript|data|blob):/i;function ie(o){if(!o||typeof o!="string")return"";if(o.indexOf("<")===-1)return o;const e=document.createElement("template");return e.innerHTML=o,Kt(e.content),e.innerHTML}function Kt(o){const e=[],t=o.querySelectorAll("*");for(const n of t){const i=n.tagName.toLowerCase();if(Ft.has(i)){e.push(n);continue}if((i==="svg"||n.namespaceURI==="http://www.w3.org/2000/svg")&&Array.from(n.attributes).some(l=>Oe.test(l.name)||l.name==="href"||l.name==="xlink:href")){e.push(n);continue}const r=[];for(const s of n.attributes){const l=s.name.toLowerCase();if(Oe.test(l)){r.push(s.name);continue}if(qt.has(l)&&Bt.test(s.value)){r.push(s.name);continue}if(l==="style"&&/expression\s*\(|javascript:|behavior\s*:/i.test(s.value)){r.push(s.name);continue}}r.forEach(s=>n.removeAttribute(s))}e.forEach(n=>n.remove())}function ze(o,e){if(!o||o.indexOf("{{")===-1)return o;const t=[],n=o.replace(Dt,(l,a)=>{const c=Vt(a,e);return t.push({expr:a.trim(),result:c}),c}),i=$t(n),r=t.length&&t.every(l=>l.result===""||l.result===H);return/Reflect\.|\bProxy\b|ownKeys\(/.test(o)||r?"":i}function Vt(o,e){if(o=(o||"").trim(),!o||/\b(Reflect|Proxy|ownKeys)\b/.test(o))return H;if(o==="value")return e.value==null?H:String(e.value);if(o.startsWith("row.")&&!/[()?]/.test(o)&&!o.includes(":")){const n=o.slice(4),i=e.row?e.row[n]:void 0;return i==null?H:String(i)}if(o.length>80||!Ot.test(o)||zt.test(o))return H;const t=o.match(/\./g);if(t&&t.length>1)return H;try{const i=new Function("value","row",`return (${o});`)(e.value,e.row),r=i==null?"":String(i);return/Reflect|Proxy|ownKeys/.test(r)?H:r||H}catch{return H}}function $t(o){return o&&o.replace(new RegExp(H,"g"),"").replace(/Reflect\.[^<>{}\s]+/g,"").replace(/\bProxy\b/g,"").replace(/ownKeys\([^)]*\)/g,"")}function Gt(o){if(/Reflect|Proxy|ownKeys/.test(o.textContent||"")){if(Array.from(o.childNodes).forEach(e=>{e.nodeType===Node.TEXT_NODE&&/Reflect|Proxy|ownKeys/.test(e.textContent||"")&&(e.textContent="")}),/Reflect|Proxy|ownKeys/.test(o.textContent||"")){if(/Reflect|Proxy|ownKeys/.test(o.textContent||""))for(;o.firstChild;)o.removeChild(o.firstChild);o.textContent=(o.textContent||"").replace(/Reflect|Proxy|ownKeys/g,"")}(o.textContent||"").trim().length===0&&(o.textContent="")}}function Fe(o){const e=/Reflect\.|\bProxy\b|ownKeys\(/.test(o),t=n=>e?"":ze(o,n);return t.__blocked=e,t}function Wt(o){return Array.from(o.querySelectorAll("tbw-grid-column")).map(t=>{const n=t.getAttribute("field")||"";if(!n)return null;const i=t.getAttribute("type")||void 0,s=i&&new Set(["number","string","date","boolean","select","typeahead"]).has(i)?i:void 0,l=t.getAttribute("header")||void 0,a=t.hasAttribute("sortable"),c=t.hasAttribute("editable"),d={field:n,type:s,header:l,sortable:a,editable:c};t.hasAttribute("resizable")&&(d.resizable=!0),t.hasAttribute("sizable")&&(d.resizable=!0);const u=t.getAttribute("options");u&&(d.options=u.split(",").map(g=>{const[w,y]=g.includes(":")?g.split(":"):[g.trim(),g.trim()];return{value:w.trim(),label:y?.trim()||w.trim()}}));const f=t.querySelector("tbw-grid-column-view"),h=t.querySelector("tbw-grid-column-editor"),p=t.querySelector("tbw-grid-column-header");return f&&(d.__viewTemplate=f),h&&(d.__editorTemplate=h),p&&(d.__headerTemplate=p),d}).filter(t=>!!t)}function Ut(o,e){if((!o||!o.length)&&(!e||!e.length))return[];if(!o||!o.length)return e||[];if(!e||!e.length)return o;const t={};e.forEach(i=>t[i.field]=i);const n=o.map(i=>{const r=t[i.field];if(!r)return i;const s={...i};return r.header&&!s.header&&(s.header=r.header),r.type&&!s.type&&(s.type=r.type),s.sortable=i.sortable||r.sortable,(i.resizable===!0||r.resizable===!0)&&(s.resizable=!0),s.editable=i.editable||r.editable,r.__viewTemplate&&(s.__viewTemplate=r.__viewTemplate),r.__editorTemplate&&(s.__editorTemplate=r.__editorTemplate),r.__headerTemplate&&(s.__headerTemplate=r.__headerTemplate),delete t[i.field],s});return Object.keys(t).forEach(i=>n.push(t[i])),n}function le(o,e){try{o.part?.add?.(e)}catch{}const t=o.getAttribute("part");t?t.split(/\s+/).includes(e)||o.setAttribute("part",t+" "+e):o.setAttribute("part",e)}function jt(o){o.__lightDomColumnsCache||(o.__originalColumnNodes=Array.from(o.querySelectorAll("tbw-grid-column")),o.__lightDomColumnsCache=o.__originalColumnNodes.length?Wt(o):[]);const e=o.__lightDomColumnsCache,t=Ut(o._columns,e);t.forEach(i=>{i.__viewTemplate&&!i.__compiledView&&(i.__compiledView=Fe(i.__viewTemplate.innerHTML)),i.__editorTemplate&&!i.__compiledEditor&&(i.__compiledEditor=Fe(i.__editorTemplate.innerHTML))});const{columns:n}=De(o._rows,t);o._columns=n}function qe(o){const e=o.effectiveConfig?.fitMode||o.fitMode||$.STRETCH;if(e!==$.STRETCH&&e!==$.FIXED||o.__didInitialAutoSize||!o.isConnected)return;const t=o._headerRowEl?.children||[];if(!t.length)return;let n=!1;o._visibleColumns.forEach((i,r)=>{if(i.width)return;const s=t[r];let l=s?s.scrollWidth:0;for(const a of o._rowPool){const c=a.children[r];if(c){const d=c.scrollWidth;d>l&&(l=d)}}l>0&&(i.width=l+2,i.__autoSized=!0,n=!0)}),n&&B(o),o.__didInitialAutoSize=!0}function B(o){(o.effectiveConfig?.fitMode||o.fitMode||$.STRETCH)===$.STRETCH?o._gridTemplate=o._visibleColumns.map(t=>{if(t.width)return`${t.width}px`;const n=t.minWidth;return n!=null?`minmax(${n}px, 1fr)`:"1fr"}).join(" ").trim():o._gridTemplate=o._visibleColumns.map(t=>t.width?`${t.width}px`:"max-content").join(" "),o.style.setProperty("--tbw-column-template",o._gridTemplate)}function Xt(o){switch(o.type){case"number":return e=>{const t=document.createElement("input");return t.type="number",t.value=e.value!=null?String(e.value):"",t.addEventListener("blur",()=>e.commit(t.value===""?null:Number(t.value))),t.addEventListener("keydown",n=>{n.key==="Enter"&&e.commit(t.value===""?null:Number(t.value)),n.key==="Escape"&&e.cancel()}),t.focus(),t};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.focus(),t};case"date":return e=>{const t=document.createElement("input");return t.type="date",e.value instanceof Date&&(t.valueAsDate=e.value),t.addEventListener("change",()=>e.commit(t.valueAsDate)),t.addEventListener("keydown",n=>{n.key==="Escape"&&e.cancel()}),t.focus(),t};case"select":case"typeahead":return e=>{const t=document.createElement("select");e.column.multi&&(t.multiple=!0),(typeof e.column.options=="function"?e.column.options():e.column.options||[]).forEach(r=>{const s=document.createElement("option");s.value=String(r.value),s.textContent=r.label,(e.column.multi&&Array.isArray(e.value)&&e.value.includes(r.value)||!e.column.multi&&e.value===r.value)&&(s.selected=!0),t.appendChild(s)});const i=()=>{if(e.column.multi){const r=[];Array.from(t.selectedOptions).forEach(s=>{r.push(s.value)}),e.commit(r)}else e.commit(t.value)};return t.addEventListener("change",i),t.addEventListener("blur",i),t.addEventListener("keydown",r=>{r.key==="Escape"&&e.cancel()}),t.focus(),t};default:return e=>{const t=document.createElement("input");return t.type="text",t.value=e.value!=null?String(e.value):"",t.addEventListener("blur",()=>e.commit(t.value)),t.addEventListener("keydown",n=>{n.key==="Enter"&&e.commit(t.value),n.key==="Escape"&&e.cancel()}),t.focus(),t}}}function Yt(o,e){if(o._dispatchKeyDown?.(e))return;const t=o._rows.length-1,n=o._visibleColumns.length-1,i=o._activeEditRows!==void 0&&o._activeEditRows!==-1,s=o._visibleColumns[o._focusCol]?.type,l=e.composedPath?e.composedPath():[],a=l&&l.length?l[0]:e.target,c=d=>{if(!d)return!1;const u=d.tagName;return!!(u==="INPUT"||u==="SELECT"||u==="TEXTAREA"||d.isContentEditable)};if(!(c(a)&&(e.key==="Home"||e.key==="End"))&&!(c(a)&&(e.key==="ArrowUp"||e.key==="ArrowDown")&&a.tagName==="INPUT"&&a.type==="number")&&!(c(a)&&(e.key==="ArrowLeft"||e.key==="ArrowRight"))&&!(c(a)&&(e.key==="Enter"||e.key==="Escape"))&&!(i&&(s==="select"||s==="typeahead")&&(e.key==="ArrowDown"||e.key==="ArrowUp"))){switch(e.key){case"Tab":{e.preventDefault(),!e.shiftKey?o._focusCol<n?o._focusCol+=1:(typeof o.commitActiveRowEdit=="function"&&o.commitActiveRowEdit(),o._focusRow<t&&(o._focusRow+=1,o._focusCol=0)):o._focusCol>0?o._focusCol-=1:o._focusRow>0&&(typeof o.commitActiveRowEdit=="function"&&o._activeEditRows===o._focusRow&&o.commitActiveRowEdit(),o._focusRow-=1,o._focusCol=n),O(o);return}case"ArrowDown":i&&typeof o.commitActiveRowEdit=="function"&&o.commitActiveRowEdit(),o._focusRow=Math.min(t,o._focusRow+1),e.preventDefault();break;case"ArrowUp":i&&typeof o.commitActiveRowEdit=="function"&&o.commitActiveRowEdit(),o._focusRow=Math.max(0,o._focusRow-1),e.preventDefault();break;case"ArrowRight":o._focusCol=Math.min(n,o._focusCol+1),e.preventDefault();break;case"ArrowLeft":o._focusCol=Math.max(0,o._focusCol-1),e.preventDefault();break;case"Home":(e.ctrlKey||e.metaKey)&&(i&&typeof o.commitActiveRowEdit=="function"&&o.commitActiveRowEdit(),o._focusRow=0),o._focusCol=0,e.preventDefault(),O(o,{forceScrollLeft:!0});return;case"End":(e.ctrlKey||e.metaKey)&&(i&&typeof o.commitActiveRowEdit=="function"&&o.commitActiveRowEdit(),o._focusRow=t),o._focusCol=n,e.preventDefault(),O(o,{forceScrollRight:!0});return;case"PageDown":o._focusRow=Math.min(t,o._focusRow+20),e.preventDefault();break;case"PageUp":o._focusRow=Math.max(0,o._focusRow-20),e.preventDefault();break;case"Enter":return typeof o.beginBulkEdit=="function"?o.beginBulkEdit(o._focusRow):o.dispatchEvent(new CustomEvent("activate-cell",{detail:{row:o._focusRow,col:o._focusCol}})),O(o);default:return}O(o)}}function O(o,e){if(o._virtualization?.enabled){const{rowHeight:s,container:l,viewportEl:a}=o._virtualization,c=l,d=a?.clientHeight??c?.clientHeight??0;if(c&&d>0){const u=o._focusRow*s;u<c.scrollTop?c.scrollTop=u:u+s>c.scrollTop+d&&(c.scrollTop=u-d+s)}}o._activeEditRows!==void 0&&o._activeEditRows!==-1||o.refreshVirtualWindow(!1),Array.from(o._bodyEl.querySelectorAll(".cell-focus")).forEach(s=>s.classList.remove("cell-focus")),Array.from(o._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(s=>{s.setAttribute("aria-selected","false")});const n=o._focusRow,i=o._virtualization.start??0,r=o._virtualization.end??o._rows.length;if(n>=i&&n<r){const s=o._bodyEl.querySelectorAll(".data-grid-row")[n-i],l=s?.children[o._focusCol];if(l){l.classList.add("cell-focus"),l.setAttribute("aria-selected","true");const a=o.shadowRoot?.querySelector(".tbw-scroll-area");if(a&&l)if(e?.forceScrollLeft)a.scrollLeft=0;else if(e?.forceScrollRight)a.scrollLeft=a.scrollWidth-a.clientWidth;else{const c=o._getHorizontalScrollOffsets?.(s??void 0,l)??{left:0,right:0};if(!c.skipScroll){const d=l.getBoundingClientRect(),u=a.getBoundingClientRect(),f=d.left-u.left+a.scrollLeft,h=f+d.width,p=a.scrollLeft+c.left,g=a.scrollLeft+a.clientWidth-c.right;f<p?a.scrollLeft=f-c.left:h>g&&(a.scrollLeft=h-a.clientWidth+c.right)}}if(o._activeEditRows!==void 0&&o._activeEditRows!==-1&&l.classList.contains("editing")){const c=l.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');if(c&&document.activeElement!==c)try{c.focus()}catch{}}else if(!l.contains(document.activeElement)){l.hasAttribute("tabindex")||l.setAttribute("tabindex","-1");try{l.focus({preventScroll:!0})}catch{}}}}}const Zt="__cellDisplayCache",Jt="__cellCacheEpoch";function ae(o){o[Zt]=void 0,o[Jt]=void 0,o.__hasSpecialColumns=void 0}function Qt(o,e,t,n,i){const r=Math.max(0,t-e),s=o._bodyEl,l=o._visibleColumns,a=l.length;let c=o.__cachedHeaderRowCount;for(c===void 0&&(c=o.shadowRoot?.querySelector(".header-group-row")?2:1,o.__cachedHeaderRowCount=c);o._rowPool.length<r;){const u=document.createElement("div");u.className="data-grid-row",u.setAttribute("role","row"),u.addEventListener("click",f=>Be(o,f,u,!1)),u.addEventListener("dblclick",f=>Be(o,f,u,!0)),o._rowPool.push(u)}if(o._rowPool.length>r){for(let u=r;u<o._rowPool.length;u++){const f=o._rowPool[u];f.parentNode===s&&f.remove()}o._rowPool.length=r}const d=i&&o.__hasRenderRowPlugins!==!1;for(let u=0;u<r;u++){const f=e+u,h=o._rows[f],p=o._rowPool[u];if(p.setAttribute("aria-rowindex",String(f+c+1)),d&&i(h,p,f)){p.__epoch=n,p.__rowDataRef=h,p.parentNode!==s&&s.appendChild(p);continue}const g=p.__epoch,w=p.__rowDataRef,y=p.children.length,T=g===n&&y===a,S=w!==h;let b=!1;if(T&&S){for(let E=0;E<a;E++)if(l[E].externalView&&!p.querySelector(`.cell[data-col="${E}"] [data-external-view]`)){b=!0;break}}if(!T||b){const E=p.querySelector(".cell.editing"),v=o._activeEditRows===f;if(E&&!v)p.__isCustomRow&&(p.className="data-grid-row",p.setAttribute("role","row"),p.__isCustomRow=!1),G(o,p,h,f),p.__epoch=n,p.__rowDataRef=h;else if(E&&v)ce(o,p,h,f),p.__rowDataRef=h;else if(p.__isCustomRow&&(p.className="data-grid-row",p.setAttribute("role","row"),p.__isCustomRow=!1),G(o,p,h,f),p.__epoch=n,p.__rowDataRef=h,v){const x=p.children;for(let _=0;_<x.length;_++){const k=o._visibleColumns[_];k&&k.editable&&D(o,h,f,k,x[_])}}}else if(S){const E=p.querySelector(".cell.editing"),v=o._activeEditRows===f;if(E&&!v)G(o,p,h,f),p.__epoch=n,p.__rowDataRef=h;else if(ce(o,p,h,f),p.__rowDataRef=h,v&&!E){const x=p.children;for(let _=0;_<x.length;_++){const k=o._visibleColumns[_];k&&k.editable&&D(o,h,f,k,x[_])}}}else{const E=p.querySelector(".cell.editing"),v=o._activeEditRows===f;if(E&&!v)G(o,p,h,f),p.__epoch=n,p.__rowDataRef=h;else if(ce(o,p,h,f),v&&!E){const x=p.children;for(let _=0;_<x.length;_++){const k=o._visibleColumns[_];k&&k.editable&&D(o,h,f,k,x[_])}}}const m=o._changedRowIndices.has(f),A=p.classList.contains("changed");m!==A&&p.classList.toggle("changed",m),p.parentNode!==s&&s.appendChild(p)}}function ce(o,e,t,n){const i=e.children,r=o._visibleColumns,s=r.length,l=i.length,a=s<l?s:l,c=o._focusRow,d=o._focusCol;let u=o.__hasSpecialColumns;if(u===void 0){u=!1;for(let h=0;h<s;h++){const p=r[h];if(p.__viewTemplate||p.__compiledView||p.viewRenderer||p.externalView||p.format||p.type==="date"||p.type==="boolean"){u=!0;break}}o.__hasSpecialColumns=u}const f=String(n);if(!u){for(let h=0;h<a;h++){const p=i[h],g=t[r[h].field];p.textContent=g==null?"":String(g),p.getAttribute("data-row")!==f&&p.setAttribute("data-row",f);const w=c===n&&d===h,y=p.classList.contains("cell-focus");w!==y&&(p.classList.toggle("cell-focus",w),p.setAttribute("aria-selected",String(w)))}return}for(let h=0;h<a;h++)if(r[h].externalView&&!i[h].querySelector("[data-external-view]")){G(o,e,t,n);return}for(let h=0;h<a;h++){const p=r[h],g=i[h];g.getAttribute("data-row")!==f&&g.setAttribute("data-row",f);const w=c===n&&d===h,y=g.classList.contains("cell-focus");if(w!==y&&(g.classList.toggle("cell-focus",w),g.setAttribute("aria-selected",String(w))),g.classList.contains("editing"))continue;if(p.viewRenderer){const S=t[p.field],b=p.viewRenderer({row:t,value:S,field:p.field,column:p});typeof b=="string"?g.innerHTML=ie(b):b?(g.innerHTML="",g.appendChild(b)):g.textContent=S==null?"":String(S);continue}if(p.__viewTemplate||p.__compiledView||p.externalView)continue;const R=t[p.field];let T;if(p.format)try{const S=p.format(R,t);T=S==null?"":String(S)}catch{T=R==null?"":String(R)}else if(p.type==="date"){if(R==null||R==="")T="";else if(R instanceof Date)T=isNaN(R.getTime())?"":R.toLocaleDateString();else{const S=new Date(R);T=isNaN(S.getTime())?"":S.toLocaleDateString()}g.textContent=T}else if(p.type==="boolean"){const S=!!R;g.innerHTML=`<span role="checkbox" aria-checked="${S}" aria-label="${S}">${S?"&#x1F5F9;":"&#9744;"}</span>`}else T=R==null?"":String(R),g.textContent=T}}function G(o,e,t,n){e.innerHTML="";const i=o._visibleColumns,r=i.length,s=o._focusRow,l=o._focusCol,a=o.effectiveConfig?.editOn||o.editOn,c=o,d=document.createDocumentFragment();for(let u=0;u<r;u++){const f=i[u],h=document.createElement("div");h.className="cell",le(h,"cell"),h.setAttribute("role","gridcell"),h.setAttribute("aria-colindex",String(u+1)),h.setAttribute("data-col",String(u)),h.setAttribute("data-row",String(n)),h.setAttribute("data-field",f.field),f.type,f.type&&h.setAttribute("data-type",f.type);let p=t[f.field];const g=f.format;if(g)try{p=g(p,t)}catch{}const w=f.__compiledView,y=f.__viewTemplate,R=f.viewRenderer,T=f.externalView;let S=!1;if(R){const b=R({row:t,value:p,field:f.field,column:f});typeof b=="string"?(h.innerHTML=ie(b),S=!0):b?h.appendChild(b):h.textContent=p==null?"":String(p)}else if(T){const b=T,m=document.createElement("div");m.setAttribute("data-external-view",""),m.setAttribute("data-field",f.field),h.appendChild(m);const A={row:t,value:p,field:f.field,column:f};if(b.mount)try{b.mount({placeholder:m,context:A,spec:b})}catch{}else queueMicrotask(()=>{try{c.dispatchEvent(new CustomEvent("mount-external-view",{bubbles:!0,composed:!0,detail:{placeholder:m,spec:b,context:A}}))}catch{}});m.setAttribute("data-mounted","")}else if(w){const b=w({row:t,value:p,field:f.field,column:f}),m=w.__blocked;h.innerHTML=m?"":ie(b),S=!0,m&&(h.textContent="",h.setAttribute("data-blocked-template",""))}else if(y){const b=y.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(b)?(h.textContent="",h.setAttribute("data-blocked-template","")):(h.innerHTML=ie(ze(b,{row:t,value:p})),S=!0)}else if(f.type==="date")if(p==null||p==="")h.textContent="";else{let b=null;if(p instanceof Date)b=p;else if(typeof p=="number"||typeof p=="string"){const m=new Date(p);isNaN(m.getTime())||(b=m)}h.textContent=b?b.toLocaleDateString():""}else if(f.type==="boolean"){const b=!!p;h.innerHTML=`<span role="checkbox" aria-checked="${b}" aria-label="${b}">${b?"&#x1F5F9;":"&#9744;"}</span>`}else h.textContent=p==null?"":String(p);if(S){Gt(h);const b=h.textContent||"";/Proxy|Reflect\.ownKeys/.test(b)&&(h.textContent=b.replace(/Proxy|Reflect\.ownKeys/g,"").trim(),/Proxy|Reflect\.ownKeys/.test(h.textContent||"")&&(h.textContent=""))}h.hasAttribute("data-blocked-template")&&(h.textContent||"").trim().length&&(h.textContent=""),f.editable?(h.tabIndex=0,h.addEventListener("mousedown",()=>{if(h.classList.contains("editing"))return;const b=Number(h.getAttribute("data-row")),m=Number(h.getAttribute("data-col"));isNaN(b)||isNaN(m)||(o._focusRow=b,o._focusCol=m,O(o))}),a==="click"?h.addEventListener("click",b=>{if(h.classList.contains("editing"))return;b.stopPropagation();const m=Number(h.getAttribute("data-row")),A=Number(h.getAttribute("data-col"));if(isNaN(m)||isNaN(A))return;const E=o._rows[m],v=o._visibleColumns[A];!E||!v||(o._focusRow=m,o._focusCol=A,D(o,E,m,v,h))}):h.addEventListener("dblclick",b=>{b.stopPropagation();const m=Number(h.getAttribute("data-row"));if(isNaN(m))return;const A=o._rows[m];if(!A)return;W(o,m,A);const E=o.findRenderedRowElement?.(m);if(E){const v=E.children;for(let x=0;x<v.length;x++){const _=o._visibleColumns[x];_&&_.editable&&D(o,A,m,_,v[x])}}}),h.addEventListener("keydown",b=>{const m=Number(h.getAttribute("data-row")),A=Number(h.getAttribute("data-col"));if(isNaN(m)||isNaN(A))return;const E=o._rows[m],v=o._visibleColumns[A];if(!(!E||!v)){if((v.type==="select"||v.type==="typeahead")&&!h.classList.contains("editing")&&b.key==="Enter"){b.preventDefault(),o._activeEditRows!==m&&W(o,m,E),D(o,E,m,v,h),setTimeout(()=>{const x=h.querySelector("select");try{x?.showPicker?.()}catch{}x?.focus()},0);return}if(v.type==="boolean"&&b.key===" "&&!h.classList.contains("editing")){b.preventDefault(),o._activeEditRows!==m&&W(o,m,E);const x=!E[v.field];ue(o,m,v,x,E),h.innerHTML=`<span role="checkbox" aria-checked="${x}" aria-label="${x}">${x?"&#x1F5F9;":"&#9744;"}</span>`;return}if(b.key==="Enter"&&!h.classList.contains("editing")){b.preventDefault(),b.stopPropagation(),o._focusRow=m,o._focusCol=A,typeof o.beginBulkEdit=="function"?o.beginBulkEdit(m):D(o,E,m,v,h);return}if(b.key==="F2"&&!h.classList.contains("editing")){b.preventDefault(),D(o,E,m,v,h);return}}})):f.type==="boolean"&&(h.hasAttribute("tabindex")||(h.tabIndex=0)),s===n&&l===u?(h.classList.add("cell-focus"),h.setAttribute("aria-selected","true")):h.setAttribute("aria-selected","false"),d.appendChild(h)}e.appendChild(d)}function Be(o,e,t,n){if(e.target?.closest(".resize-handle"))return;const i=t.querySelector(".cell[data-row]");if(!i)return;const r=Number(i.getAttribute("data-row"));if(isNaN(r))return;const s=o._rows[r];if(!s||o._dispatchRowClick?.(e,r,s,t))return;const l=e.target?.closest(".cell[data-col]");if(l){if(l.classList.contains("editing"))return;const c=Number(l.getAttribute("data-col"));if(!isNaN(c)){if(o._dispatchCellClick?.(e,r,c,l))return;o._focusRow=r,o._focusCol=c,O(o)}}if(t.querySelector(".cell.editing")){const c=t.querySelectorAll(".cell.editing");if(!n)return;c.forEach(d=>d.classList.remove("editing"))}const a=o.effectiveConfig?.editOn||o.editOn||"doubleClick";if(a==="click"||a==="doubleClick"&&n)W(o,r,s);else return;Array.from(t.children).forEach((c,d)=>{const u=o._visibleColumns[d];u&&u.editable&&D(o,s,r,u,c)}),l&&queueMicrotask(()=>{const c=t.querySelector(`.cell[data-col="${o._focusCol}"]`);if(c?.classList.contains("editing")){const d=c.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');try{d?.focus()}catch{}}})}function de(o){return!(o==="__proto__"||o==="constructor"||o==="prototype")}function W(o,e,t){o._activeEditRows!==e&&(o._rowEditSnapshots.set(e,{...t}),o._activeEditRows=e)}function K(o,e,t){if(o._activeEditRows!==e)return;const n=o._rowEditSnapshots.get(e),i=o._rows[e],r=o.findRenderedRowElement?.(e);if(!t&&r&&i&&r.querySelectorAll(".cell.editing").forEach(l=>{const a=Number(l.getAttribute("data-col"));if(isNaN(a))return;const c=o._visibleColumns[a];if(!c)return;const d=l.querySelector("input,textarea,select");if(d){let u;d instanceof HTMLInputElement&&d.type==="checkbox"?u=d.checked:(u=d.value,c.type==="number"&&u!==""&&(u=Number(u))),i[c.field]!==u&&ue(o,e,c,u,i)}}),t&&n&&i)Object.keys(n).forEach(s=>i[s]=n[s]),o._changedRowIndices.delete(e),ae(o);else if(!t){const s=o._changedRowIndices.has(e);o.dispatchEvent(new CustomEvent("row-commit",{detail:{rowIndex:e,row:i,changed:s,changedRows:o.changedRows,changedRowIndices:o.changedRowIndices}}))}o._rowEditSnapshots.delete(e),o._activeEditRows=-1,r&&(G(o,r,o._rows[e],e),o._changedRowIndices.has(e)?r.classList.add("changed"):r.classList.remove("changed")),queueMicrotask(()=>{try{const s=o._focusRow,l=o._focusCol,a=o.findRenderedRowElement?.(s);if(a){Array.from(o._bodyEl.querySelectorAll(".cell-focus")).forEach(d=>d.classList.remove("cell-focus"));const c=a.querySelector(`.cell[data-row="${s}"][data-col="${l}"]`);c&&(c.classList.add("cell-focus"),c.setAttribute("aria-selected","true"),c.hasAttribute("tabindex")||c.setAttribute("tabindex","-1"),c.focus({preventScroll:!0}))}}catch{}})}function ue(o,e,t,n,i){const r=t.field;if(!de(r)||i[r]===n)return;i[r]=n;const l=!o._changedRowIndices.has(e);o._changedRowIndices.add(e);const a=o.findRenderedRowElement?.(e);a&&a.classList.add("changed"),o.dispatchEvent(new CustomEvent("cell-commit",{detail:{row:i,field:r,value:n,rowIndex:e,changedRows:o.changedRows,changedRowIndices:o.changedRowIndices,firstTimeForRow:l}}))}function D(o,e,t,n,i){if(!n.editable||(o._activeEditRows!==t&&W(o,t,e),i.classList.contains("editing")))return;const r=de(n.field)?e[n.field]:void 0;i.classList.add("editing");let s=!1;const l=h=>{s||o._activeEditRows===-1||ue(o,t,n,h,e)},a=()=>{s=!0,e[n.field]=de(n.field)?r:void 0;const h=i.querySelector("input,textarea,select");h&&(typeof HTMLInputElement<"u"&&h instanceof HTMLInputElement&&h.type==="checkbox"?h.checked=!!r:"value"in h&&(h.value=r??""))},c=document.createElement("div");c.style.display="contents",i.innerHTML="",i.appendChild(c),c.addEventListener("keydown",h=>{h.key==="Enter"&&(h.stopPropagation(),h.preventDefault(),s=!0,K(o,t,!1)),h.key==="Escape"&&(h.stopPropagation(),h.preventDefault(),a(),K(o,t,!0))});const d=n.__editorTemplate,u=n.editor||(d?"template":Xt(n)),f=r;if(u==="template"&&d){const h=d.cloneNode(!0),p=n.__compiledEditor;p?h.innerHTML=p({row:e,value:r,field:n.field,column:n}):h.querySelectorAll("*").forEach(w=>{w.childNodes.length===1&&w.firstChild?.nodeType===Node.TEXT_NODE&&(w.textContent=w.textContent?.replace(/{{\s*value\s*}}/g,r==null?"":String(r)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(y,R)=>{const T=e[R];return T==null?"":String(T)})||"")});const g=h.querySelector("input,textarea,select");if(g){const w=typeof HTMLInputElement<"u";w&&g instanceof HTMLInputElement&&g.type==="checkbox"?g.checked=!!r:"value"in g&&(g.value=r??""),g.addEventListener("blur",()=>{const y=w&&g instanceof HTMLInputElement&&g.type==="checkbox"?g.checked:g.value;l(y)}),g.addEventListener("keydown",y=>{if(y.key==="Enter"){y.stopPropagation(),y.preventDefault(),s=!0;const R=w&&g instanceof HTMLInputElement&&g.type==="checkbox"?g.checked:g.value;l(R),K(o,t,!1)}y.key==="Escape"&&(y.stopPropagation(),y.preventDefault(),a(),K(o,t,!0))}),w&&g instanceof HTMLInputElement&&g.type==="checkbox"&&g.addEventListener("change",()=>{const y=g.checked;l(y)}),setTimeout(()=>g.focus(),0)}c.appendChild(h)}else if(typeof u=="string"){const h=document.createElement(u);h.value=f,h.addEventListener("change",()=>l(h.value)),c.appendChild(h)}else if(typeof u=="function"){const h=u({row:e,value:f,field:n.field,column:n,commit:l,cancel:a});typeof h=="string"?c.innerHTML=h:c.appendChild(h)}else if(u&&typeof u=="object"){const h=document.createElement("div");h.setAttribute("data-external-editor",""),h.setAttribute("data-field",n.field),c.appendChild(h);const p={row:e,value:f,field:n.field,column:n,commit:l,cancel:a};if(u.mount)try{u.mount({placeholder:h,context:p,spec:u})}catch{}else o.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:h,spec:u,context:p}}))}}function Ke(o,e){return o==null&&e==null?0:o==null?-1:e==null||o>e?1:o<e?-1:0}function Ve(o,e,t){const i=t.find(l=>l.field===e.field)?.sortComparator??Ke,{field:r,direction:s}=e;return[...o].sort((l,a)=>i(l[r],a[r],l,a)*s)}function $e(o,e,t,n){o._rows=e,o.__rowRenderEpoch++,o._rowPool.forEach(i=>i.__epoch=-1),U(o),o.refreshVirtualWindow(!0),o.dispatchEvent(new CustomEvent("sort-change",{detail:{field:t.field,direction:n}})),o.requestStateChange?.()}function Ge(o,e){!o._sortState||o._sortState.field!==e.field?(o._sortState||(o.__originalOrder=o._rows.slice()),We(o,e,1)):o._sortState.direction===1?We(o,e,-1):(o._sortState=null,o.__rowRenderEpoch++,o._rowPool.forEach(n=>n.__epoch=-1),o._rows=o.__originalOrder.slice(),U(o),o._headerRowEl?.querySelectorAll('[role="columnheader"].sortable')?.forEach(n=>{n.getAttribute("aria-sort")?(n.getAttribute("aria-sort")==="ascending"||n.getAttribute("aria-sort")==="descending")&&(o._sortState||n.setAttribute("aria-sort","none")):n.setAttribute("aria-sort","none")}),o.refreshVirtualWindow(!0),o.dispatchEvent(new CustomEvent("sort-change",{detail:{field:e.field,direction:0}})),o.requestStateChange?.())}function We(o,e,t){o._sortState={field:e.field,direction:t};const n={field:e.field,direction:t},i=o._columns,s=(o.effectiveConfig?.sortHandler??Ve)(o._rows,n,i);s&&typeof s.then=="function"?s.then(l=>{$e(o,l,e,t)}):$e(o,s,e,t)}function eo(o,e){typeof e=="string"?o.textContent=e:e instanceof HTMLElement&&(o.innerHTML="",o.appendChild(e.cloneNode(!0)))}function U(o){o._headerRowEl=o.findHeaderRow();const e=o._headerRowEl;e.innerHTML="",o._visibleColumns.forEach((t,n)=>{const i=document.createElement("div");i.className="cell",le(i,"header-cell"),i.setAttribute("role","columnheader"),i.setAttribute("aria-colindex",String(n+1)),i.setAttribute("data-field",t.field),i.setAttribute("data-col",String(n));const r=t.__headerTemplate;if(r)Array.from(r.childNodes).forEach(s=>i.appendChild(s.cloneNode(!0)));else{const s=t.header||t.field,l=document.createElement("span");l.textContent=s,i.appendChild(l)}if(t.sortable){i.classList.add("sortable"),i.tabIndex=0;const s=document.createElement("span");le(s,"sort-indicator");const l=o._sortState?.field===t.field?o._sortState.direction:0,a={...I,...o.icons},c=l===1?a.sortAsc:l===-1?a.sortDesc:a.sortNone;eo(s,c),i.appendChild(s),i.setAttribute("aria-sort",l===0?"none":l===1?"ascending":"descending"),i.addEventListener("click",d=>{o._resizeController?.isResizing||o._dispatchHeaderClick?.(d,n,i)||Ge(o,t)}),i.addEventListener("keydown",d=>{if(d.key==="Enter"||d.key===" "){if(d.preventDefault(),o._dispatchHeaderClick?.(d,n,i))return;Ge(o,t)}})}if(t.resizable){i.style.position="relative";const s=document.createElement("div");s.className="resize-handle",s.setAttribute("aria-hidden","true"),s.addEventListener("mousedown",l=>{l.stopPropagation(),l.preventDefault(),o._resizeController.start(l,n,i)}),s.addEventListener("dblclick",l=>{l.stopPropagation(),l.preventDefault(),o._resizeController.resetColumn(n)}),i.appendChild(s)}e.appendChild(i)}),e.querySelectorAll(".cell.sortable").forEach(t=>{t.getAttribute("aria-sort")||t.setAttribute("aria-sort","none")}),e.children.length>0?(e.setAttribute("role","row"),e.setAttribute("aria-rowindex","1")):(e.removeAttribute("role"),e.removeAttribute("aria-rowindex"))}function to(o){let e=null,t=null,n=null,i=null;const r=a=>{if(!e)return;const c=a.clientX-e.startX,d=Math.max(40,e.startWidth+c),u=o._visibleColumns[e.colIndex];u.width=d,u.__userResized=!0,u.__renderedWidth=d,t==null&&(t=requestAnimationFrame(()=>{t=null,o.updateTemplate?.()})),o.dispatchEvent(new CustomEvent("column-resize",{detail:{field:u.field,width:d}}))};let s=!1;const l=()=>{const a=e!==null;a&&(s=!0,requestAnimationFrame(()=>{s=!1})),window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",l),n!==null&&(document.documentElement.style.cursor=n,n=null),i!==null&&(document.body.style.userSelect=i,i=null),e=null,a&&o.requestStateChange&&o.requestStateChange()};return{get isResizing(){return e!==null||s},start(a,c,d){a.preventDefault();const u=d.getBoundingClientRect();e={startX:a.clientX,colIndex:c,startWidth:u.width},window.addEventListener("mousemove",r),window.addEventListener("mouseup",l),n===null&&(n=document.documentElement.style.cursor),document.documentElement.style.cursor="e-resize",i===null&&(i=document.body.style.userSelect),document.body.style.userSelect="none"},resetColumn(a){const c=o._visibleColumns[a];c&&(c.__userResized=!1,c.__renderedWidth=void 0,c.width=c.__originalWidth,o.updateTemplate?.(),o.requestStateChange?.(),o.dispatchEvent(new CustomEvent("column-resize-reset",{detail:{field:c.field,width:c.width}})))},dispose(){l()}}}function Q(o){return o?typeof o=="string"?o:o.outerHTML:""}function oo(){return{toolPanels:new Map,headerContents:new Map,toolbarButtons:new Map,lightDomButtons:[],lightDomHeaderContent:[],isPanelOpen:!1,expandedSections:new Set,headerContentCleanups:new Map,panelCleanups:new Map,toolbarButtonCleanups:new Map,activePanel:null,activePanelCleanup:null}}function no(o,e){return!!(o?.header?.title||o?.header?.toolbarButtons?.length||e.toolPanels.size>0||e.headerContents.size>0||e.toolbarButtons.size>0||e.lightDomButtons.length>0||e.lightDomHeaderContent.length>0)}function io(o,e,t="☰"){const n=o?.header?.title??"",i=!!n,r=Q(t),s=o?.header?.toolbarButtons??[],l=s.length>0,a=e.toolbarButtons.size>0,c=e.lightDomButtons.length>0,d=e.toolPanels.size>0,f=(l||a||c)&&d,h=[...s].sort((w,y)=>(w.order??100)-(y.order??100)),p=[...e.toolbarButtons.values()].sort((w,y)=>(w.order??100)-(y.order??100));let g="";for(const w of h)w.icon&&w.action&&(g+=`<button class="tbw-toolbar-btn" data-btn="${w.id}" title="${w.label}" aria-label="${w.label}"${w.disabled?" disabled":""}>${w.icon}</button>`);for(const w of p)w.icon&&w.action&&(g+=`<button class="tbw-toolbar-btn" data-btn="${w.id}" title="${w.label}" aria-label="${w.label}"${w.disabled?" disabled":""}>${w.icon}</button>`);for(const w of h)(w.element||w.render)&&(g+=`<div class="tbw-toolbar-btn-slot" data-btn-slot="${w.id}"></div>`);for(const w of p)(w.element||w.render)&&(g+=`<div class="tbw-toolbar-btn-slot" data-btn-slot="${w.id}"></div>`);if(c&&(g+='<slot name="toolbar"></slot>'),f&&(g+='<div class="tbw-toolbar-separator"></div>'),d){const w=e.isPanelOpen;g+=`<button class="tbw-toolbar-btn${w?" active":""}" data-panel-toggle title="Settings" aria-label="Toggle settings panel" aria-pressed="${w}" aria-controls="tbw-tool-panel">${r}</button>`}return`
2
2
  <div class="tbw-shell-header" part="shell-header" role="presentation">
3
3
  ${i?`<div class="tbw-shell-title">${n}</div>`:""}
4
4
  <div class="tbw-shell-content" part="shell-content" role="presentation">
@@ -41,7 +41,7 @@
41
41
  ${h}
42
42
  </div>
43
43
  `}function Ue(o,e){const t=o.querySelector("tbw-grid-header");if(!t)return;t.style.display="none";const n=t.querySelectorAll("tbw-grid-header-content");e.lightDomHeaderContent=Array.from(n),e.lightDomHeaderContent.forEach(r=>{r.setAttribute("slot","header-content")});const i=t.querySelectorAll("tbw-grid-tool-button");e.lightDomButtons=Array.from(i),e.lightDomButtons.sort((r,s)=>{const l=parseInt(r.getAttribute("order")??"100",10),a=parseInt(s.getAttribute("order")??"100",10);return l-a}),e.lightDomButtons.forEach(r=>{r.setAttribute("slot","toolbar")})}function so(o,e,t,n){const i=o.querySelector(".tbw-shell-toolbar");i&&i.addEventListener("click",s=>{const l=s.target;if(l.closest("[data-panel-toggle]")){n.onPanelToggle();return}const c=l.closest("[data-btn]");if(c){const d=c.getAttribute("data-btn");d&&n.onToolbarButtonClick(d)}});const r=o.querySelector(".tbw-accordion");r&&r.addEventListener("click",s=>{const a=s.target.closest(".tbw-accordion-header");if(a){const d=a.closest("[data-section]")?.getAttribute("data-section");d&&n.onSectionToggle(d)}})}function lo(o,e,t){const n=o.querySelector(".tbw-tool-panel"),i=o.querySelector("[data-resize-handle]"),r=o.querySelector(".tbw-shell-body");if(!n||!i||!r)return()=>{};const s=e?.toolPanel?.position??"right",l=200;let a=0,c=0,d=0,u=!1;const f=g=>{if(!u)return;g.preventDefault();const w=s==="left"?g.clientX-a:a-g.clientX,y=Math.min(d,Math.max(l,c+w));n.style.width=`${y}px`},h=()=>{if(!u)return;u=!1,i.classList.remove("resizing"),n.style.transition="",document.body.style.cursor="",document.body.style.userSelect="";const g=n.getBoundingClientRect().width;t(g),document.removeEventListener("mousemove",f),document.removeEventListener("mouseup",h)},p=g=>{g.preventDefault(),u=!0,a=g.clientX,c=n.getBoundingClientRect().width,d=r.getBoundingClientRect().width-20,i.classList.add("resizing"),n.style.transition="none",document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",f),document.addEventListener("mouseup",h)};return i.addEventListener("mousedown",p),()=>{i.removeEventListener("mousedown",p),document.removeEventListener("mousemove",f),document.removeEventListener("mouseup",h)}}function ao(o,e,t){const n=[...e?.header?.toolbarButtons??[],...t.toolbarButtons.values()];for(const i of n){const r=o.querySelector(`[data-btn-slot="${i.id}"]`);if(!r)continue;const s=t.toolbarButtonCleanups.get(i.id);if(s&&(s(),t.toolbarButtonCleanups.delete(i.id)),i.element)r.appendChild(i.element);else if(i.render){const l=i.render(r);l&&t.toolbarButtonCleanups.set(i.id,l)}}}function je(o,e){const t=o.querySelector(".tbw-shell-content");if(!t)return;const n=[...e.headerContents.values()].sort((r,s)=>(r.order??100)-(s.order??100)),i=t.querySelector('slot[name="header-content"]');for(const r of n){const s=e.headerContentCleanups.get(r.id);s&&(s(),e.headerContentCleanups.delete(r.id));let l=t.querySelector(`[data-header-content="${r.id}"]`);l||(l=document.createElement("div"),l.setAttribute("data-header-content",r.id),i?t.insertBefore(l,i):t.appendChild(l));const a=r.render(l);a&&e.headerContentCleanups.set(r.id,a)}}function co(o,e,t){if(!e.isPanelOpen)return;const n=Q(t?.expand??I.expand),i=Q(t?.collapse??I.collapse);for(const[r,s]of e.toolPanels){const l=e.expandedSections.has(r),a=o.querySelector(`[data-section="${r}"]`),c=a?.querySelector(".tbw-accordion-content");if(!a||!c)continue;a.classList.toggle("expanded",l);const d=a.querySelector(".tbw-accordion-header");d&&d.setAttribute("aria-expanded",String(l));const u=a.querySelector(".tbw-accordion-chevron");if(u&&(u.innerHTML=l?i:n),l){if(c.children.length===0){const f=s.render(c);f&&e.panelCleanups.set(r,f)}}else{const f=e.panelCleanups.get(r);f&&(f(),e.panelCleanups.delete(r)),c.innerHTML=""}}}function Xe(o,e){const t=o.querySelector("[data-panel-toggle]");t&&(t.classList.toggle("active",e.isPanelOpen),t.setAttribute("aria-pressed",String(e.isPanelOpen)))}function Ye(o,e){const t=o.querySelector(".tbw-tool-panel");t&&(t.classList.toggle("open",e.isPanelOpen),e.isPanelOpen||(t.style.width=""))}function uo(o,e){const t=[];for(const n of o?.header?.toolbarButtons??[])t.push({id:n.id,label:n.label,disabled:n.disabled??!1,source:"config"});for(const n of e.toolbarButtons.values())t.push({id:n.id,label:n.label,disabled:n.disabled??!1,source:"config"});for(let n=0;n<e.lightDomButtons.length;n++){const r=e.lightDomButtons[n].querySelector("button");t.push({id:`light-dom-${n}`,label:r?.getAttribute("title")??r?.getAttribute("aria-label")??"",disabled:r?.disabled??!1,source:"light-dom"})}for(const n of e.toolPanels.values())t.push({id:`panel-toggle-${n.id}`,label:n.tooltip??n.title,disabled:!1,source:"panel-toggle",panelId:n.id});return t}function ho(o){for(const e of o.headerContentCleanups.values())e();o.headerContentCleanups.clear(),o.activePanelCleanup&&(o.activePanelCleanup(),o.activePanelCleanup=null);for(const e of o.toolbarButtonCleanups.values())e();o.toolbarButtonCleanups.clear(),o.activePanel&&o.toolPanels.get(o.activePanel)?.onClose?.(),o.toolPanels.clear(),o.headerContents.clear(),o.toolbarButtons.clear(),o.lightDomButtons=[],o.lightDomHeaderContent=[],o.activePanel=null}function fo(o,e){let t=!1;const n={get isInitialized(){return t},setInitialized(i){t=i},get isPanelOpen(){return o.isPanelOpen},get activePanel(){return o.isPanelOpen&&o.expandedSections.size>0?[...o.expandedSections][0]:null},get expandedSections(){return[...o.expandedSections]},openToolPanel(){if(o.isPanelOpen)return;if(o.toolPanels.size===0){console.warn("[tbw-grid] No tool panels registered");return}if(o.isPanelOpen=!0,o.expandedSections.size===0&&o.toolPanels.size>0){const s=[...o.toolPanels.values()].sort((l,a)=>(l.order??100)-(a.order??100))[0];s&&o.expandedSections.add(s.id)}const i=e.getShadow();Xe(i,o),Ye(i,o),co(i,o,e.getAccordionIcons()),e.emit("tool-panel-open",{sections:n.expandedSections})},closeToolPanel(){if(!o.isPanelOpen)return;for(const r of o.panelCleanups.values())r();o.panelCleanups.clear(),o.activePanelCleanup&&(o.activePanelCleanup(),o.activePanelCleanup=null);for(const r of o.toolPanels.values())r.onClose?.();o.isPanelOpen=!1;const i=e.getShadow();Xe(i,o),Ye(i,o),e.emit("tool-panel-close",{})},toggleToolPanel(){o.isPanelOpen?n.closeToolPanel():n.openToolPanel()},toggleToolPanelSection(i){const r=o.toolPanels.get(i);if(!r){console.warn(`[tbw-grid] Tool panel section "${i}" not found`);return}if(o.toolPanels.size===1)return;const s=e.getShadow(),l=o.expandedSections.has(i);if(l){const a=o.panelCleanups.get(i);a&&(a(),o.panelCleanups.delete(i)),r.onClose?.(),o.expandedSections.delete(i),he(s,i,!1)}else{for(const[a,c]of o.toolPanels)if(a!==i&&o.expandedSections.has(a)){const d=o.panelCleanups.get(a);d&&(d(),o.panelCleanups.delete(a)),c.onClose?.(),o.expandedSections.delete(a),he(s,a,!1);const u=s.querySelector(`[data-section="${a}"] .tbw-accordion-content`);u&&(u.innerHTML="")}o.expandedSections.add(i),he(s,i,!0),po(s,o,i)}e.emit("tool-panel-section-toggle",{id:i,expanded:!l})},getToolPanels(){return[...o.toolPanels.values()]},registerToolPanel(i){if(o.toolPanels.has(i.id)){console.warn(`[tbw-grid] Tool panel "${i.id}" already registered`);return}o.toolPanels.set(i.id,i),t&&e.refreshShellHeader()},unregisterToolPanel(i){if(o.expandedSections.has(i)){const r=o.panelCleanups.get(i);r&&(r(),o.panelCleanups.delete(i)),o.expandedSections.delete(i)}o.toolPanels.delete(i),t&&e.refreshShellHeader()},getHeaderContents(){return[...o.headerContents.values()]},registerHeaderContent(i){if(o.headerContents.has(i.id)){console.warn(`[tbw-grid] Header content "${i.id}" already registered`);return}o.headerContents.set(i.id,i),t&&je(e.getShadow(),o)},unregisterHeaderContent(i){const r=o.headerContentCleanups.get(i);r&&(r(),o.headerContentCleanups.delete(i)),o.headerContents.get(i)?.onDestroy?.(),o.headerContents.delete(i),e.getShadow().querySelector(`[data-header-content="${i}"]`)?.remove()},getToolbarButtons(){return uo(e.getShellConfig(),o)},registerToolbarButton(i){if(o.toolbarButtons.has(i.id)){console.warn(`[tbw-grid] Toolbar button "${i.id}" already registered`);return}o.toolbarButtons.set(i.id,i),t&&e.refreshShellHeader()},unregisterToolbarButton(i){const r=o.toolbarButtonCleanups.get(i);r&&(r(),o.toolbarButtonCleanups.delete(i)),o.toolbarButtons.delete(i),t&&e.refreshShellHeader()},setToolbarButtonDisabled(i,r){const s=o.toolbarButtons.get(i);s&&(s.disabled=r);const l=e.getShadow().querySelector(`[data-btn="${i}"]`);l&&(l.disabled=r)}};return n}function he(o,e,t){const n=o.querySelector(`[data-section="${e}"]`);n&&n.classList.toggle("expanded",t)}function po(o,e,t){const n=e.toolPanels.get(t);if(!n?.render)return;const i=o.querySelector(`[data-section="${t}"] .tbw-accordion-content`);if(!i)return;const r=n.render(i);r&&e.panelCleanups.set(t,r)}class Ze{constructor(e){this.grid=e}plugins=[];pluginMap=new Map;cellRenderers=new Map;headerRenderers=new Map;cellEditors=new Map;attachAll(e){for(const t of e)this.attach(t)}attach(e){if(this.pluginMap.set(e.constructor,e),this.plugins.push(e),e.cellRenderers)for(const[t,n]of Object.entries(e.cellRenderers))this.cellRenderers.set(t,n);if(e.headerRenderers)for(const[t,n]of Object.entries(e.headerRenderers))this.headerRenderers.set(t,n);if(e.cellEditors)for(const[t,n]of Object.entries(e.cellEditors))this.cellEditors.set(t,n);e.attach(this.grid)}detachAll(){for(let e=this.plugins.length-1;e>=0;e--)this.plugins[e].detach();this.plugins=[],this.pluginMap.clear(),this.cellRenderers.clear(),this.headerRenderers.clear(),this.cellEditors.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}getCellRenderer(e){return this.cellRenderers.get(e)}getHeaderRenderer(e){return this.headerRenderers.get(e)}getCellEditor(e){return this.cellEditors.get(e)}getAllStyles(){return this.plugins.filter(e=>e.styles).map(e=>e.styles).join(`
44
- `)}processRows(e){let t=[...e];for(const n of this.plugins)n.processRows&&(t=n.processRows(t));return t}processColumns(e){let t=[...e];for(const n of this.plugins)n.processColumns&&(t=n.processColumns(t));return t}beforeRender(){for(const e of this.plugins)e.beforeRender?.()}afterRender(){for(const e of this.plugins)e.afterRender?.()}onScrollRender(){for(const e of this.plugins)e.onScrollRender?.()}getExtraHeight(){let e=0;for(const t of this.plugins)typeof t.getExtraHeight=="function"&&(e+=t.getExtraHeight());return e}getExtraHeightBefore(e){let t=0;for(const n of this.plugins)typeof n.getExtraHeightBefore=="function"&&(t+=n.getExtraHeightBefore(e));return t}adjustVirtualStart(e,t,n){let i=e;for(const r of this.plugins)if(typeof r.adjustVirtualStart=="function"){const s=r.adjustVirtualStart(e,t,n);s<i&&(i=s)}return i}renderRow(e,t,n){for(const i of this.plugins)if(i.renderRow?.(e,t,n))return!0;return!1}queryPlugins(e){const t=[];for(const n of this.plugins){const i=n.onPluginQuery?.(e);i!==void 0&&t.push(i)}return t}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 n=0,i=0,r=!1;for(const s of this.plugins){const l=s.getHorizontalScrollOffsets?.(e,t);l&&(n+=l.left,i+=l.right,l.skipScroll&&(r=!0))}return{left:n,right:i,skipScroll:r}}getToolPanels(){const e=[];for(const t of this.plugins){const n=t.getToolPanel?.();n&&e.push({plugin:t,panel:n})}return e.sort((t,n)=>(t.panel.order??0)-(n.panel.order??0))}getHeaderContents(){const e=[];for(const t of this.plugins){const n=t.getHeaderContent?.();n&&e.push({plugin:t,content:n})}return e.sort((t,n)=>(t.content.order??0)-(n.content.order??0))}}class V extends HTMLElement{static tagName="tbw-grid";static version=typeof __GRID_VERSION__<"u"?__GRID_VERSION__:"dev";static get observedAttributes(){return["rows","columns","grid-config","fit-mode","edit-on"]}#o;#r=!1;#m;#R;#s=[];#l;#v;#_;#S;#t={};#g=!1;#w=0;#A=null;#k=!1;#D;#T=!1;#L=null;#P=null;#M=null;#I=null;#y=null;#C=null;#x=null;#u=0;#h=0;#b=0;#c;#E;#e;#z;#f;#i=oo();#n;#H;_rows=[];#F=[];get _columns(){return this.#t.columns??[]}set _columns(e){this.#t.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};_focusRow=0;_focusCol=0;_sortState=null;_activeEditRows=-1;_rowEditSnapshots=new Map;_changedRowIndices=new Set;_gridTemplate="";__rowRenderEpoch=0;__didInitialAutoSize=!1;__lightDomColumnsCache;__originalColumnNodes;__originalOrder=[];get rows(){return this._rows}set rows(e){const t=this.#s;this.#s=e,t!==e&&this.#ee()}get sourceRows(){return this.#s}get columns(){return[...this._columns]}set columns(e){const t=this.#l;this.#l=e,t!==e&&this.#te()}get gridConfig(){return this.#t}set gridConfig(e){const t=this.#v;this.#v=e,t!==e&&this.#oe()}get fitMode(){return this.#t.fitMode??"stretch"}set fitMode(e){const t=this.#_;this.#_=e,t!==e&&this.#J()}get editOn(){return this.#t.editOn}set editOn(e){const t=this.#S;this.#S=e,t!==e&&this.#Q()}get effectiveConfig(){return this.#t}get disconnectSignal(){return this.#c||(this.#c=new AbortController),this.#c.signal}constructor(){super(),this.#o=this.attachShadow({mode:"open"}),this.#j(),this.#m=new Promise(e=>this.#R=e),this.#n=fo(this.#i,{getShadow:()=>this.#o,getShellConfig:()=>this.#t?.shell,getAccordionIcons:()=>({expand:this.#t?.icons?.expand??I.expand,collapse:this.#t?.icons?.collapse??I.collapse}),emit:(e,t)=>this.#a(e,t),refreshShellHeader:()=>this.refreshShellHeader()})}#j(){const e=new CSSStyleSheet;e.replaceSync(J),this.#o.adoptedStyleSheets=[e]}getPlugin(e){return this.#e?.getPlugin(e)}getPluginByName(e){return this.#e?.getPluginByName(e)}requestRender(){this.#O(),this.#N(),U(this),B(this),this.refreshVirtualWindow(!0)}updateTemplate(){B(this)}requestAfterRender(){this.#e?.afterRender()}#K(){this.#e=new Ze(this);const e=this.#t?.plugins,t=Array.isArray(e)?e:[];this.#e.attachAll(t)}#V(){const e=this.#e?.getAllStyles()??"";if(e){const t=document.createElement("style");t.setAttribute("data-plugin","all"),t.textContent=e,this.#o.appendChild(t)}}#$(){this.#e&&this.#e.detachAll(),this.#K(),this.#V(),this.#k=this.#e?.getAll().some(e=>e.onScroll)??!1}#X(){this.#e?.detachAll()}#Y(){if(!this.#e)return;const e=this.#e.getToolPanels();for(const{panel:n}of e)this.#i.toolPanels.has(n.id)||this.#i.toolPanels.set(n.id,n);const t=this.#e.getHeaderContents();for(const{content:n}of t)this.#i.headerContents.has(n.id)||this.#i.headerContents.set(n.id,n)}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=0),this.hasAttribute("version")||this.setAttribute("version",V.version),this._rows=Array.isArray(this.#s)?[...this.#s]:[],this.#c?.abort(),this.#c=new AbortController,this.#p(),this.#K(),this.#Y(),this.#r||(this.#U(),this.#V(),this.#r=!0),this.#G()}disconnectedCallback(){this.#X(),ho(this.#i),this.#n.setInitialized(!1),this.#H?.(),this.#H=void 0,this.#c&&(this.#c.abort(),this.#c=void 0),this._resizeController&&this._resizeController.dispose(),this.#E&&(this.#E.disconnect(),this.#E=void 0),this.#g=!1}attributeChangedCallback(e,t,n){if(t===n||!n||n==="null"||n==="undefined")return;const r={rows:"rows",columns:"columns","grid-config":"gridConfig","fit-mode":"fitMode","edit-on":"editOn"}[e];if(r)if(e==="rows"||e==="columns"||e==="grid-config")try{this[r]=JSON.parse(n)}catch{console.warn(`[tbw-grid] Invalid JSON for '${e}' attribute:`,n)}else this[r]=n}#G(){const t=this.#o.querySelector(".tbw-grid-content")??this.#o.querySelector(".tbw-grid-root");if(this._headerRowEl=t?.querySelector(".header-row"),this._virtualization.totalHeightEl=t?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=t?.querySelector(".rows-viewport"),this._bodyEl=t?.querySelector(".rows"),this.#n.isInitialized){je(this.#o,this.#i),ao(this.#o,this.#t?.shell,this.#i);const l=this.#t?.shell?.toolPanel?.defaultOpen;l&&this.#i.toolPanels.has(l)&&(this.openToolPanel(),this.#i.expandedSections.add(l))}this.setAttribute("data-upgraded",""),this.#g=!0;const n=this.disconnectSignal;this._resizeController=to(this),this.#d(),this.addEventListener("keydown",l=>Yt(this,l),{signal:n}),document.addEventListener("keydown",l=>{l.key==="Escape"&&this._activeEditRows!==-1&&K(this,this._activeEditRows,!0)},{capture:!0,signal:n}),document.addEventListener("mousedown",l=>{if(this._activeEditRows===-1)return;const a=this.findRenderedRowElement(this._activeEditRows);!a||(l.composedPath&&l.composedPath()||[]).includes(a)||K(this,this._activeEditRows,!1)},{signal:n});const i=t?.querySelector(".faux-vscroll"),r=t?.querySelector(".rows");if(this._virtualization.container=i??this,this.#k=this.#e?.getAll().some(l=>l.onScroll)??!1,i&&r){i.addEventListener("scroll",()=>{if(!this._virtualization.enabled&&!this.#k)return;const c=i.scrollTop,d=this._virtualization.rowHeight,u=Math.floor(c/d),f=u-u%2,h=-(c-f*d);r.style.transform=`translateY(${h}px)`,this.#A=c,this.#w||(this.#w=requestAnimationFrame(()=>{this.#w=0,this.#A!==null&&(this.#ie(this.#A),this.#A=null)}))},{passive:!0,signal:n});const l=this.#o.querySelector(".tbw-grid-content"),a=this.#o.querySelector(".tbw-scroll-area");l&&(l.addEventListener("wheel",c=>{const d=c.shiftKey||Math.abs(c.deltaX)>Math.abs(c.deltaY);if(d&&a){const u=c.shiftKey?c.deltaY:c.deltaX,{scrollLeft:f,scrollWidth:h,clientWidth:p}=a;(u>0&&f<h-p||u<0&&f>0)&&(c.preventDefault(),a.scrollLeft+=u)}else if(!d){const{scrollTop:u,scrollHeight:f,clientHeight:h}=i;(c.deltaY>0&&u<f-h||c.deltaY<0&&u>0)&&(c.preventDefault(),i.scrollTop+=c.deltaY)}},{passive:!1,signal:n}),l.addEventListener("touchstart",c=>{c.touches.length===1&&(this.#b&&(cancelAnimationFrame(this.#b),this.#b=0),this.#L=c.touches[0].clientY,this.#P=c.touches[0].clientX,this.#y=c.touches[0].clientY,this.#C=c.touches[0].clientX,this.#x=performance.now(),this.#M=i.scrollTop,this.#I=a?.scrollLeft??0,this.#u=0,this.#h=0)},{passive:!0,signal:n}),l.addEventListener("touchmove",c=>{if(c.touches.length===1&&this.#L!==null&&this.#P!==null&&this.#M!==null&&this.#I!==null){const d=c.touches[0].clientY,u=c.touches[0].clientX,f=performance.now(),h=this.#L-d,p=this.#P-u;if(this.#x!==null&&this.#y!==null&&this.#C!==null){const b=f-this.#x;b>0&&(this.#u=(this.#y-d)/b,this.#h=(this.#C-u)/b)}this.#y=d,this.#C=u,this.#x=f;const{scrollTop:g,scrollHeight:w,clientHeight:y}=i,R=w-y,T=h>0&&g<R||h<0&&g>0;let A=!1;if(a){const{scrollLeft:b,scrollWidth:m,clientWidth:S}=a,E=m-S;A=p>0&&b<E||p<0&&b>0}T&&(i.scrollTop=this.#M+h),A&&a&&(a.scrollLeft=this.#I+p),(T||A)&&c.preventDefault()}},{passive:!1,signal:n}),l.addEventListener("touchend",()=>{(Math.abs(this.#u)>.1||Math.abs(this.#h)>.1)&&this.#re(i,a),this.#L=null,this.#P=null,this.#M=null,this.#I=null,this.#y=null,this.#C=null,this.#x=null},{passive:!0,signal:n}))}this.#o.addEventListener("mousedown",l=>this.#se(l),{signal:n}),document.addEventListener("mousemove",l=>this.#le(l),{signal:n}),document.addEventListener("mouseup",l=>this.#ae(l),{signal:n}),this._virtualization.enabled&&requestAnimationFrame(()=>this.refreshVirtualWindow(!0));const s=this.#t.rowHeight;s&&s>0?this._virtualization.rowHeight=s:requestAnimationFrame(()=>{const l=this._bodyEl?.querySelector(".data-grid-row");if(l){const a=l.getBoundingClientRect().height;a>0&&(this._virtualization.rowHeight=a,this.refreshVirtualWindow(!0))}}),this._virtualization.viewportEl&&(this.#E=new ResizeObserver(()=>{this.#w||(this.#w=requestAnimationFrame(()=>{this.#w=0,this.refreshVirtualWindow(!0),D(this)}))}),this.#E.observe(this._virtualization.viewportEl)),queueMicrotask(()=>this.#Z()),requestAnimationFrame(()=>requestAnimationFrame(()=>this.#R?.()))}#a(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}_emitCellCommit(e){this.#a("cell-commit",e)}_emitRowCommit(e){this.#a("row-commit",e)}_emitSortChange(e){this.#a("sort-change",e)}_emitColumnResize(e){this.#a("column-resize",e)}_emitActivateCell(e){this.#a("activate-cell",e)}#Z(){this._bodyEl?.querySelectorAll(".data-grid-row")?.forEach((t,n)=>{const i=n===this._focusRow;t.setAttribute("aria-selected",String(i)),t.querySelectorAll(".cell").forEach((r,s)=>{r.setAttribute("aria-selected",String(i&&s===this._focusCol))})})}#J(){if(!this.#g)return;this.#p(),this.#t.fitMode==="fixed"?(this.__didInitialAutoSize=!1,qe(this)):(this._columns.forEach(t=>{!t.__userResized&&t.__autoSized&&delete t.width}),B(this))}#Q(){this.#g&&(this.#p(),this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++,this.refreshVirtualWindow(!0))}#ee(){this._rows=Array.isArray(this.#s)?[...this.#s]:[],this.#O(),this._columns.length>0||Array.isArray(this.#t?.columns)&&this.#t.columns.length>0||Array.isArray(this.#l)&&this.#l.length>0?(this.#N(),this.refreshVirtualWindow(!0)):this.#d()}#te(){ae(this),this.#g&&(this.#p(),this.#d())}#oe(){this.#g&&(this.#p(),this.#$(),this.#O(),this.#N(),U(this),B(this),this.refreshVirtualWindow(!0))}#N(){if(this.#e){const e=this.#F.length>0?this.#F:this._columns,t=e.filter(r=>!r.hidden),n=e.filter(r=>r.hidden),i=this.#e.processColumns([...t]);if(i!==t){const r=new Map(i.map((l,a)=>[l.field,{col:l,order:a}]));if(!t.some(l=>r.has(l.field))&&i.length>0)this._columns=[...i,...n];else{const l=e.map(a=>{if(a.hidden)return a;const c=r.get(a.field);return c?c.col:a});this._columns=l}}else this._columns=[...e]}}#O(){ae(this);const e=Array.isArray(this.#s)?[...this.#s]:[],t=this.#e?.processRows(e)??e;this._rows=t}#p(){const e=this.#v?{...this.#v}:{};let t=Array.isArray(e.columns)?[...e.columns]:[];const n=(this.__lightDomColumnsCache||[]).map(i=>({...i}));if(n.length){const i={};t.forEach(r=>i[r.field]=r),n.forEach(r=>{const s=i[r.field];s?(r.header&&!s.header&&(s.header=r.header),r.type&&!s.type&&(s.type=r.type),s.sortable=s.sortable||r.sortable,r.resizable&&(s.resizable=!0),r.editable&&(s.editable=!0)):(t.push(r),i[r.field]=r)})}if(this.#l&&this.#l.length&&(t=[...this.#l]),(!t||t.length===0)&&this._rows.length&&(t=Oe(this._rows).columns),t.length){t.forEach(s=>{s.sortable===void 0&&(s.sortable=!0),s.resizable===void 0&&(s.resizable=!0);const l=s;l.__originalWidth===void 0&&typeof s.width=="number"&&(l.__originalWidth=s.width)});const i=this.#t.columns;i?.some(s=>s.__compiledView||s.__compiledEditor)?e.columns=i:e.columns=t}else{const i=this.#t.columns;i?.some(r=>r.__compiledView||r.__compiledEditor)&&(e.columns=i)}this.#_&&(e.fitMode=this.#_),e.fitMode||(e.fitMode="stretch"),this.#S&&(e.editOn=this.#S),e.rowHeight&&e.rowHeight>0&&(this._virtualization.rowHeight=e.rowHeight),e.columnState&&!this.#f&&(this.#f=e.columnState),this.#t=e,e.fitMode==="fixed"&&this._columns.forEach(i=>{i.width==null&&(i.width=80)}),this.#ne()}#ne(){const e={...Ne,...this.#t.animation},t=e.mode??"reduced-motion";let n=1;t===!1||t==="off"?n=0:(t===!0||t==="on")&&(n=1),this.style.setProperty("--tbw-animation-duration",`${e.duration}ms`),this.style.setProperty("--tbw-animation-easing",e.easing??"ease-out"),this.style.setProperty("--tbw-animation-enabled",String(n)),this.dataset.animationMode=typeof t=="boolean"?t?"on":"off":t}#q(e,t,n=this.__rowRenderEpoch){this.#D||(this.#D=(i,r,s)=>this.#e?.renderRow(i,r,s)??!1),Qt(this,e,t,n,this.#D)}#d(){if(!this.isConnected||!this._headerRowEl||!this._bodyEl)return;const e=this.#v?.columns||this.#l||[];if(e.length){const n=new Map(this._columns.filter(r=>r.hidden).map(r=>[r.field,!0])),i=e.map(r=>({...r,hidden:n.get(r.field)??r.hidden}));this._columns=i}if(jt(this),this.#p(),this.#$(),this.#F=[...this._columns],this.#O(),this.#N(),this.#f){const n=this.#f;this.#f=void 0,this.#W(n)}U(this),B(this),this.refreshVirtualWindow(!0),this.#t.fitMode==="fixed"&&!this.__didInitialAutoSize&&requestAnimationFrame(()=>qe(this)),this._bodyEl&&(this._bodyEl.style.display="",this._bodyEl.style.gridTemplateColumns=""),queueMicrotask(()=>this.#e?.afterRender())}#W(e){const t=this.#t.columns??[],n=this.#e?.getAll()??[];It(this,e,t,n);for(const i of e.columns){const r=t.find(s=>s.field===i.field);r&&(r.hidden=!i.visible)}}#ie(e){if(this.refreshVirtualWindow(!1),this.#e?.onScrollRender(),this.#k){const t=this._virtualization.container,n={scrollTop:e,scrollLeft:t?.scrollLeft??0,scrollHeight:t?.scrollHeight??0,scrollWidth:t?.scrollWidth??0,clientHeight:t?.clientHeight??0,clientWidth:t?.clientWidth??0,originalEvent:new Event("scroll")};this.#e?.onScroll(n)}}findHeaderRow(){return this.#o.querySelector(".header-row")}findRenderedRowElement(e){return Array.from(this._bodyEl.querySelectorAll(".data-grid-row")).find(t=>{const n=t.querySelector(".cell[data-row]");return n&&Number(n.getAttribute("data-row"))===e})||null}_dispatchCellClick(e,t,n,i){const r=this._rows[t],s=this._columns[n];if(!r||!s)return!1;const l={row:r,rowIndex:t,colIndex:n,field:s.field,value:r[s.field],cellEl:i,originalEvent:e};return this.#e?.onCellClick(l)??!1}_dispatchRowClick(e,t,n,i){if(!n)return!1;const r={rowIndex:t,row:n,rowEl:i,originalEvent:e};return this.#e?.onRowClick(r)??!1}_dispatchHeaderClick(e,t,n){const i=this._columns[t];if(!i)return!1;const r={colIndex:t,field:i.field,column:i,headerEl:n,originalEvent:e};return this.#e?.onHeaderClick(r)??!1}_dispatchKeyDown(e){return this.#e?.onKeyDown(e)??!1}_getHorizontalScrollOffsets(e,t){return this.#e?.getHorizontalScrollOffsets(e,t)??{left:0,right:0}}queryPlugins(e){return this.#e?.queryPlugins(e)??[]}#B(e,t){let n=null;const i=e.composedPath?.();if(i&&i.length>0?n=i[0]:n=e.target,n&&!this.#o.contains(n)){const p=this.#o.elementFromPoint(e.clientX,e.clientY);p&&(n=p)}const r=n?.closest?.("[data-col]"),s=n?.closest?.(".data-grid-row"),l=n?.closest?.(".header-row");let a,c,d,u,f,h;return r&&(a=parseInt(r.getAttribute("data-row")??"-1",10),c=parseInt(r.getAttribute("data-col")??"-1",10),a>=0&&c>=0&&(d=this._rows[a],h=this._columns[c],u=h?.field,f=d&&u?d[u]:void 0)),{type:t,row:d,rowIndex:a!==void 0&&a>=0?a:void 0,colIndex:c!==void 0&&c>=0?c:void 0,field:u,value:f,column:h,originalEvent:e,cellElement:r??void 0,rowElement:s??void 0,isHeader:!!l,cell:a!==void 0&&c!==void 0&&a>=0&&c>=0?{row:a,col:c}:void 0}}#re(e,t){const r=()=>{this.#u*=.95,this.#h*=.95;const s=this.#u*16,l=this.#h*16;Math.abs(this.#u)>.01&&(e.scrollTop+=s),Math.abs(this.#h)>.01&&t&&(t.scrollLeft+=l),Math.abs(this.#u)>.01||Math.abs(this.#h)>.01?this.#b=requestAnimationFrame(r):this.#b=0};this.#b=requestAnimationFrame(r)}#se(e){const t=this.#B(e,"mousedown");(this.#e?.onCellMouseDown(t)??!1)&&(this.#T=!0)}#le(e){if(!this.#T)return;const t=this.#B(e,"mousemove");this.#e?.onCellMouseMove(t)}#ae(e){if(!this.#T)return;const t=this.#B(e,"mouseup");this.#e?.onCellMouseUp(t),this.#T=!1}get changedRows(){return Array.from(this._changedRowIndices).map(e=>this._rows[e])}get changedRowIndices(){return Array.from(this._changedRowIndices)}async resetChangedRows(e){this._changedRowIndices.clear(),e||this.#a("changed-rows-reset",{rows:this.changedRows,indices:this.changedRowIndices}),this._rowPool.forEach(t=>t.classList.remove("changed"))}async beginBulkEdit(e){if(!this._columns.some(r=>r.editable))return;const n=this._rows[e];W(this,e,n);const i=this.findRenderedRowElement?.(e);i&&(Array.from(i.children).forEach((r,s)=>{const l=this._visibleColumns[s];if(l?.editable){const a=r;a.classList.contains("editing")||O(this,n,e,l,a)}}),queueMicrotask(()=>{const r=i.querySelector(`.cell[data-col="${this._focusCol}"]`);if(r?.classList.contains("editing")){const s=r.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');try{s?.focus()}catch{}}}))}async commitActiveRowEdit(){this._activeEditRows!==-1&&K(this,this._activeEditRows,!1)}async ready(){return this.#m}async forceLayout(){this.#d(),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(e)))}async getConfig(){return Object.freeze({...this.#t||{}})}setColumnVisible(e,t){const n=this.#t.columns,i=n?.find(l=>l.field===e);if(!i||!t&&i.lockVisible||!t&&(n??[]).filter(a=>!a.hidden&&a.field!==e).length===0)return!1;const r=!!i.hidden,s=!t;return r!==s?(i.hidden=s,this.#a("column-visibility",{field:e,visible:t,visibleColumns:(n??[]).filter(l=>!l.hidden).map(l=>l.field)}),this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++,this.#d(),this.requestStateChange(),!0):!1}toggleColumnVisibility(e){const i=!!this.#t.columns?.find(r=>r.field===e)?.hidden;return this.setColumnVisible(e,i)}isColumnVisible(e){const n=this.#t.columns?.find(i=>i.field===e);return n?!n.hidden:!1}showAllColumns(){const e=this.#t.columns;e?.some(n=>n.hidden)&&(e?.forEach(n=>{n.hidden=!1}),this.#a("column-visibility",{visibleColumns:(e??[]).map(n=>n.field)}),this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++,this.#d(),this.requestStateChange())}getAllColumns(){return(this.#t.columns??[]).map(t=>({field:t.field,header:t.header||t.field,visible:!t.hidden,lockVisible:t.lockVisible}))}setColumnOrder(e){if(!e.length)return;const t=new Map(this._columns.map(i=>[i.field,i])),n=[];for(const i of e){const r=t.get(i);r&&(n.push(r),t.delete(i))}for(const i of t.values())n.push(i);this._columns=n,U(this),B(this),this.refreshVirtualWindow(!0)}getColumnOrder(){return this._columns.map(e=>e.field)}getColumnState(){const e=this.#e?.getAll()??[];return He(this,e)}set columnState(e){e&&(this.#f=e,this.#r&&this.#ce(e))}get columnState(){return this.getColumnState()}#ce(e){(this.#t.columns??[]).forEach(n=>{n.hidden=!1}),this.#W(e),this.#d()}requestStateChange(){this.#z||(this.#z=Ht(this,()=>this.#e?.getAll()??[],e=>this.#a("column-state-change",e))),this.#z()}resetColumnState(){this.#f=void 0,(this.#t.columns??[]).forEach(n=>{n.hidden=!1}),this._sortState=null,this.__originalOrder=[],this.#p(),this.#d();const t=this.#e?.getAll()??[];for(const n of t)if(n.applyColumnState)for(const i of this._columns)n.applyColumnState(i.field,{field:i.field,order:0,visible:!0});this.requestStateChange()}get isToolPanelOpen(){return this.#n.isPanelOpen}get activeToolPanel(){return this.#n.activePanel}get expandedToolPanelSections(){return this.#n.expandedSections}openToolPanel(){this.#n.openToolPanel()}closeToolPanel(){this.#n.closeToolPanel()}toggleToolPanel(){this.#n.toggleToolPanel()}toggleToolPanelSection(e){this.#n.toggleToolPanelSection(e)}getToolPanels(){return this.#n.getToolPanels()}registerToolPanel(e){this.#n.registerToolPanel(e)}unregisterToolPanel(e){this.#n.unregisterToolPanel(e)}getHeaderContents(){return this.#n.getHeaderContents()}registerHeaderContent(e){this.#n.registerHeaderContent(e)}unregisterHeaderContent(e){this.#n.unregisterHeaderContent(e)}getToolbarButtons(){return this.#n.getToolbarButtons()}registerToolbarButton(e){this.#n.registerToolbarButton(e)}unregisterToolbarButton(e){this.#n.unregisterToolbarButton(e)}setToolbarButtonDisabled(e,t){this.#n.setToolbarButtonDisabled(e,t)}refreshShellHeader(){Ue(this,this.#i),this.#U(),this.#G()}refreshVirtualWindow(e=!1){if(!this._bodyEl)return;const t=this._rows.length;if(!this._virtualization.enabled){this.#q(0,t),this.#e?.afterRender();return}if(this._rows.length<=this._virtualization.bypassThreshold){if(this._virtualization.start=0,this._virtualization.end=t,this._bodyEl.style.transform="translateY(0px)",this.#q(0,t,e?++this.__rowRenderEpoch:this.__rowRenderEpoch),this._virtualization.totalHeightEl){const S=this.#o.querySelector(".tbw-scroll-area"),E=S?S.offsetHeight-S.clientHeight:0;this._virtualization.totalHeightEl.style.height=`${t*this._virtualization.rowHeight+E}px`}const m=this.#o.querySelector(".rows-body");m?.setAttribute("aria-rowcount",String(t)),m?.setAttribute("aria-colcount",String(this._visibleColumns.length)),this.#e?.afterRender();return}const n=this._virtualization.container??this,r=(this._virtualization.viewportEl??n).clientHeight,s=this._virtualization.rowHeight,l=n.scrollTop;let a=Math.floor(l/s),c=0;const d=10;for(;c<d;){const m=this.#e?.getExtraHeightBefore?.(a)??0,S=Math.floor((l-m)/s);if(S>=a||S<0)break;a=S,c++}a=a-a%2,a<0&&(a=0);const u=this.#e?.adjustVirtualStart(a,l,s);u!==void 0&&u<a&&(a=u,a=a-a%2,a<0&&(a=0));const f=Math.ceil(r/s)+3;let h=a+f;h>t&&(h=t),this._virtualization.start=a,this._virtualization.end=h;const g=this.#o.querySelector(".tbw-footer")?.offsetHeight??0,w=this.#e?.getExtraHeight()??0,y=this.#o.querySelector(".tbw-scroll-area"),R=y?y.offsetHeight-y.clientHeight:0;this._virtualization.totalHeightEl&&(this._virtualization.totalHeightEl.style.height=`${t*s+s+g+w+R}px`);const T=this.#e?.getExtraHeightBefore?.(a)??0,A=-(l-a*s-T);this._bodyEl.style.transform=`translateY(${A}px)`,this.#q(a,h,e?++this.__rowRenderEpoch:this.__rowRenderEpoch);const b=this.#o.querySelector(".rows-body");b?.setAttribute("aria-rowcount",String(t)),b?.setAttribute("aria-colcount",String(this._visibleColumns.length)),e&&this.#e?.afterRender()}#U(){Ue(this,this.#i);const e=this.#t?.shell,t=no(e,this.#i),n=`
44
+ `)}processRows(e){let t=[...e];for(const n of this.plugins)n.processRows&&(t=n.processRows(t));return t}processColumns(e){let t=[...e];for(const n of this.plugins)n.processColumns&&(t=n.processColumns(t));return t}beforeRender(){for(const e of this.plugins)e.beforeRender?.()}afterRender(){for(const e of this.plugins)e.afterRender?.()}onScrollRender(){for(const e of this.plugins)e.onScrollRender?.()}getExtraHeight(){let e=0;for(const t of this.plugins)typeof t.getExtraHeight=="function"&&(e+=t.getExtraHeight());return e}getExtraHeightBefore(e){let t=0;for(const n of this.plugins)typeof n.getExtraHeightBefore=="function"&&(t+=n.getExtraHeightBefore(e));return t}adjustVirtualStart(e,t,n){let i=e;for(const r of this.plugins)if(typeof r.adjustVirtualStart=="function"){const s=r.adjustVirtualStart(e,t,n);s<i&&(i=s)}return i}renderRow(e,t,n){for(const i of this.plugins)if(i.renderRow?.(e,t,n))return!0;return!1}queryPlugins(e){const t=[];for(const n of this.plugins){const i=n.onPluginQuery?.(e);i!==void 0&&t.push(i)}return t}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 n=0,i=0,r=!1;for(const s of this.plugins){const l=s.getHorizontalScrollOffsets?.(e,t);l&&(n+=l.left,i+=l.right,l.skipScroll&&(r=!0))}return{left:n,right:i,skipScroll:r}}getToolPanels(){const e=[];for(const t of this.plugins){const n=t.getToolPanel?.();n&&e.push({plugin:t,panel:n})}return e.sort((t,n)=>(t.panel.order??0)-(n.panel.order??0))}getHeaderContents(){const e=[];for(const t of this.plugins){const n=t.getHeaderContent?.();n&&e.push({plugin:t,content:n})}return e.sort((t,n)=>(t.content.order??0)-(n.content.order??0))}}class V extends HTMLElement{static tagName="tbw-grid";static version=typeof __GRID_VERSION__<"u"?__GRID_VERSION__:"dev";static get observedAttributes(){return["rows","columns","grid-config","fit-mode","edit-on"]}#o;#r=!1;#m;#R;#s=[];#l;#v;#_;#S;#t={};#g=!1;#w=0;#A=null;#k=!1;#O;#T=!1;#L=null;#P=null;#M=null;#I=null;#y=null;#C=null;#x=null;#u=0;#h=0;#b=0;#c;#E;#e;#z;#f;#i=oo();#n;#H;_rows=[];#F=[];get _columns(){return this.#t.columns??[]}set _columns(e){this.#t.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};_focusRow=0;_focusCol=0;_sortState=null;_activeEditRows=-1;_rowEditSnapshots=new Map;_changedRowIndices=new Set;_gridTemplate="";__rowRenderEpoch=0;__didInitialAutoSize=!1;__lightDomColumnsCache;__originalColumnNodes;__originalOrder=[];get rows(){return this._rows}set rows(e){const t=this.#s;this.#s=e,t!==e&&this.#ee()}get sourceRows(){return this.#s}get columns(){return[...this._columns]}set columns(e){const t=this.#l;this.#l=e,t!==e&&this.#te()}get gridConfig(){return this.#t}set gridConfig(e){const t=this.#v;this.#v=e,t!==e&&this.#oe()}get fitMode(){return this.#t.fitMode??"stretch"}set fitMode(e){const t=this.#_;this.#_=e,t!==e&&this.#J()}get editOn(){return this.#t.editOn}set editOn(e){const t=this.#S;this.#S=e,t!==e&&this.#Q()}get effectiveConfig(){return this.#t}get disconnectSignal(){return this.#c||(this.#c=new AbortController),this.#c.signal}constructor(){super(),this.#o=this.attachShadow({mode:"open"}),this.#j(),this.#m=new Promise(e=>this.#R=e),this.#n=fo(this.#i,{getShadow:()=>this.#o,getShellConfig:()=>this.#t?.shell,getAccordionIcons:()=>({expand:this.#t?.icons?.expand??I.expand,collapse:this.#t?.icons?.collapse??I.collapse}),emit:(e,t)=>this.#a(e,t),refreshShellHeader:()=>this.refreshShellHeader()})}#j(){const e=new CSSStyleSheet;e.replaceSync(J),this.#o.adoptedStyleSheets=[e]}getPlugin(e){return this.#e?.getPlugin(e)}getPluginByName(e){return this.#e?.getPluginByName(e)}requestRender(){this.#D(),this.#N(),U(this),B(this),this.refreshVirtualWindow(!0)}updateTemplate(){B(this)}requestAfterRender(){this.#e?.afterRender()}#K(){this.#e=new Ze(this);const e=this.#t?.plugins,t=Array.isArray(e)?e:[];this.#e.attachAll(t)}#V(){const e=this.#e?.getAllStyles()??"";if(e){const t=document.createElement("style");t.setAttribute("data-plugin","all"),t.textContent=e,this.#o.appendChild(t)}}#$(){this.#e&&this.#e.detachAll(),this.#K(),this.#V(),this.#k=this.#e?.getAll().some(e=>e.onScroll)??!1}#X(){this.#e?.detachAll()}#Y(){if(!this.#e)return;const e=this.#e.getToolPanels();for(const{panel:n}of e)this.#i.toolPanels.has(n.id)||this.#i.toolPanels.set(n.id,n);const t=this.#e.getHeaderContents();for(const{content:n}of t)this.#i.headerContents.has(n.id)||this.#i.headerContents.set(n.id,n)}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=0),this.hasAttribute("version")||this.setAttribute("version",V.version),this._rows=Array.isArray(this.#s)?[...this.#s]:[],this.#c?.abort(),this.#c=new AbortController,this.#p(),this.#K(),this.#Y(),this.#r||(this.#U(),this.#V(),this.#r=!0),this.#G()}disconnectedCallback(){this.#X(),ho(this.#i),this.#n.setInitialized(!1),this.#H?.(),this.#H=void 0,this.#c&&(this.#c.abort(),this.#c=void 0),this._resizeController&&this._resizeController.dispose(),this.#E&&(this.#E.disconnect(),this.#E=void 0),this.#g=!1}attributeChangedCallback(e,t,n){if(t===n||!n||n==="null"||n==="undefined")return;const r={rows:"rows",columns:"columns","grid-config":"gridConfig","fit-mode":"fitMode","edit-on":"editOn"}[e];if(r)if(e==="rows"||e==="columns"||e==="grid-config")try{this[r]=JSON.parse(n)}catch{console.warn(`[tbw-grid] Invalid JSON for '${e}' attribute:`,n)}else this[r]=n}#G(){const t=this.#o.querySelector(".tbw-grid-content")??this.#o.querySelector(".tbw-grid-root");if(this._headerRowEl=t?.querySelector(".header-row"),this._virtualization.totalHeightEl=t?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=t?.querySelector(".rows-viewport"),this._bodyEl=t?.querySelector(".rows"),this.#n.isInitialized){je(this.#o,this.#i),ao(this.#o,this.#t?.shell,this.#i);const l=this.#t?.shell?.toolPanel?.defaultOpen;l&&this.#i.toolPanels.has(l)&&(this.openToolPanel(),this.#i.expandedSections.add(l))}this.setAttribute("data-upgraded",""),this.#g=!0;const n=this.disconnectSignal;this._resizeController=to(this),this.#d(),this.addEventListener("keydown",l=>Yt(this,l),{signal:n}),document.addEventListener("keydown",l=>{l.key==="Escape"&&this._activeEditRows!==-1&&K(this,this._activeEditRows,!0)},{capture:!0,signal:n}),document.addEventListener("mousedown",l=>{if(this._activeEditRows===-1)return;const a=this.findRenderedRowElement(this._activeEditRows);!a||(l.composedPath&&l.composedPath()||[]).includes(a)||K(this,this._activeEditRows,!1)},{signal:n});const i=t?.querySelector(".faux-vscroll"),r=t?.querySelector(".rows");if(this._virtualization.container=i??this,this.#k=this.#e?.getAll().some(l=>l.onScroll)??!1,i&&r){i.addEventListener("scroll",()=>{if(!this._virtualization.enabled&&!this.#k)return;const c=i.scrollTop,d=this._virtualization.rowHeight;if(this._rows.length<=this._virtualization.bypassThreshold)r.style.transform=`translateY(${-c}px)`;else{const u=Math.floor(c/d),f=u-u%2,h=-(c-f*d);r.style.transform=`translateY(${h}px)`}this.#A=c,this.#w||(this.#w=requestAnimationFrame(()=>{this.#w=0,this.#A!==null&&(this.#ie(this.#A),this.#A=null)}))},{passive:!0,signal:n});const l=this.#o.querySelector(".tbw-grid-content"),a=this.#o.querySelector(".tbw-scroll-area");l&&(l.addEventListener("wheel",c=>{const d=c.shiftKey||Math.abs(c.deltaX)>Math.abs(c.deltaY);if(d&&a){const u=c.shiftKey?c.deltaY:c.deltaX,{scrollLeft:f,scrollWidth:h,clientWidth:p}=a;(u>0&&f<h-p||u<0&&f>0)&&(c.preventDefault(),a.scrollLeft+=u)}else if(!d){const{scrollTop:u,scrollHeight:f,clientHeight:h}=i;(c.deltaY>0&&u<f-h||c.deltaY<0&&u>0)&&(c.preventDefault(),i.scrollTop+=c.deltaY)}},{passive:!1,signal:n}),l.addEventListener("touchstart",c=>{c.touches.length===1&&(this.#b&&(cancelAnimationFrame(this.#b),this.#b=0),this.#L=c.touches[0].clientY,this.#P=c.touches[0].clientX,this.#y=c.touches[0].clientY,this.#C=c.touches[0].clientX,this.#x=performance.now(),this.#M=i.scrollTop,this.#I=a?.scrollLeft??0,this.#u=0,this.#h=0)},{passive:!0,signal:n}),l.addEventListener("touchmove",c=>{if(c.touches.length===1&&this.#L!==null&&this.#P!==null&&this.#M!==null&&this.#I!==null){const d=c.touches[0].clientY,u=c.touches[0].clientX,f=performance.now(),h=this.#L-d,p=this.#P-u;if(this.#x!==null&&this.#y!==null&&this.#C!==null){const b=f-this.#x;b>0&&(this.#u=(this.#y-d)/b,this.#h=(this.#C-u)/b)}this.#y=d,this.#C=u,this.#x=f;const{scrollTop:g,scrollHeight:w,clientHeight:y}=i,R=w-y,T=h>0&&g<R||h<0&&g>0;let S=!1;if(a){const{scrollLeft:b,scrollWidth:m,clientWidth:A}=a,E=m-A;S=p>0&&b<E||p<0&&b>0}T&&(i.scrollTop=this.#M+h),S&&a&&(a.scrollLeft=this.#I+p),(T||S)&&c.preventDefault()}},{passive:!1,signal:n}),l.addEventListener("touchend",()=>{(Math.abs(this.#u)>.1||Math.abs(this.#h)>.1)&&this.#re(i,a),this.#L=null,this.#P=null,this.#M=null,this.#I=null,this.#y=null,this.#C=null,this.#x=null},{passive:!0,signal:n}))}this.#o.addEventListener("mousedown",l=>this.#se(l),{signal:n}),document.addEventListener("mousemove",l=>this.#le(l),{signal:n}),document.addEventListener("mouseup",l=>this.#ae(l),{signal:n}),this._virtualization.enabled&&requestAnimationFrame(()=>this.refreshVirtualWindow(!0));const s=this.#t.rowHeight;s&&s>0?this._virtualization.rowHeight=s:requestAnimationFrame(()=>{const l=this._bodyEl?.querySelector(".data-grid-row");if(l){const a=l.getBoundingClientRect().height;a>0&&(this._virtualization.rowHeight=a,this.refreshVirtualWindow(!0))}}),this._virtualization.viewportEl&&(this.#E=new ResizeObserver(()=>{this.#w||(this.#w=requestAnimationFrame(()=>{this.#w=0,this.refreshVirtualWindow(!0),O(this)}))}),this.#E.observe(this._virtualization.viewportEl)),queueMicrotask(()=>this.#Z()),requestAnimationFrame(()=>requestAnimationFrame(()=>this.#R?.()))}#a(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}_emitCellCommit(e){this.#a("cell-commit",e)}_emitRowCommit(e){this.#a("row-commit",e)}_emitSortChange(e){this.#a("sort-change",e)}_emitColumnResize(e){this.#a("column-resize",e)}_emitActivateCell(e){this.#a("activate-cell",e)}#Z(){this._bodyEl?.querySelectorAll(".data-grid-row")?.forEach((t,n)=>{const i=n===this._focusRow;t.setAttribute("aria-selected",String(i)),t.querySelectorAll(".cell").forEach((r,s)=>{r.setAttribute("aria-selected",String(i&&s===this._focusCol))})})}#J(){if(!this.#g)return;this.#p(),this.#t.fitMode==="fixed"?(this.__didInitialAutoSize=!1,qe(this)):(this._columns.forEach(t=>{!t.__userResized&&t.__autoSized&&delete t.width}),B(this))}#Q(){this.#g&&(this.#p(),this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++,this.refreshVirtualWindow(!0))}#ee(){this._rows=Array.isArray(this.#s)?[...this.#s]:[],this.#D(),this._columns.length>0||Array.isArray(this.#t?.columns)&&this.#t.columns.length>0||Array.isArray(this.#l)&&this.#l.length>0?(this.#N(),this.refreshVirtualWindow(!0)):this.#d()}#te(){ae(this),this.#g&&(this.#p(),this.#d())}#oe(){this.#g&&(this.#p(),this.#$(),this.#D(),this.#N(),U(this),B(this),this.refreshVirtualWindow(!0))}#N(){if(this.#e){const e=this.#F.length>0?this.#F:this._columns,t=e.filter(r=>!r.hidden),n=e.filter(r=>r.hidden),i=this.#e.processColumns([...t]);if(i!==t){const r=new Map(i.map((l,a)=>[l.field,{col:l,order:a}]));if(!t.some(l=>r.has(l.field))&&i.length>0)this._columns=[...i,...n];else{const l=e.map(a=>{if(a.hidden)return a;const c=r.get(a.field);return c?c.col:a});this._columns=l}}else this._columns=[...e]}}#D(){ae(this);const e=Array.isArray(this.#s)?[...this.#s]:[],t=this.#e?.processRows(e)??e;this._rows=t}#p(){const e=this.#v?{...this.#v}:{};let t=Array.isArray(e.columns)?[...e.columns]:[];const n=(this.__lightDomColumnsCache||[]).map(i=>({...i}));if(n.length){const i={};t.forEach(r=>i[r.field]=r),n.forEach(r=>{const s=i[r.field];s?(r.header&&!s.header&&(s.header=r.header),r.type&&!s.type&&(s.type=r.type),s.sortable=s.sortable||r.sortable,r.resizable&&(s.resizable=!0),r.editable&&(s.editable=!0)):(t.push(r),i[r.field]=r)})}if(this.#l&&this.#l.length&&(t=[...this.#l]),(!t||t.length===0)&&this._rows.length&&(t=De(this._rows).columns),t.length){t.forEach(s=>{s.sortable===void 0&&(s.sortable=!0),s.resizable===void 0&&(s.resizable=!0);const l=s;l.__originalWidth===void 0&&typeof s.width=="number"&&(l.__originalWidth=s.width)});const i=this.#t.columns;i?.some(s=>s.__compiledView||s.__compiledEditor)?e.columns=i:e.columns=t}else{const i=this.#t.columns;i?.some(r=>r.__compiledView||r.__compiledEditor)&&(e.columns=i)}this.#_&&(e.fitMode=this.#_),e.fitMode||(e.fitMode="stretch"),this.#S&&(e.editOn=this.#S),e.rowHeight&&e.rowHeight>0&&(this._virtualization.rowHeight=e.rowHeight),e.columnState&&!this.#f&&(this.#f=e.columnState),this.#t=e,e.fitMode==="fixed"&&this._columns.forEach(i=>{i.width==null&&(i.width=80)}),this.#ne()}#ne(){const e={...Ne,...this.#t.animation},t=e.mode??"reduced-motion";let n=1;t===!1||t==="off"?n=0:(t===!0||t==="on")&&(n=1),this.style.setProperty("--tbw-animation-duration",`${e.duration}ms`),this.style.setProperty("--tbw-animation-easing",e.easing??"ease-out"),this.style.setProperty("--tbw-animation-enabled",String(n)),this.dataset.animationMode=typeof t=="boolean"?t?"on":"off":t}#q(e,t,n=this.__rowRenderEpoch){this.#O||(this.#O=(i,r,s)=>this.#e?.renderRow(i,r,s)??!1),Qt(this,e,t,n,this.#O)}#d(){if(!this.isConnected||!this._headerRowEl||!this._bodyEl)return;const e=this.#v?.columns||this.#l||[];if(e.length){const n=new Map(this._columns.filter(r=>r.hidden).map(r=>[r.field,!0])),i=e.map(r=>({...r,hidden:n.get(r.field)??r.hidden}));this._columns=i}if(jt(this),this.#p(),this.#$(),this.#F=[...this._columns],this.#D(),this.#N(),this.#f){const n=this.#f;this.#f=void 0,this.#W(n)}U(this),B(this),this.refreshVirtualWindow(!0),this.#t.fitMode==="fixed"&&!this.__didInitialAutoSize&&requestAnimationFrame(()=>qe(this)),this._bodyEl&&(this._bodyEl.style.display="",this._bodyEl.style.gridTemplateColumns=""),queueMicrotask(()=>this.#e?.afterRender())}#W(e){const t=this.#t.columns??[],n=this.#e?.getAll()??[];It(this,e,t,n);for(const i of e.columns){const r=t.find(s=>s.field===i.field);r&&(r.hidden=!i.visible)}}#ie(e){if(this.refreshVirtualWindow(!1),this.#e?.onScrollRender(),this.#k){const t=this._virtualization.container,n={scrollTop:e,scrollLeft:t?.scrollLeft??0,scrollHeight:t?.scrollHeight??0,scrollWidth:t?.scrollWidth??0,clientHeight:t?.clientHeight??0,clientWidth:t?.clientWidth??0,originalEvent:new Event("scroll")};this.#e?.onScroll(n)}}findHeaderRow(){return this.#o.querySelector(".header-row")}findRenderedRowElement(e){return Array.from(this._bodyEl.querySelectorAll(".data-grid-row")).find(t=>{const n=t.querySelector(".cell[data-row]");return n&&Number(n.getAttribute("data-row"))===e})||null}_dispatchCellClick(e,t,n,i){const r=this._rows[t],s=this._columns[n];if(!r||!s)return!1;const l={row:r,rowIndex:t,colIndex:n,field:s.field,value:r[s.field],cellEl:i,originalEvent:e};return this.#e?.onCellClick(l)??!1}_dispatchRowClick(e,t,n,i){if(!n)return!1;const r={rowIndex:t,row:n,rowEl:i,originalEvent:e};return this.#e?.onRowClick(r)??!1}_dispatchHeaderClick(e,t,n){const i=this._columns[t];if(!i)return!1;const r={colIndex:t,field:i.field,column:i,headerEl:n,originalEvent:e};return this.#e?.onHeaderClick(r)??!1}_dispatchKeyDown(e){return this.#e?.onKeyDown(e)??!1}_getHorizontalScrollOffsets(e,t){return this.#e?.getHorizontalScrollOffsets(e,t)??{left:0,right:0}}queryPlugins(e){return this.#e?.queryPlugins(e)??[]}#B(e,t){let n=null;const i=e.composedPath?.();if(i&&i.length>0?n=i[0]:n=e.target,n&&!this.#o.contains(n)){const p=this.#o.elementFromPoint(e.clientX,e.clientY);p&&(n=p)}const r=n?.closest?.("[data-col]"),s=n?.closest?.(".data-grid-row"),l=n?.closest?.(".header-row");let a,c,d,u,f,h;return r&&(a=parseInt(r.getAttribute("data-row")??"-1",10),c=parseInt(r.getAttribute("data-col")??"-1",10),a>=0&&c>=0&&(d=this._rows[a],h=this._columns[c],u=h?.field,f=d&&u?d[u]:void 0)),{type:t,row:d,rowIndex:a!==void 0&&a>=0?a:void 0,colIndex:c!==void 0&&c>=0?c:void 0,field:u,value:f,column:h,originalEvent:e,cellElement:r??void 0,rowElement:s??void 0,isHeader:!!l,cell:a!==void 0&&c!==void 0&&a>=0&&c>=0?{row:a,col:c}:void 0}}#re(e,t){const r=()=>{this.#u*=.95,this.#h*=.95;const s=this.#u*16,l=this.#h*16;Math.abs(this.#u)>.01&&(e.scrollTop+=s),Math.abs(this.#h)>.01&&t&&(t.scrollLeft+=l),Math.abs(this.#u)>.01||Math.abs(this.#h)>.01?this.#b=requestAnimationFrame(r):this.#b=0};this.#b=requestAnimationFrame(r)}#se(e){const t=this.#B(e,"mousedown");(this.#e?.onCellMouseDown(t)??!1)&&(this.#T=!0)}#le(e){if(!this.#T)return;const t=this.#B(e,"mousemove");this.#e?.onCellMouseMove(t)}#ae(e){if(!this.#T)return;const t=this.#B(e,"mouseup");this.#e?.onCellMouseUp(t),this.#T=!1}get changedRows(){return Array.from(this._changedRowIndices).map(e=>this._rows[e])}get changedRowIndices(){return Array.from(this._changedRowIndices)}async resetChangedRows(e){this._changedRowIndices.clear(),e||this.#a("changed-rows-reset",{rows:this.changedRows,indices:this.changedRowIndices}),this._rowPool.forEach(t=>t.classList.remove("changed"))}async beginBulkEdit(e){if(!this._columns.some(r=>r.editable))return;const n=this._rows[e];W(this,e,n);const i=this.findRenderedRowElement?.(e);i&&(Array.from(i.children).forEach((r,s)=>{const l=this._visibleColumns[s];if(l?.editable){const a=r;a.classList.contains("editing")||D(this,n,e,l,a)}}),queueMicrotask(()=>{const r=i.querySelector(`.cell[data-col="${this._focusCol}"]`);if(r?.classList.contains("editing")){const s=r.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');try{s?.focus()}catch{}}}))}async commitActiveRowEdit(){this._activeEditRows!==-1&&K(this,this._activeEditRows,!1)}async ready(){return this.#m}async forceLayout(){this.#d(),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(e)))}async getConfig(){return Object.freeze({...this.#t||{}})}setColumnVisible(e,t){const n=this.#t.columns,i=n?.find(l=>l.field===e);if(!i||!t&&i.lockVisible||!t&&(n??[]).filter(a=>!a.hidden&&a.field!==e).length===0)return!1;const r=!!i.hidden,s=!t;return r!==s?(i.hidden=s,this.#a("column-visibility",{field:e,visible:t,visibleColumns:(n??[]).filter(l=>!l.hidden).map(l=>l.field)}),this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++,this.#d(),this.requestStateChange(),!0):!1}toggleColumnVisibility(e){const i=!!this.#t.columns?.find(r=>r.field===e)?.hidden;return this.setColumnVisible(e,i)}isColumnVisible(e){const n=this.#t.columns?.find(i=>i.field===e);return n?!n.hidden:!1}showAllColumns(){const e=this.#t.columns;e?.some(n=>n.hidden)&&(e?.forEach(n=>{n.hidden=!1}),this.#a("column-visibility",{visibleColumns:(e??[]).map(n=>n.field)}),this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++,this.#d(),this.requestStateChange())}getAllColumns(){return(this.#t.columns??[]).map(t=>({field:t.field,header:t.header||t.field,visible:!t.hidden,lockVisible:t.lockVisible}))}setColumnOrder(e){if(!e.length)return;const t=new Map(this._columns.map(i=>[i.field,i])),n=[];for(const i of e){const r=t.get(i);r&&(n.push(r),t.delete(i))}for(const i of t.values())n.push(i);this._columns=n,U(this),B(this),this.refreshVirtualWindow(!0)}getColumnOrder(){return this._columns.map(e=>e.field)}getColumnState(){const e=this.#e?.getAll()??[];return He(this,e)}set columnState(e){e&&(this.#f=e,this.#r&&this.#ce(e))}get columnState(){return this.getColumnState()}#ce(e){(this.#t.columns??[]).forEach(n=>{n.hidden=!1}),this.#W(e),this.#d()}requestStateChange(){this.#z||(this.#z=Ht(this,()=>this.#e?.getAll()??[],e=>this.#a("column-state-change",e))),this.#z()}resetColumnState(){this.#f=void 0,(this.#t.columns??[]).forEach(n=>{n.hidden=!1}),this._sortState=null,this.__originalOrder=[],this.#p(),this.#d();const t=this.#e?.getAll()??[];for(const n of t)if(n.applyColumnState)for(const i of this._columns)n.applyColumnState(i.field,{field:i.field,order:0,visible:!0});this.requestStateChange()}get isToolPanelOpen(){return this.#n.isPanelOpen}get activeToolPanel(){return this.#n.activePanel}get expandedToolPanelSections(){return this.#n.expandedSections}openToolPanel(){this.#n.openToolPanel()}closeToolPanel(){this.#n.closeToolPanel()}toggleToolPanel(){this.#n.toggleToolPanel()}toggleToolPanelSection(e){this.#n.toggleToolPanelSection(e)}getToolPanels(){return this.#n.getToolPanels()}registerToolPanel(e){this.#n.registerToolPanel(e)}unregisterToolPanel(e){this.#n.unregisterToolPanel(e)}getHeaderContents(){return this.#n.getHeaderContents()}registerHeaderContent(e){this.#n.registerHeaderContent(e)}unregisterHeaderContent(e){this.#n.unregisterHeaderContent(e)}getToolbarButtons(){return this.#n.getToolbarButtons()}registerToolbarButton(e){this.#n.registerToolbarButton(e)}unregisterToolbarButton(e){this.#n.unregisterToolbarButton(e)}setToolbarButtonDisabled(e,t){this.#n.setToolbarButtonDisabled(e,t)}refreshShellHeader(){Ue(this,this.#i),this.#U(),this.#G()}refreshVirtualWindow(e=!1){if(!this._bodyEl)return;const t=this._rows.length;if(!this._virtualization.enabled){this.#q(0,t),this.#e?.afterRender();return}if(this._rows.length<=this._virtualization.bypassThreshold){if(this._virtualization.start=0,this._virtualization.end=t,e&&(this._bodyEl.style.transform="translateY(0px)"),this.#q(0,t,e?++this.__rowRenderEpoch:this.__rowRenderEpoch),this._virtualization.totalHeightEl){const A=this._virtualization.container?.clientHeight??0,E=this._virtualization.viewportEl?.clientHeight??A,v=A-E;this._virtualization.totalHeightEl.style.height=`${t*this._virtualization.rowHeight+v}px`}const m=this.#o.querySelector(".rows-body");m?.setAttribute("aria-rowcount",String(t)),m?.setAttribute("aria-colcount",String(this._visibleColumns.length)),this.#e?.afterRender();return}const n=this._virtualization.container??this,r=(this._virtualization.viewportEl??n).clientHeight,s=this._virtualization.rowHeight,l=n.scrollTop;let a=Math.floor(l/s),c=0;const d=10;for(;c<d;){const m=this.#e?.getExtraHeightBefore?.(a)??0,A=Math.floor((l-m)/s);if(A>=a||A<0)break;a=A,c++}a=a-a%2,a<0&&(a=0);const u=this.#e?.adjustVirtualStart(a,l,s);u!==void 0&&u<a&&(a=u,a=a-a%2,a<0&&(a=0));const f=Math.ceil(r/s)+3;let h=a+f;h>t&&(h=t),this._virtualization.start=a,this._virtualization.end=h;const g=this.#o.querySelector(".tbw-footer")?.offsetHeight??0,w=this.#e?.getExtraHeight()??0,y=this.#o.querySelector(".tbw-scroll-area"),R=y?y.offsetHeight-y.clientHeight:0;this._virtualization.totalHeightEl&&(this._virtualization.totalHeightEl.style.height=`${t*s+s+g+w+R}px`);const T=this.#e?.getExtraHeightBefore?.(a)??0,S=-(l-a*s-T);this._bodyEl.style.transform=`translateY(${S}px)`,this.#q(a,h,e?++this.__rowRenderEpoch:this.__rowRenderEpoch);const b=this.#o.querySelector(".rows-body");b?.setAttribute("aria-rowcount",String(t)),b?.setAttribute("aria-colcount",String(this._visibleColumns.length)),e&&this.#e?.afterRender()}#U(){Ue(this,this.#i);const e=this.#t?.shell,t=no(e,this.#i),n=`
45
45
  <div class="tbw-scroll-area">
46
46
  <div class="rows-body-wrapper">
47
47
  <div class="rows-body" role="grid">
@@ -89,5 +89,5 @@
89
89
  <Row>`;for(const r of e){let s=i[r.field];t.processCell&&(s=t.processCell(s,r.field,i));let l="String",a="";s==null?a="":typeof s=="number"&&!isNaN(s)?(l="Number",a=String(s)):s instanceof Date?(l="DateTime",a=s.toISOString()):a=lt(String(s)),n+=`<Cell><Data ss:Type="${l}">${a}</Data></Cell>`}n+="</Row>"}return n+=`
90
90
  </Table>
91
91
  </Worksheet>
92
- </Workbook>`,n}function No(o,e){const t=e.endsWith(".xls")?e:`${e}.xls`,n=new Blob([o],{type:"application/vnd.ms-excel;charset=utf-8;"});Re(n,t)}class Oo extends L{name="export";version="1.0.0";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;performExport(e,t){const n=this.config,i={format:e,fileName:t?.fileName??n.fileName??"export",includeHeaders:t?.includeHeaders??n.includeHeaders,processCell:t?.processCell,processHeader:t?.processHeader,columns:t?.columns,rowIndices:t?.rowIndices};let r=[...this.columns];if(n.onlyVisible&&(r=r.filter(a=>!a.hidden&&!a.field.startsWith("__"))),t?.columns){const a=new Set(t.columns);r=r.filter(c=>a.has(c.field))}let s=[...this.rows];if(n.onlySelected){const a=this.getSelectionState();a?.selected?.size&&(s=[...a.selected].sort((d,u)=>d-u).map(d=>this.rows[d]).filter(Boolean))}t?.rowIndices&&(s=t.rowIndices.map(a=>this.rows[a]).filter(Boolean)),this.isExportingFlag=!0;let l=i.fileName;try{switch(e){case"csv":{const a=Mo(s,r,i,{bom:!0});l=l.endsWith(".csv")?l:`${l}.csv`,Io(a,l);break}case"excel":{const a=Ho(s,r,i);l=l.endsWith(".xls")?l:`${l}.xls`,No(a,l);break}case"json":{const a=s.map(u=>{const f={};for(const h of r){let p=u[h.field];i.processCell&&(p=i.processCell(p,h.field,u)),f[h.field]=p}return f}),c=JSON.stringify(a,null,2);l=l.endsWith(".json")?l:`${l}.json`;const d=new Blob([c],{type:"application/json"});Re(d,l);break}}this.lastExportInfo={format:e,timestamp:new Date},this.emit("export-complete",{format:e,fileName:l,rowCount:s.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}}function Do(o){const{totalRows:e,viewportHeight:t,scrollTop:n,rowHeight:i,overscan:r}=o,s=Math.ceil(t/i);let l=Math.floor(n/i)-r;l<0&&(l=0);let a=l+s+r*2;return a>e&&(a=e),a===e&&l>0&&(l=Math.max(0,a-s-r*2)),{start:l,end:a,offsetY:l*i,totalHeight:e*i}}function zo(o,e){return o<=e}function Fo(o,e,t=!1){const n=o[e.field];if(e.operator==="blank")return n==null||n==="";if(e.operator==="notBlank")return n!=null&&n!=="";if(n==null)return!1;const i=String(n),r=t?i:i.toLowerCase(),s=t?String(e.value):String(e.value).toLowerCase();switch(e.operator){case"contains":return r.includes(s);case"notContains":return!r.includes(s);case"equals":return r===s;case"notEquals":return r!==s;case"startsWith":return r.startsWith(s);case"endsWith":return r.endsWith(s);case"lessThan":return Number(n)<Number(e.value);case"lessThanOrEqual":return Number(n)<=Number(e.value);case"greaterThan":return Number(n)>Number(e.value);case"greaterThanOrEqual":return Number(n)>=Number(e.value);case"between":return Number(n)>=Number(e.value)&&Number(n)<=Number(e.valueTo);case"in":return Array.isArray(e.value)&&e.value.includes(n);case"notIn":return Array.isArray(e.value)&&!e.value.includes(n);default:return!0}}function qo(o,e,t=!1){return e.length?o.filter(n=>e.every(i=>Fo(n,i,t))):o}function Bo(o){return JSON.stringify(o.map(e=>({field:e.field,operator:e.operator,value:e.value,valueTo:e.valueTo})))}function at(o,e){const t=new Set;for(const n of o){const i=n[e];i!=null&&t.add(i)}return[...t].sort((n,i)=>typeof n=="number"&&typeof i=="number"?n-i:String(n).localeCompare(String(i)))}const Ko='.header-cell.filtered:before{content:"";position:absolute;top:4px;right:4px;width:6px;height:6px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border-radius:50%}.tbw-filter-btn{display:inline-flex;align-items:center;justify-content:center;background:transparent;border:none;cursor:pointer;padding:2px;margin-left:4px;opacity:.4;transition:opacity .15s;color:inherit;vertical-align:middle}.tbw-filter-btn:hover,.tbw-filter-btn.active{opacity:1}.tbw-filter-btn.active{color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6))}',Vo=".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, 4px));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:12px;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, 13px)}.tbw-filter-search{margin-bottom:8px}.tbw-filter-search-input{width:100%;padding:6px 10px;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, 4px);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:4px 2px;margin-bottom:8px;border-bottom:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)))}.tbw-filter-action-btn{background:transparent;border:none;color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));cursor:pointer;font-size:12px;padding:2px 0}.tbw-filter-action-btn:hover{text-decoration:underline}.tbw-filter-values{flex:1;overflow-y:auto;margin-bottom:8px;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:8px;padding:4px 2px;cursor:pointer;border-radius:3px}.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:8px 0;text-align:center;font-style:italic}.tbw-filter-buttons{display:flex;gap:8px;padding-top:8px;border-top:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)))}.tbw-filter-apply-btn{flex:1;padding:6px 12px;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:4px;cursor:pointer;font-size:13px}.tbw-filter-apply-btn:hover{filter:brightness(.9)}.tbw-filter-clear-btn{flex:1;padding:6px 12px;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:4px;cursor:pointer;font-size:13px}.tbw-filter-clear-btn:hover{background:var(--tbw-filter-hover, var(--tbw-color-row-hover, light-dark(#f0f6ff, #1c1c1c)))}";class q extends L{name="filtering";version="1.0.0";get defaultConfig(){return{debounceMs:300,caseSensitive:!1,trimInput:!0,useWorker:!0}}filters=new Map;cachedResult=null;cacheKey=null;openPanelField=null;panelElement=null;searchText=new Map;excludedValues=new Map;panelAbortController=null;globalStylesInjected=!1;static LIST_ITEM_HEIGHT=28;static LIST_OVERSCAN=3;static LIST_BYPASS_THRESHOLD=50;attach(e){super.attach(e),this.injectGlobalStyles()}detach(){this.filters.clear(),this.cachedResult=null,this.cacheKey=null,this.openPanelField=null,this.panelElement&&(this.panelElement.remove(),this.panelElement=null),this.searchText.clear(),this.excludedValues.clear(),this.panelAbortController?.abort(),this.panelAbortController=null}processRows(e){const t=[...this.filters.values()];if(!t.length)return[...e];if(this.config.filterHandler)return this.cachedResult?this.cachedResult:[...e];const n=Bo(t);if(this.cacheKey===n&&this.cachedResult)return this.cachedResult;const i=qo([...e],t,this.config.caseSensitive);return this.cachedResult=i,this.cacheKey=n,i}afterRender(){const e=this.shadowRoot;if(!e)return;e.querySelectorAll('[part~="header-cell"]').forEach(n=>{const i=n.getAttribute("data-col");if(i===null)return;const r=this.visibleColumns[parseInt(i,10)];if(!r||r.filterable===!1)return;const s=r.field;if(!s)return;const l=this.filters.has(s);let a=n.querySelector(".tbw-filter-btn");if(a){a.classList.toggle("active",l),n.classList.toggle("filtered",l);return}a=document.createElement("button"),a.className="tbw-filter-btn",a.setAttribute("aria-label",`Filter ${r.header??s}`),a.innerHTML='<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>',l&&(a.classList.add("active"),n.classList.add("filtered")),a.addEventListener("click",c=>{c.stopPropagation(),this.toggleFilterPanel(s,r,a)}),n.appendChild(a)})}setFilter(e,t){t===null?(this.filters.delete(e),this.excludedValues.delete(e)):(this.filters.set(e,{...t,field:e}),t.type==="set"&&t.operator==="notIn"&&Array.isArray(t.value)?this.excludedValues.set(e,new Set(t.value)):t.type==="set"&&this.excludedValues.delete(e)),this.cachedResult=null,this.cacheKey=null,this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0}),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),t.type==="set"&&t.operator==="notIn"&&Array.isArray(t.value)&&this.excludedValues.set(t.field,new Set(t.value));this.cachedResult=null,this.cacheKey=null,this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0}),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){return at(this.sourceRows,e)}injectGlobalStyles(){if(this.globalStylesInjected)return;if(document.getElementById("tbw-filter-panel-styles")){this.globalStylesInjected=!0;return}const e=document.createElement("style");e.id="tbw-filter-panel-styles",e.textContent=Vo,document.head.appendChild(e),this.globalStylesInjected=!0}toggleFilterPanel(e,t,n){if(this.openPanelField===e){this.closeFilterPanel();return}this.closeFilterPanel();const i=document.createElement("div");if(i.className="tbw-filter-panel",this.panelElement=i,this.openPanelField=e,this.config.valuesHandler){i.innerHTML='<div class="tbw-filter-loading">Loading...</div>',document.body.appendChild(i),this.positionPanel(i,n),this.setupPanelCloseHandler(i,n),this.config.valuesHandler(e,t).then(s=>{this.openPanelField!==e||!this.panelElement||(i.innerHTML="",this.renderPanelContent(e,t,i,s))});return}const r=at(this.sourceRows,e);this.renderPanelContent(e,t,i,r),document.body.appendChild(i),this.positionPanel(i,n),this.setupPanelCloseHandler(i,n)}renderPanelContent(e,t,n,i){let r=this.excludedValues.get(e);r||(r=new Set,this.excludedValues.set(e,r));const s=this.searchText.get(e)??"",l={field:e,column:t,uniqueValues:i,excludedValues:r,searchText:s,applySetFilter:c=>{this.applySetFilter(e,c),this.closeFilterPanel()},applyTextFilter:(c,d,u)=>{this.applyTextFilter(e,c,d,u),this.closeFilterPanel()},clearFilter:()=>{this.clearFieldFilter(e),this.closeFilterPanel()},closePanel:()=>this.closeFilterPanel()};let a=!1;this.config.filterPanelRenderer&&(this.config.filterPanelRenderer(n,l),a=n.children.length>0),a||this.renderDefaultFilterPanel(n,l,i,r)}setupPanelCloseHandler(e,t){this.panelAbortController=new AbortController,setTimeout(()=>{document.addEventListener("click",n=>{!e.contains(n.target)&&n.target!==t&&this.closeFilterPanel()},{signal:this.panelAbortController?.signal})},0)}closeFilterPanel(){this.panelElement&&(this.panelElement.remove(),this.panelElement=null),this.openPanelField=null,this.panelAbortController?.abort(),this.panelAbortController=null}positionPanel(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.top=`${n.bottom+4}px`,e.style.left=`${n.left}px`,requestAnimationFrame(()=>{const i=e.getBoundingClientRect();i.right>window.innerWidth-8&&(e.style.left=`${window.innerWidth-i.width-8}px`),i.bottom>window.innerHeight-8&&(e.style.top=`${n.top-i.height-4}px`)})}renderDefaultFilterPanel(e,t,n,i){const{field:r}=t,s=document.createElement("div");s.className="tbw-filter-search";const l=document.createElement("input");l.type="text",l.placeholder="Search...",l.className="tbw-filter-search-input",l.value=this.searchText.get(r)??"",s.appendChild(l),e.appendChild(s);const a=document.createElement("div");a.className="tbw-filter-actions";const c=document.createElement("label");c.className="tbw-filter-value-item",c.style.padding="0",c.style.margin="0";const d=document.createElement("input");d.type="checkbox",d.className="tbw-filter-checkbox";const u=document.createElement("span");u.textContent="Select All",c.appendChild(d),c.appendChild(u),a.appendChild(c);const f=()=>{const v=[...w.values()],x=v.every(k=>k),_=v.every(k=>!k);d.checked=x,d.indeterminate=!x&&!_};d.addEventListener("change",()=>{const v=d.checked;for(const x of w.keys())w.set(x,v);f(),T()}),e.appendChild(a);const h=document.createElement("div");h.className="tbw-filter-values";const p=document.createElement("div");p.className="tbw-filter-values-spacer",h.appendChild(p);const g=document.createElement("div");g.className="tbw-filter-values-content",h.appendChild(g);const w=new Map;n.forEach(v=>{const x=v==null?"__null__":String(v);w.set(x,!i.has(v))}),f();let y=[];const R=(v,x)=>{const _=v==null?"(Blank)":String(v),k=v==null?"__null__":String(v),P=document.createElement("label");P.className="tbw-filter-value-item",P.style.position="absolute",P.style.top=`${x*q.LIST_ITEM_HEIGHT}px`,P.style.left="0",P.style.right="0",P.style.height=`${q.LIST_ITEM_HEIGHT}px`,P.style.boxSizing="border-box";const z=document.createElement("input");z.type="checkbox",z.className="tbw-filter-checkbox",z.checked=w.get(k)??!0,z.dataset.value=k,z.addEventListener("change",()=>{w.set(k,z.checked),f()});const Pt=document.createElement("span");return Pt.textContent=_,P.appendChild(z),P.appendChild(Pt),P},T=()=>{const v=y.length,x=h.clientHeight,_=h.scrollTop;if(p.style.height=`${v*q.LIST_ITEM_HEIGHT}px`,zo(v,q.LIST_BYPASS_THRESHOLD/3)){g.innerHTML="",g.style.transform="translateY(0px)",y.forEach((P,z)=>{g.appendChild(R(P,z))});return}const k=Do({totalRows:v,viewportHeight:x,scrollTop:_,rowHeight:q.LIST_ITEM_HEIGHT,overscan:q.LIST_OVERSCAN});g.style.transform=`translateY(${k.offsetY}px)`,g.innerHTML="";for(let P=k.start;P<k.end;P++)g.appendChild(R(y[P],P-k.start))},A=v=>{const x=v.toLowerCase();if(y=n.filter(_=>{const k=_==null?"(Blank)":String(_);return!v||k.toLowerCase().includes(x)}),y.length===0){p.style.height="0px",g.innerHTML="";const _=document.createElement("div");_.className="tbw-filter-no-match",_.textContent="No matching values",g.appendChild(_);return}T()};h.addEventListener("scroll",()=>{y.length>0&&T()},{passive:!0}),A(l.value),e.appendChild(h);let b;l.addEventListener("input",()=>{clearTimeout(b),b=setTimeout(()=>{this.searchText.set(r,l.value),A(l.value)},this.config.debounceMs??150)});const m=document.createElement("div");m.className="tbw-filter-buttons";const S=document.createElement("button");S.className="tbw-filter-apply-btn",S.textContent="Apply",S.addEventListener("click",()=>{const v=[];for(const[x,_]of w)if(!_)if(x==="__null__")v.push(null);else{const k=n.find(P=>String(P)===x);v.push(k!==void 0?k:x)}t.applySetFilter(v)}),m.appendChild(S);const E=document.createElement("button");E.className="tbw-filter-clear-btn",E.textContent="Clear Filter",E.addEventListener("click",()=>{t.clearFilter()}),m.appendChild(E),e.appendChild(m)}applySetFilter(e,t){this.excludedValues.set(e,new Set(t)),t.length===0?this.filters.delete(e):this.filters.set(e,{field:e,type:"set",operator:"notIn",value:t}),this.applyFiltersInternal()}applyTextFilter(e,t,n,i){this.filters.set(e,{field:e,type:"text",operator:t,value:n,valueTo:i}),this.applyFiltersInternal()}applyFiltersInternal(){this.cachedResult=null,this.cacheKey=null;const e=[...this.filters.values()];if(this.config.filterHandler){const t=this.grid;t.setAttribute("aria-busy","true");const n=this.config.filterHandler(e,this.sourceRows),i=r=>{t.removeAttribute("aria-busy"),this.cachedResult=r,this.grid.rows=r,this.emit("filter-change",{filters:e,filteredRowCount:r.length}),this.requestRender()};n&&typeof n.then=="function"?n.then(i):i(n);return}this.emit("filter-change",{filters:e,filteredRowCount:0}),this.requestRender()}getColumnState(e){const t=this.filters.get(e);if(t)return{filter:{type:t.type,operator:t.operator,value:t.value,valueTo:t.valueTo}}}applyColumnState(e,t){if(!t.filter){this.filters.delete(e);return}const n={field:e,type:t.filter.type,operator:t.filter.operator,value:t.filter.value,valueTo:t.filter.valueTo};this.filters.set(e,n),this.cachedResult=null,this.cacheKey=null}styles=Ko}function $o(o){if(!o.length)return[];const e=new Map,t=[],n=(s,l)=>{if(!l.length)return;const a=t[t.length-1];if(a&&a.implicit&&a.firstIndex+a.columns.length===s){a.columns.push(...l);return}t.push({id:"__implicit__"+s,label:void 0,columns:l,firstIndex:s,implicit:!0})};let i=[],r=0;return o.forEach((s,l)=>{const a=s.group;if(!a){i.length===0&&(r=l),i.push(s);return}i.length&&(n(r,i.slice()),i=[]);const c=typeof a=="string"?a:a.id;let d=e.get(c);d||(d={id:c,label:typeof a=="string"?void 0:a.label,columns:[],firstIndex:l},e.set(c,d),t.push(d)),d.columns.push(s)}),i.length&&n(r,i),t.length===1&&t[0].implicit&&t[0].columns.length===o.length?[]:t}function Go(o,e,t){if(!e.length||!o)return;const n=new Map;for(const r of e)for(const s of r.columns)s?.field&&n.set(s.field,r.id);const i=Array.from(o.querySelectorAll(".cell[data-field]"));i.forEach(r=>{const s=r.getAttribute("data-field")||"",l=n.get(s);l&&(r.classList.add("grouped"),r.getAttribute("data-group")||r.setAttribute("data-group",l))});for(const r of e){const s=r.columns[r.columns.length-1],l=i.find(a=>a.getAttribute("data-field")===s.field);l&&l.classList.add("group-end")}}function Wo(o,e){if(o.length===0)return null;const t=document.createElement("div");t.className="header-group-row",t.setAttribute("role","row");for(const n of o){const i=n.firstIndex!=null?n.firstIndex:e.findIndex(a=>n.columns.includes(a)),r=String(n.id).startsWith("__implicit__"),s=r?"":n.label||n.id,l=document.createElement("div");l.className="cell header-group-cell",r&&l.classList.add("implicit-group"),l.setAttribute("data-group",String(n.id)),l.style.gridColumn=`${i+1} / span ${n.columns.length}`,l.textContent=s,t.appendChild(l)}return t}function Uo(o){return o.some(e=>e.group!=null)}const jo=".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:4px 8px;font-weight:600;font-size:.9em;text-transform:uppercase;letter-spacing:.5px;border-right:1px solid var(--tbw-grouping-columns-border, 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))}.header-row .cell.group-end:last-child{border-right:none}.header-group-row.no-borders{border-bottom:none}.header-group-row.no-borders .header-group-cell{border-right:none}.header-row.no-group-borders .cell.group-end{border-right:1px solid var(--tbw-color-border)}";class Xo extends L{name="groupingColumns";version="1.0.0";get defaultConfig(){return{showGroupBorders:!0}}groups=[];isActive=!1;detach(){this.groups=[],this.isActive=!1}static detect(e,t){const n=t?.columns;return Array.isArray(n)?Uo(n):!1}processColumns(e){const t=$o(e);return t.length===0?(this.isActive=!1,this.groups=[],[...e]):(this.isActive=!0,this.groups=t,[...e])}afterRender(){if(!this.isActive||this.groups.length===0){const s=this.shadowRoot?.querySelector(".header")?.querySelector(".header-group-row");s&&s.remove();return}const e=this.shadowRoot?.querySelector(".header");if(!e)return;const t=e.querySelector(".header-group-row");t&&t.remove();const n=Wo(this.groups,this.columns);if(n){n.classList.toggle("no-borders",!this.config.showGroupBorders);const r=e.querySelector(".header-row");r?e.insertBefore(n,r):e.appendChild(n)}const i=e.querySelector(".header-row");i&&(i.classList.toggle("no-group-borders",!this.config.showGroupBorders),Go(i,this.groups,this.columns))}isGroupingActive(){return this.isActive}getGroups(){return this.groups}getGroupColumns(e){const t=this.groups.find(n=>n.id===e);return t?t.columns:[]}refresh(){this.requestRender()}styles=jo}function Yo({rows:o,config:e,expanded:t}){const n=e.groupOn;if(typeof n!="function")return[];const i={key:"__root__",value:null,depth:-1,rows:[],children:new Map};if(o.forEach(l=>{let a=n(l);a==null||a===!1?a=["__ungrouped__"]:Array.isArray(a)||(a=[a]);let c=i;a.forEach((d,u)=>{const f=d==null?"∅":String(d),h=c.key==="__root__"?f:c.key+"||"+f;let p=c.children.get(f);p||(p={key:h,value:d,depth:u,rows:[],children:new Map,parent:c},c.children.set(f,p)),c=p}),c.rows.push(l)}),i.children.size===1&&i.children.has("__ungrouped__")&&i.children.get("__ungrouped__").rows.length===o.length)return[];const r=[],s=l=>{if(l===i){l.children.forEach(c=>s(c));return}const a=t.has(l.key);r.push({kind:"group",key:l.key,value:l.value,depth:l.depth,rows:l.rows,expanded:a}),a&&(l.children.size?l.children.forEach(c=>s(c)):l.rows.forEach(c=>r.push({kind:"data",row:c,rowIndex:o.indexOf(c)})))};return s(i),r}function Zo(o,e){const t=new Set(o);return t.has(e)?t.delete(e):t.add(e),t}function Jo(o){const e=new Set;for(const t of o)t.kind==="group"&&e.add(t.key);return e}function Qo(){return new Set}function en(o){return o.kind!=="group"?0:o.rows.length}const tn='.group-row{background:var(--tbw-grouping-rows-bg, var(--tbw-color-panel-bg));font-weight:500}.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:20px;height:20px;margin-right:4px}.group-toggle:hover{background:var(--tbw-grouping-rows-toggle-hover, var(--tbw-color-row-hover));border-radius:2px}.group-label{display:inline-flex;align-items:center;gap:8px}.group-count{color:var(--tbw-grouping-rows-count-color, var(--tbw-color-fg-muted));font-size:.85em;font-weight:400}[data-group-depth="0"] .group-label{padding-left:0}[data-group-depth="1"] .group-label{padding-left:20px}[data-group-depth="2"] .group-label{padding-left:40px}[data-group-depth="3"] .group-label{padding-left:60px}[data-group-depth="4"] .group-label{padding-left:80px}.data-grid-row.tbw-group-slide-in{animation:tbw-group-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.data-grid-row.tbw-group-fade-in{animation:tbw-group-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-fade-in{0%{opacity:0}to{opacity:1}}';class on extends L{name="groupingRows";version="1.0.0";get defaultConfig(){return{defaultExpanded:!1,showRowCount:!0,indentWidth:20,aggregators:{},animation:"slide"}}expandedKeys=new Set;flattenedRows=[];isActive=!1;previousVisibleKeys=new Set;keysToAnimate=new Set;get animationStyle(){const t=this.grid.effectiveConfig?.animation?.mode??"reduced-motion";if(t===!1||t==="off")return!1;if(t!==!0&&t!=="on"){const n=this.shadowRoot?.host;if(n&&getComputedStyle(n).getPropertyValue("--tbw-animation-enabled").trim()==="0")return!1}return this.config.animation??"slide"}detach(){this.expandedKeys.clear(),this.flattenedRows=[],this.isActive=!1,this.previousVisibleKeys.clear(),this.keysToAnimate.clear()}static detect(e,t){return typeof t?.groupOn=="function"||typeof t?.enableRowGrouping=="boolean"}processRows(e){const t=this.config;if(typeof t.groupOn!="function")return this.isActive=!1,this.flattenedRows=[],[...e];const n=Yo({rows:e,config:t,expanded:this.expandedKeys});if(n.length===0)return this.isActive=!1,this.flattenedRows=[],[...e];this.isActive=!0,this.flattenedRows=n,this.keysToAnimate.clear();const i=new Set;return n.forEach((r,s)=>{if(r.kind==="data"){const l=`data-${s}`;i.add(l),this.previousVisibleKeys.has(l)||this.keysToAnimate.add(l)}}),this.previousVisibleKeys=i,n.map(r=>r.kind==="group"?{__isGroupRow:!0,__groupKey:r.key,__groupValue:r.value,__groupDepth:r.depth,__groupRows:r.rows,__groupExpanded:r.expanded,__groupRowCount:en(r)}:r.row)}onCellClick(e){const t=e.row;if(t?.__isGroupRow&&e.originalEvent.target?.closest(".group-toggle"))return this.toggle(t.__groupKey),!0}renderRow(e,t,n){if(!e?.__isGroupRow)return!1;const i=this.config;if(i.groupRowRenderer){const l=()=>{this.toggle(e.__groupKey)},a=i.groupRowRenderer({key:e.__groupKey,value:e.__groupValue,depth:e.__groupDepth,rows:e.__groupRows,expanded:e.__groupExpanded,toggleExpand:l});if(a)return t.className="group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),typeof a=="string"?t.innerHTML=a:(t.innerHTML="",t.appendChild(a)),!0}const r=()=>{this.toggle(e.__groupKey)};return t.className="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.paddingLeft=`${(e.__groupDepth||0)*(i.indentWidth??20)}px`,t.innerHTML="",i.fullWidth!==!1?this.renderFullWidthGroupRow(e,t,r):this.renderPerColumnGroupRow(e,t,r),!0}afterRender(){const e=this.animationStyle;if(e===!1||this.keysToAnimate.size===0)return;const t=this.shadowRoot?.querySelector(".rows");if(!t)return;const n=e==="fade"?"tbw-group-fade-in":"tbw-group-slide-in";for(const i of t.querySelectorAll(".data-grid-row:not(.group-row)")){const r=i.querySelector(".cell[data-row]"),s=r?parseInt(r.getAttribute("data-row")??"-1",10):-1,a=this.flattenedRows[s]?.kind==="data"?`data-${s}`:void 0;a&&this.keysToAnimate.has(a)&&(i.classList.add(n),i.addEventListener("animationend",()=>i.classList.remove(n),{once:!0}))}this.keysToAnimate.clear()}renderFullWidthGroupRow(e,t,n){const i=this.config,r=document.createElement("div");r.className="cell group-full",r.style.gridColumn="1 / -1",r.setAttribute("role","gridcell");const s=document.createElement("button");s.type="button",s.className=`group-toggle${e.__groupExpanded?" expanded":""}`,s.setAttribute("aria-label",e.__groupExpanded?"Collapse group":"Expand group"),this.setIcon(s,this.resolveIcon(e.__groupExpanded?"collapse":"expand")),s.addEventListener("click",c=>{c.stopPropagation(),n()}),r.appendChild(s);const l=document.createElement("span");l.className="group-label";const a=i.formatLabel?i.formatLabel(e.__groupValue,e.__groupDepth||0,e.__groupKey):String(e.__groupValue);if(l.textContent=a,r.appendChild(l),i.showRowCount!==!1){const c=document.createElement("span");c.className="group-count",c.textContent=`(${e.__groupRowCount??e.__groupRows?.length??0})`,r.appendChild(c)}t.appendChild(r)}renderPerColumnGroupRow(e,t,n){const i=this.config,r=i.aggregators??{},s=this.columns,l=e.__groupRows??[],c=this.shadowRoot?.querySelector(".body")?.style.gridTemplateColumns||"";c&&(t.style.display="grid",t.style.gridTemplateColumns=c),s.forEach((d,u)=>{const f=document.createElement("div");if(f.className="cell group-cell",f.setAttribute("data-col",String(u)),f.setAttribute("role","gridcell"),u===0){const h=document.createElement("button");h.type="button",h.className=`group-toggle${e.__groupExpanded?" expanded":""}`,h.setAttribute("aria-label",e.__groupExpanded?"Collapse group":"Expand group"),this.setIcon(h,this.resolveIcon(e.__groupExpanded?"collapse":"expand")),h.addEventListener("click",w=>{w.stopPropagation(),n()}),f.appendChild(h);const p=document.createElement("span"),g=r[d.field];if(g){const w=we(g,l,d.field,d);p.textContent=w!=null?String(w):String(e.__groupValue)}else{const w=i.formatLabel?i.formatLabel(e.__groupValue,e.__groupDepth||0,e.__groupKey):String(e.__groupValue);p.textContent=w}if(f.appendChild(p),i.showRowCount!==!1){const w=document.createElement("span");w.className="group-count",w.textContent=` (${l.length})`,f.appendChild(w)}}else{const h=r[d.field];if(h){const p=we(h,l,d.field,d);f.textContent=p!=null?String(p):""}else f.textContent=""}t.appendChild(f)})}expandAll(){this.expandedKeys=Jo(this.flattenedRows),this.requestRender()}collapseAll(){this.expandedKeys=Qo(),this.requestRender()}toggle(e){this.expandedKeys=Zo(this.expandedKeys,e);const t=this.flattenedRows.find(n=>n.kind==="group"&&n.key===e);this.emit("group-toggle",{key:e,expanded:this.expandedKeys.has(e),value:t?.value,depth:t?.depth??0}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}expand(e){this.expandedKeys.has(e)||(this.expandedKeys=new Set([...this.expandedKeys,e]),this.requestRender())}collapse(e){if(this.expandedKeys.has(e)){const t=new Set(this.expandedKeys);t.delete(e),this.expandedKeys=t,this.requestRender()}}getGroupState(){const e=this.flattenedRows.filter(t=>t.kind==="group");return{isActive:this.isActive,expandedCount:this.expandedKeys.size,totalGroups:e.length,expandedKeys:[...this.expandedKeys]}}getRowCount(){return this.flattenedRows.length}refreshGroups(){this.requestRender()}getExpandedGroups(){return[...this.expandedKeys]}getFlattenedRows(){return this.flattenedRows}isGroupingActive(){return this.isActive}setGroupOn(e){this.config.groupOn=e,this.requestRender()}styles=tn}function _e(o,e){const t=new Set(o);return t.has(e)?t.delete(e):t.add(e),t}function nn(o,e){const t=new Set(o);return t.add(e),t}function rn(o,e){const t=new Set(o);return t.delete(e),t}function sn(o,e){return o.has(e)}function ln(o,e,t,n){const i=document.createElement("div");i.className="master-detail-row",i.setAttribute("data-detail-for",String(e)),i.setAttribute("role","row");const r=document.createElement("div");r.className="master-detail-cell",r.setAttribute("role","cell"),r.style.gridColumn=`1 / ${n+1}`;const s=t(o,e);return typeof s=="string"?r.innerHTML=s:s instanceof HTMLElement&&r.appendChild(s),i.appendChild(r),i}const an=".master-detail-cell-wrapper{display:flex;align-items:center;gap:4px}.master-detail-toggle{cursor:pointer;opacity:.7;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center}.master-detail-toggle:hover{opacity:1}.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}.master-detail-cell{padding:16px;overflow:auto}.master-detail-row.tbw-expanding{animation:tbw-detail-expand var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}.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:500px;padding-top:16px;padding-bottom:16px}}@keyframes tbw-detail-collapse{0%{opacity:1;max-height:500px}to{opacity:0;max-height:0}}";class cn extends L{name="masterDetail";version="1.0.0";get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,showExpandColumn:!0,animation:"slide"}}get isAnimationEnabled(){const t=this.grid.effectiveConfig?.animation?.mode??"reduced-motion";if(t===!1||t==="off")return!1;if(t===!0||t==="on")return!0;const n=this.shadowRoot?.host;return n?getComputedStyle(n).getPropertyValue("--tbw-animation-enabled").trim()!=="0":!0}get animationStyle(){return this.isAnimationEnabled?this.config.animation??"slide":!1}get animationDuration(){const e=this.shadowRoot?.host;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),n=parseInt(t,10);if(!isNaN(n))return n}return 200}animateExpand(e){!this.isAnimationEnabled||this.animationStyle===!1||(e.classList.add("tbw-expanding"),e.addEventListener("animationend",()=>{e.classList.remove("tbw-expanding")},{once:!0}))}animateCollapse(e,t){if(!this.isAnimationEnabled||this.animationStyle===!1){t();return}e.classList.add("tbw-collapsing");const n=()=>{e.classList.remove("tbw-collapsing"),t()};e.addEventListener("animationend",n,{once:!0}),setTimeout(n,this.animationDuration+50)}expandedRows=new Set;detailElements=new Map;detach(){this.expandedRows.clear(),this.detailElements.clear()}processColumns(e){if(!this.config.detailRenderer)return[...e];const t=[...e];if(t.length>0){const n={...t[0]},i=n.viewRenderer;if(i?.__masterDetailWrapped)return t;const r=s=>{const{value:l,row:a}=s,c=this.expandedRows.has(a),d=document.createElement("span");d.className="master-detail-cell-wrapper";const u=document.createElement("span");u.className=`master-detail-toggle${c?" expanded":""}`,this.setIcon(u,this.resolveIcon(c?"collapse":"expand")),u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-expanded",String(c)),u.setAttribute("aria-label",c?"Collapse details":"Expand details"),u.addEventListener("click",h=>{h.stopPropagation();const p=this.rows.indexOf(a);this.expandedRows=_e(this.expandedRows,a),this.emit("detail-expand",{rowIndex:p,row:a,expanded:this.expandedRows.has(a)}),this.requestRender()}),d.appendChild(u);const f=document.createElement("span");if(i){const h=i(s);h instanceof Node?f.appendChild(h):f.textContent=String(h??l??"")}else f.textContent=String(l??"");return d.appendChild(f),d};r.__masterDetailWrapped=!0,n.viewRenderer=r,t[0]=n}return t}onRowClick(e){if(!(!this.config.expandOnRowClick||!this.config.detailRenderer))return this.expandedRows=_e(this.expandedRows,e.row),this.emit("detail-expand",{rowIndex:e.rowIndex,row:e.row,expanded:this.expandedRows.has(e.row)}),this.requestRender(),!1}onCellClick(){this.expandedRows.size>0&&queueMicrotask(()=>this.#o())}afterRender(){this.#o()}onScrollRender(){!this.config.detailRenderer||this.expandedRows.size===0||this.#o()}#o(){if(!this.config.detailRenderer)return;const e=this.shadowRoot?.querySelector(".rows");if(!e)return;const t=new Map,n=e.querySelectorAll(".data-grid-row"),i=this.columns.length;for(const s of n){const l=s.querySelector(".cell[data-row]"),a=l?parseInt(l.getAttribute("data-row")??"-1",10):-1;a>=0&&t.set(a,s)}const r=e.querySelectorAll(".master-detail-row");for(const s of r){const l=parseInt(s.getAttribute("data-detail-for")??"-1",10),a=l>=0?this.rows[l]:void 0,c=a&&this.expandedRows.has(a),d=t.has(l);(!c||!d)&&(s.remove(),a&&this.detailElements.delete(a))}for(const[s,l]of t){const a=this.rows[s];if(!a||!this.expandedRows.has(a))continue;const c=this.detailElements.get(a);if(c){c.previousElementSibling!==l&&l.after(c);continue}const d=ln(a,s,this.config.detailRenderer,i);typeof this.config.detailHeight=="number"&&(d.style.height=`${this.config.detailHeight}px`),l.after(d),this.detailElements.set(a,d),this.animateExpand(d)}}getExtraHeight(){let e=0;for(const t of this.expandedRows){const n=this.detailElements.get(t);if(n)e+=n.offsetHeight;else{const i=this.config?.detailHeight;e+=typeof i=="number"?i:150}}return e}getExtraHeightBefore(e){let t=0;for(const n of this.expandedRows){const i=this.rows.indexOf(n);if(i>=0&&i<e){const r=this.detailElements.get(n);if(r)t+=r.offsetHeight;else{const s=this.config?.detailHeight;t+=typeof s=="number"?s:150}}}return t}adjustVirtualStart(e,t,n){if(this.expandedRows.size===0)return e;const i=[];for(const l of this.expandedRows){const a=this.rows.indexOf(l);a>=0&&i.push({index:a,row:l})}i.sort((l,a)=>l.index-a.index);let r=e,s=0;for(const{index:l,row:a}of i){const c=l*n+s,u=this.detailElements.get(a)?.offsetHeight??(typeof this.config?.detailHeight=="number"?this.config.detailHeight:150),f=c+n+u;s+=u,!(l>=e)&&f>t&&l<r&&(r=l)}return r}expand(e){const t=this.rows[e];t&&(this.expandedRows=nn(this.expandedRows,t),this.requestRender())}collapse(e){const t=this.rows[e];t&&(this.expandedRows=rn(this.expandedRows,t),this.requestRender())}toggle(e){const t=this.rows[e];t&&(this.expandedRows=_e(this.expandedRows,t),this.requestRender())}isExpanded(e){const t=this.rows[e];return t?sn(this.expandedRows,t):!1}expandAll(){for(const e of this.rows)this.expandedRows.add(e);this.requestRender()}collapseAll(){this.expandedRows.clear(),this.requestRender()}getExpandedRows(){const e=[];for(const t of this.expandedRows){const n=this.rows.indexOf(t);n>=0&&e.push(n)}return e}getDetailElement(e){const t=this.rows[e];return t?this.detailElements.get(t):void 0}styles=an}function dn(o,e,t){return e.length?[...o].sort((n,i)=>{for(const r of e){const l=t.find(u=>u.field===r.field)?.sortComparator??un,a=n[r.field],c=i[r.field],d=l(a,c,n,i);if(d!==0)return r.direction==="asc"?d:-d}return 0}):[...o]}function un(o,e){return o==null&&e==null?0:o==null?1:e==null?-1:typeof o=="number"&&typeof e=="number"?o-e:o instanceof Date&&e instanceof Date?o.getTime()-e.getTime():typeof o=="boolean"&&typeof e=="boolean"?o===e?0:o?-1:1:String(o).localeCompare(String(e))}function hn(o,e,t,n){const i=o.find(r=>r.field===e);return t?i?i.direction==="asc"?o.map(r=>r.field===e?{...r,direction:"desc"}:r):o.filter(r=>r.field!==e):o.length<n?[...o,{field:e,direction:"asc"}]:o:i?.direction==="asc"?[{field:e,direction:"desc"}]:i?.direction==="desc"?[]:[{field:e,direction:"asc"}]}function ct(o,e){const t=o.findIndex(n=>n.field===e);return t>=0?t+1:void 0}function dt(o,e){return o.find(t=>t.field===e)?.direction}const fn='.header-cell[data-sort=asc]:after{content:"↑";margin-left:4px;opacity:.8}.header-cell[data-sort=desc]:after{content:"↓";margin-left:4px;opacity:.8}.sort-indicator{margin-left:4px;opacity:.8}.sort-index{font-size:10px;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:14px;height:14px;display:inline-flex;align-items:center;justify-content:center;margin-left:2px;font-weight:600}';class pn extends L{name="multiSort";version="1.0.0";get defaultConfig(){return{maxSortColumns:3,showSortIndex:!0}}sortModel=[];detach(){this.sortModel=[]}processRows(e){return this.sortModel.length===0?[...e]:dn([...e],this.sortModel,[...this.columns])}onHeaderClick(e){if(!this.columns.find(r=>r.field===e.field)?.sortable)return!1;const n=e.originalEvent.shiftKey,i=this.config.maxSortColumns??3;return this.sortModel=hn(this.sortModel,e.field,n,i),this.emit("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),!0}afterRender(){const e=this.shadowRoot;if(!e)return;const t=this.config.showSortIndex!==!1;e.querySelectorAll(".header-row .cell[data-field]").forEach(i=>{const r=i.getAttribute("data-field");if(!r)return;const s=ct(this.sortModel,r),l=dt(this.sortModel,r);if(i.querySelector(".sort-index")?.remove(),l){i.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove(),i.setAttribute("data-sort",l);const d=document.createElement("span");if(d.className="sort-indicator",this.setIcon(d,this.resolveIcon(l==="asc"?"sortAsc":"sortDesc")),i.appendChild(d),t&&this.sortModel.length>1&&s!==void 0){const u=document.createElement("span");u.className="sort-index",u.textContent=String(s),i.appendChild(u)}}else i.removeAttribute("data-sort")})}getSortModel(){return[...this.sortModel]}setSortModel(e){this.sortModel=[...e],this.emit("sort-change",{sortModel:[...e]}),this.requestRender()}clearSort(){this.sortModel=[],this.emit("sort-change",{sortModel:[]}),this.requestRender()}getSortIndex(e){return ct(this.sortModel,e)}getSortDirection(e){return dt(this.sortModel,e)}getColumnState(e){const t=this.sortModel.findIndex(i=>i.field===e);return t===-1?void 0:{sort:{direction:this.sortModel[t].direction,priority:t}}}applyColumnState(e,t){if(!t.sort){this.sortModel=this.sortModel.filter(r=>r.field!==e);return}const n=this.sortModel.findIndex(r=>r.field===e),i={field:e,direction:t.sort.direction};n!==-1?this.sortModel[n]=i:this.sortModel.splice(t.sort.priority,0,i)}styles=fn}function gn(o){return o.filter(e=>e.sticky==="left")}function wn(o){return o.filter(e=>e.sticky==="right")}function Se(o){return o.some(e=>e.sticky==="left"||e.sticky==="right")}function ut(o,e){const t=o.shadowRoot;if(!t)return;const n=Array.from(t.querySelectorAll(".header-row .cell"));if(!n.length)return;const i=new Map;e.forEach((l,a)=>{l.field&&i.set(l.field,a)});let r=0;for(const l of e)if(l.sticky==="left"){const a=i.get(l.field),c=n.find(d=>d.getAttribute("data-field")===l.field);c&&(c.classList.add("sticky-left"),c.style.position="sticky",c.style.left=r+"px",a!==void 0&&t.querySelectorAll(`.data-grid-row .cell[data-col="${a}"]`).forEach(d=>{d.classList.add("sticky-left"),d.style.position="sticky",d.style.left=r+"px"}),r+=c.offsetWidth)}let s=0;for(const l of[...e].reverse())if(l.sticky==="right"){const a=i.get(l.field),c=n.find(d=>d.getAttribute("data-field")===l.field);c&&(c.classList.add("sticky-right"),c.style.position="sticky",c.style.right=s+"px",a!==void 0&&t.querySelectorAll(`.data-grid-row .cell[data-col="${a}"]`).forEach(d=>{d.classList.add("sticky-right"),d.style.position="sticky",d.style.right=s+"px"}),s+=c.offsetWidth)}}function ht(o){const e=o.shadowRoot;if(!e)return;e.querySelectorAll(".sticky-left, .sticky-right").forEach(n=>{n.classList.remove("sticky-left","sticky-right"),n.style.position="",n.style.left="",n.style.right=""})}class bn extends L{name="pinnedColumns";version="1.0.0";get defaultConfig(){return{}}isApplied=!1;leftOffsets=new Map;rightOffsets=new Map;detach(){this.leftOffsets.clear(),this.rightOffsets.clear(),this.isApplied=!1}static detect(e,t){const n=t?.columns;return Array.isArray(n)?Se(n):!1}processColumns(e){return this.isApplied=Se([...e]),[...e]}afterRender(){if(!this.isApplied)return;const e=this.grid,t=[...this.columns];if(!Se(t)){ht(e),this.isApplied=!1;return}queueMicrotask(()=>{ut(e,t)})}onPluginQuery(e){switch(e.type){case ee.CAN_MOVE_COLUMN:{const t=e.context,n=t.sticky;if(n==="left"||n==="right")return!1;const i=t.meta?.sticky;return i==="left"||i==="right"?!1:void 0}default:return}}refreshStickyOffsets(){const e=[...this.columns];ut(this.grid,e)}getLeftPinnedColumns(){const e=[...this.columns];return gn(e)}getRightPinnedColumns(){const e=[...this.columns];return wn(e)}clearStickyPositions(){ht(this.grid)}getHorizontalScrollOffsets(e,t){if(!this.isApplied)return;let n=0,i=0;if(e){const s=e.querySelectorAll(".sticky-left"),l=e.querySelectorAll(".sticky-right");s.forEach(a=>{n+=a.offsetWidth}),l.forEach(a=>{i+=a.offsetWidth})}else{const l=this.grid.shadowRoot;l&&l.querySelectorAll(".header-row .cell").forEach(c=>{c.classList.contains("sticky-left")?n+=c.offsetWidth:c.classList.contains("sticky-right")&&(i+=c.offsetWidth)})}const r=t?.classList.contains("sticky-left")||t?.classList.contains("sticky-right");return{left:n,right:i,skipScroll:r}}}function mn(o){return typeof o=="object"&&o!==null&&"aggFunc"in o}function Ae(o,e){const t=document.createElement("div");t.className="tbw-pinned-rows",t.setAttribute("role","presentation"),t.setAttribute("aria-live","polite");const n=document.createElement("div");n.className="tbw-pinned-rows-left";const i=document.createElement("div");i.className="tbw-pinned-rows-center";const r=document.createElement("div");if(r.className="tbw-pinned-rows-right",o.showRowCount!==!1){const s=document.createElement("span");s.className="tbw-status-panel tbw-status-panel-row-count",s.textContent=`Total: ${e.totalRows} rows`,n.appendChild(s)}if(o.showFilteredCount&&e.filteredRows!==e.totalRows){const s=document.createElement("span");s.className="tbw-status-panel tbw-status-panel-filtered-count",s.textContent=`Filtered: ${e.filteredRows}`,n.appendChild(s)}if(o.showSelectedCount&&e.selectedRows>0){const s=document.createElement("span");s.className="tbw-status-panel tbw-status-panel-selected-count",s.textContent=`Selected: ${e.selectedRows}`,r.appendChild(s)}if(o.customPanels)for(const s of o.customPanels){const l=vn(s,e);switch(s.position){case"left":n.appendChild(l);break;case"center":i.appendChild(l);break;case"right":r.appendChild(l);break}}return t.appendChild(n),t.appendChild(i),t.appendChild(r),t}function ft(o){const e=document.createElement("div");return e.className=`tbw-aggregation-rows tbw-aggregation-rows-${o}`,e.setAttribute("role","presentation"),e}function pt(o,e,t,n){o.innerHTML="";for(const i of e){const r=document.createElement("div");if(r.className="tbw-aggregation-row",r.setAttribute("role","presentation"),i.id&&r.setAttribute("data-aggregation-id",i.id),i.fullWidth){const s=document.createElement("div");s.className="tbw-aggregation-cell tbw-aggregation-cell-full",s.style.gridColumn="1 / -1",s.textContent=i.label||"",r.appendChild(s)}else for(const s of t){const l=document.createElement("div");l.className="tbw-aggregation-cell",l.setAttribute("data-field",s.field);let a,c;const d=i.aggregators?.[s.field];if(d)if(mn(d)){const u=ge(d.aggFunc);u&&(a=u(n,s.field,s)),c=d.formatter}else{const u=ge(d);u&&(a=u(n,s.field,s))}else if(i.cells&&Object.prototype.hasOwnProperty.call(i.cells,s.field)){const u=i.cells[s.field];typeof u=="function"?a=u(n,s.field,s):a=u}a!=null?l.textContent=c?c(a,s.field,s):String(a):l.textContent="",r.appendChild(l)}o.appendChild(r)}}function vn(o,e){const t=document.createElement("div");t.className="tbw-status-panel tbw-status-panel-custom",t.id=`status-panel-${o.id}`;const n=o.render(e);return typeof n=="string"?t.innerHTML=n:t.appendChild(n),t}function gt(o,e,t,n,i){return{totalRows:o.length,filteredRows:i?.cachedResult?.length??o.length,selectedRows:n?.selected?.size??0,columns:e,rows:o,grid:t}}const yn=".tbw-footer{position:sticky;bottom: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:8px 12px;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:12px;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:16px}.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, 2px 8px);min-height:var(--tbw-row-height, 28px);display:flex;align-items:center;border-right:1px solid var(--tbw-color-border-cell)}.tbw-aggregation-cell:last-child{border-right:0}.tbw-aggregation-cell-full{grid-column:1 / -1;border-right:0}";class Cn extends L{name="pinnedRows";version="1.0.0";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.shadowRoot;if(!e)return;const t=e.querySelector(".tbw-scroll-area")??e.querySelector(".tbw-grid-content")??e.children[0];if(!t)return;const n=this.getSelectionState(),i=this.getFilterState(),r=gt(this.rows,this.columns,this.grid,n,i),s=this.config.aggregationRows||[],l=s.filter(f=>f.position==="top"),a=s.filter(f=>f.position!=="top");if(l.length>0){if(!this.topAggregationContainer){this.topAggregationContainer=ft("top");const f=e.querySelector(".header");f&&f.nextSibling?t.insertBefore(this.topAggregationContainer,f.nextSibling):t.appendChild(this.topAggregationContainer)}pt(this.topAggregationContainer,l,this.visibleColumns,this.rows)}else this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null);const c=this.config.showRowCount!==!1||this.config.showSelectedCount&&r.selectedRows>0||this.config.showFilteredCount&&r.filteredRows!==r.totalRows||this.config.customPanels&&this.config.customPanels.length>0,d=c&&this.config.position!=="top",u=a.length>0||d;if(c&&this.config.position==="top")if(!this.infoBarElement)this.infoBarElement=Ae(this.config,r),t.insertBefore(this.infoBarElement,t.firstChild);else{const f=Ae(this.config,r);this.infoBarElement.replaceWith(f),this.infoBarElement=f}else this.config.position==="top"&&this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null);u?(this.footerWrapper||(this.footerWrapper=document.createElement("div"),this.footerWrapper.className="tbw-footer",t.appendChild(this.footerWrapper)),this.footerWrapper.innerHTML="",a.length>0&&(this.bottomAggregationContainer||(this.bottomAggregationContainer=ft("bottom")),this.footerWrapper.appendChild(this.bottomAggregationContainer),pt(this.bottomAggregationContainer,a,this.visibleColumns,this.rows)),d&&(this.infoBarElement=Ae(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&&this.config.position!=="top"&&(this.infoBarElement.remove(),this.infoBarElement=null)}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}getFilterState(){try{return this.grid?.getPluginState?.("filtering")??null}catch{return null}}refresh(){this.requestRender()}getContext(){const e=this.getSelectionState(),t=this.getFilterState();return gt(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())}styles=yn}const xn=pe;function En(o){const e=[];return!o.rowGroupFields?.length&&!o.columnGroupFields?.length&&e.push("At least one row or column group field is required"),o.valueFields?.length||e.push("At least one value field is required"),e}function ke(o,e){return[...o,e].join("|")}function Rn(o,e){const t=e.rowGroupFields??[],n=e.columnGroupFields??[],i=e.valueFields??[],r=_n(o,n),s=wt(o,t,n,r,i,0,""),l=An(s,r,i),a=Object.values(l).reduce((c,d)=>c+d,0);return{rows:s,columnKeys:r,totals:l,grandTotal:a}}function _n(o,e){if(e.length===0)return["value"];const t=new Set;for(const n of o){const i=e.map(r=>String(n[r]??"")).join("|");t.add(i)}return[...t].sort()}function Sn(o,e){const t=new Map;for(const n of o){const i=String(n[e]??""),r=t.get(i);r?r.push(n):t.set(i,[n])}return t}function wt(o,e,t,n,i,r,s){const l=[];if(e.length===0){const f=bt(o,t,n,i),h=mt(f);return l.push({rowKey:s||"all",rowLabel:s||"All",depth:r,values:f,total:h,isGroup:!1,rowCount:o.length}),l}const a=e[0],c=e.slice(1),d=c.length>0,u=Sn(o,a);for(const[f,h]of u){const p=s?`${s}|${f}`:f,g=bt(h,t,n,i),w=mt(g);let y;d&&(y=wt(h,c,t,n,i,r+1,p)),l.push({rowKey:p,rowLabel:f||"(blank)",depth:r,values:g,total:w,isGroup:d,children:y,rowCount:h.length})}return l}function bt(o,e,t,n){const i={};for(const r of t)for(const s of n){const a=(e.length>0?o.filter(f=>e.map(h=>String(f[h]??"")).join("|")===r):o).map(f=>Number(f[s.field])||0),c=xn(s.aggFunc),d=a.length>0?c(a):null,u=ke([r],s.field);i[u]=d}return i}function mt(o){let e=0;for(const t of Object.values(o))e+=t??0;return e}function An(o,e,t){const n={};function i(r){for(const s of r)if(!s.isGroup||!s.children?.length)for(const l of e)for(const a of t){const c=ke([l],a.field);n[c]=(n[c]??0)+(s.values[c]??0)}else s.children&&i(s.children)}return i(o),n}function kn(o,e,t=!0){const n=[];function i(r){n.push(r);const s=e?e.has(r.rowKey):t;if(r.children&&s)for(const l of r.children)i(l)}for(const r of o)i(r);return n}function Te(o){const e=[];function t(n){if(n.isGroup&&e.push(n.rowKey),n.children)for(const i of n.children)t(i)}for(const n of o)t(n);return e}const Tn=["sum","avg","count","min","max","first","last"];function Ln(o,e,t,n){const i=new AbortController,r={config:e,callbacks:n,signal:i.signal},s=document.createElement("div");return s.className="tbw-pivot-panel",s.appendChild(ne("Options",()=>Nn(t,r))),s.appendChild(ne("Row Groups",()=>vt("rowGroups",r))),s.appendChild(ne("Column Groups",()=>vt("columnGroups",r))),s.appendChild(ne("Values",()=>Mn(r))),s.appendChild(ne("Available Fields",()=>Hn(r))),o.appendChild(s),()=>{i.abort(),s.remove()}}function ne(o,e){const t=document.createElement("div");t.className="tbw-pivot-section";const n=document.createElement("div");n.className="tbw-pivot-section-header",n.textContent=o;const i=document.createElement("div");return i.className="tbw-pivot-section-content",i.appendChild(e()),t.appendChild(n),t.appendChild(i),t}function vt(o,e){const{config:t,callbacks:n,signal:i}=e,r=document.createElement("div");r.className="tbw-pivot-drop-zone",r.setAttribute("data-zone",o);const s=o==="rowGroups"?t.rowGroupFields??[]:t.columnGroupFields??[];if(s.length===0){const l=document.createElement("div");l.className="tbw-pivot-placeholder",l.textContent="Drag fields here or click to add",r.appendChild(l)}else for(const l of s)r.appendChild(Pn(l,o,e));return r.addEventListener("dragover",l=>{l.preventDefault(),r.classList.add("drag-over")},{signal:i}),r.addEventListener("dragleave",()=>{r.classList.remove("drag-over")},{signal:i}),r.addEventListener("drop",l=>{l.preventDefault(),r.classList.remove("drag-over");const a=l.dataTransfer?.getData("text/plain");a&&n.onAddFieldToZone(a,o)},{signal:i}),r}function Pn(o,e,t){const{callbacks:n,signal:i}=t,r=document.createElement("div");r.className="tbw-pivot-field-chip",r.draggable=!0;const s=n.getAvailableFields().find(c=>c.field===o),l=document.createElement("span");l.className="tbw-pivot-chip-label",l.textContent=s?.header??o;const a=document.createElement("button");return a.className="tbw-pivot-chip-remove",a.innerHTML="×",a.title="Remove field",a.addEventListener("click",c=>{c.stopPropagation(),n.onRemoveFieldFromZone(o,e)},{signal:i}),r.appendChild(l),r.appendChild(a),r.addEventListener("dragstart",c=>{c.dataTransfer?.setData("text/plain",o),c.dataTransfer?.setData("source-zone",e),r.classList.add("dragging")},{signal:i}),r.addEventListener("dragend",()=>{r.classList.remove("dragging")},{signal:i}),r}function Mn(o){const{config:e,callbacks:t,signal:n}=o,i=document.createElement("div");i.className="tbw-pivot-drop-zone tbw-pivot-values-zone",i.setAttribute("data-zone","values");const r=e.valueFields??[];if(r.length===0){const s=document.createElement("div");s.className="tbw-pivot-placeholder",s.textContent="Drag numeric fields here for aggregation",i.appendChild(s)}else for(const s of r)i.appendChild(In(s,o));return i.addEventListener("dragover",s=>{s.preventDefault(),i.classList.add("drag-over")},{signal:n}),i.addEventListener("dragleave",()=>{i.classList.remove("drag-over")},{signal:n}),i.addEventListener("drop",s=>{s.preventDefault(),i.classList.remove("drag-over");const l=s.dataTransfer?.getData("text/plain");l&&t.onAddValueField(l,"sum")},{signal:n}),i}function In(o,e){const{callbacks:t,signal:n}=e,i=document.createElement("div");i.className="tbw-pivot-field-chip tbw-pivot-value-chip";const r=t.getAvailableFields().find(d=>d.field===o.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=r?.header??o.field;const a=document.createElement("select");a.className="tbw-pivot-agg-select",a.title="Aggregation function";for(const d of Tn){const u=document.createElement("option");u.value=d,u.textContent=d.toUpperCase(),u.selected=d===o.aggFunc,a.appendChild(u)}a.addEventListener("change",()=>{t.onUpdateValueAggFunc(o.field,a.value)},{signal:n});const c=document.createElement("button");return c.className="tbw-pivot-chip-remove",c.innerHTML="×",c.title="Remove value field",c.addEventListener("click",d=>{d.stopPropagation(),t.onRemoveValueField(o.field)},{signal:n}),s.appendChild(l),s.appendChild(a),i.appendChild(s),i.appendChild(c),i}function Hn(o){const{config:e,callbacks:t,signal:n}=o,i=document.createElement("div");i.className="tbw-pivot-available-fields";const r=t.getAvailableFields(),s=new Set([...e.rowGroupFields??[],...e.columnGroupFields??[],...e.valueFields?.map(a=>a.field)??[]]),l=r.filter(a=>!s.has(a.field));if(l.length===0){const a=document.createElement("div");a.className="tbw-pivot-placeholder",a.textContent="All fields are in use",i.appendChild(a)}else for(const a of l){const c=document.createElement("div");c.className="tbw-pivot-field-chip available",c.textContent=a.header,c.draggable=!0,c.title=`Drag to add "${a.field}" to a zone`,c.addEventListener("dragstart",d=>{d.dataTransfer?.setData("text/plain",a.field),c.classList.add("dragging")},{signal:n}),c.addEventListener("dragend",()=>{c.classList.remove("dragging")},{signal:n}),i.appendChild(c)}return i}function Nn(o,e){const{config:t,callbacks:n,signal:i}=e,r=document.createElement("div");return r.className="tbw-pivot-options",r.appendChild(Le("Enable Pivot View",o,s=>{n.onTogglePivot(s)},i)),r.appendChild(Le("Show Row Totals",t.showTotals??!0,s=>{n.onOptionChange("showTotals",s)},i)),r.appendChild(Le("Show Grand Total",t.showGrandTotal??!0,s=>{n.onOptionChange("showGrandTotal",s)},i)),r}function Le(o,e,t,n){const i=document.createElement("label");i.className="tbw-pivot-checkbox";const r=document.createElement("input");r.type="checkbox",r.checked=e,r.addEventListener("change",()=>t(r.checked),{signal:n});const s=document.createElement("span");return s.textContent=o,i.appendChild(r),i.appendChild(s),i}function On(o,e,t){return e.className="pivot-group-row",e.setAttribute("data-pivot-depth",String(o.__pivotDepth??0)),e.setAttribute("data-pivot-key",String(o.__pivotRowKey??"")),e.setAttribute("role","row"),e.innerHTML="",t.columns.forEach((n,i)=>{const r=document.createElement("div");if(r.className="cell",r.setAttribute("data-col",String(i)),r.setAttribute("role","gridcell"),i===0){const s=Number(o.__pivotIndent)||0;r.style.paddingLeft=`${s}px`;const l=String(o.__pivotRowKey),a=document.createElement("button");a.type="button",a.className="pivot-toggle",a.setAttribute("aria-label",o.__pivotExpanded?"Collapse group":"Expand group"),t.setIcon(a,t.resolveIcon(o.__pivotExpanded?"collapse":"expand")),a.addEventListener("click",u=>{u.stopPropagation(),t.onToggle(l)}),r.appendChild(a);const c=document.createElement("span");c.className="pivot-label",c.textContent=String(o.__pivotLabel??""),r.appendChild(c);const d=document.createElement("span");d.className="pivot-count",d.textContent=` (${Number(o.__pivotRowCount)||0})`,r.appendChild(d)}else{const s=o[n.field];r.textContent=s!=null?String(s):""}e.appendChild(r)}),!0}function Dn(o,e,t){return e.className="pivot-leaf-row",e.setAttribute("data-pivot-depth",String(o.__pivotDepth??0)),e.setAttribute("data-pivot-key",String(o.__pivotRowKey??"")),e.innerHTML="",t.forEach((n,i)=>{const r=document.createElement("div");if(r.className="cell",r.setAttribute("data-col",String(i)),r.setAttribute("role","gridcell"),i===0){const s=Number(o.__pivotIndent)||0;r.style.paddingLeft=`${s+20}px`;const l=document.createElement("span");l.className="pivot-label",l.textContent=String(o.__pivotLabel??""),r.appendChild(l)}else{const s=o[n.field];r.textContent=s!=null?String(s):""}e.appendChild(r)}),!0}function zn(o,e,t){return e.className="pivot-grand-total-row",e.setAttribute("role","presentation"),e.innerHTML="",t.forEach((n,i)=>{const r=document.createElement("div");if(r.className="cell",r.setAttribute("data-col",String(i)),i===0){const s=document.createElement("span");s.className="pivot-label",s.textContent="Grand Total",r.appendChild(s)}else{const s=o[n.field];r.textContent=s!=null?String(s):""}e.appendChild(r)}),!0}const Fn='.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:18px;height:18px;margin-right:6px;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 .15s,color .15s}.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:12px;padding:12px;height:100%;overflow-y:auto;font-size:13px}.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:8px 12px;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:8px}.tbw-pivot-toggle-wrapper{display:flex;align-items:center}.tbw-pivot-toggle-label{display:flex;align-items:center;gap:8px;cursor:pointer}.tbw-pivot-toggle-label input{width:16px;height:16px;cursor:pointer}.tbw-pivot-drop-zone{min-height:60px;padding:8px;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:6px;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:8px;text-align:center;width:100%}.tbw-pivot-field-chip{display:inline-flex;align-items:center;gap:6px;padding:4px 8px;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:12px;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:16px;height:16px;padding:0;border:none;background:transparent;color:var(--tbw-color-fg-muted);font-size:14px;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:4px 8px}.tbw-pivot-value-label-wrapper{display:flex;align-items:center;gap:8px;flex:1;min-width:0}.tbw-pivot-agg-select{padding:2px 4px;font-size:11px;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:6px;min-height:40px}.tbw-pivot-options{display:flex;flex-direction:column;gap:8px}.tbw-pivot-checkbox{display:flex;align-items:center;gap:8px;cursor:pointer}.tbw-pivot-checkbox input{width:14px;height:14px;cursor:pointer}.pivot-group-row.tbw-pivot-slide-in,.pivot-leaf-row.tbw-pivot-slide-in{animation:tbw-pivot-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-pivot-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.pivot-group-row.tbw-pivot-fade-in,.pivot-leaf-row.tbw-pivot-fade-in{animation:tbw-pivot-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-pivot-fade-in{0%{opacity:0}to{opacity:1}}';class Y extends L{name="pivot";version="1.0.0";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;originalColumns=[];panelContainer=null;grandTotalFooter=null;previousVisibleKeys=new Set;keysToAnimate=new Set;hasValidPivotConfig(){return(this.config.valueFields?.length??0)>0}get animationStyle(){const t=this.grid.effectiveConfig?.animation?.mode??"reduced-motion";if(t===!1||t==="off")return!1;if(t!==!0&&t!=="on"){const n=this.shadowRoot?.host;if(n&&getComputedStyle(n).getPropertyValue("--tbw-animation-enabled").trim()==="0")return!1}return 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()}getToolPanel(){if((this.config?.showToolPanel??this.userConfig?.showToolPanel??!0)!==!1)return{id:Y.PANEL_ID,title:"Pivot",icon:"⊞",tooltip:"Configure pivot table",order:90,render:t=>this.renderPanel(t)}}processRows(e){if(!this.hasInitialized&&this.config.active!==!1&&this.hasValidPivotConfig()&&(this.hasInitialized=!0,this.isActive=!0),!this.isActive)return[...e];const t=En(this.config);if(t.length>0)return this.warn(`Config errors: ${t.join(", ")}`),[...e];if(this.buildFieldHeaderMap(),this.defaultExpanded=this.config.defaultExpanded??!0,this.expandedKeys.size===0&&this.defaultExpanded&&this.pivotResult){const s=Te(this.pivotResult.rows);for(const l of s)this.expandedKeys.add(l)}if(this.pivotResult=Rn(e,this.config),this.expandedKeys.size===0&&this.defaultExpanded){const s=Te(this.pivotResult.rows);for(const l of s)this.expandedKeys.add(l)}const n=this.config.indentWidth??20,i=kn(this.pivotResult.rows,this.expandedKeys,this.defaultExpanded).map(s=>({__pivotRowKey:s.rowKey,__pivotLabel:s.rowLabel,__pivotDepth:s.depth,__pivotIsGroup:s.isGroup,__pivotHasChildren:!!s.children?.length,__pivotExpanded:this.expandedKeys.has(s.rowKey),__pivotRowCount:s.rowCount??0,__pivotIndent:s.depth*n,__pivotTotal:s.total,...s.values}));this.keysToAnimate.clear();const r=new Set;for(const s of i){const l=s.__pivotRowKey;r.add(l),!this.previousVisibleKeys.has(l)&&s.__pivotDepth>0&&this.keysToAnimate.add(l)}return this.previousVisibleKeys=r,i}processColumns(e){if(!this.isActive||!this.pivotResult)return[...e];const t=[],n=(this.config.rowGroupFields??[]).map(i=>this.fieldHeaderMap.get(i)??i).join(" / ");t.push({field:"__pivotLabel",header:n||"Group",width:200});for(const i of this.pivotResult.columnKeys)for(const r of this.config.valueFields??[]){const s=ke([i],r.field),l=r.header||this.fieldHeaderMap.get(r.field)||r.field;t.push({field:s,header:`${i} - ${l} (${r.aggFunc})`,width:120,type:"number"})}return this.config.showTotals&&t.push({field:"__pivotTotal",header:"Total",width:100,type:"number"}),t}renderRow(e,t){const n=e;return n.__pivotRowKey&&n.__pivotHasChildren?On(n,t,{columns:this.gridColumns,onToggle:i=>this.toggle(i),resolveIcon:i=>this.resolveIcon(i),setIcon:(i,r)=>this.setIcon(i,r)}):n.__pivotRowKey!==void 0&&this.isActive?Dn(n,t,this.gridColumns):(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="")}afterRender(){this.isActive&&this.config.showGrandTotal&&this.pivotResult?this.renderGrandTotalFooter():this.cleanupGrandTotalFooter();const e=this.animationStyle;if(e===!1||this.keysToAnimate.size===0)return;const t=this.shadowRoot?.querySelector(".rows");if(!t)return;const n=e==="fade"?"tbw-pivot-fade-in":"tbw-pivot-slide-in";for(const i of t.querySelectorAll(".pivot-group-row, .pivot-leaf-row")){const r=i.dataset.pivotKey;r&&this.keysToAnimate.has(r)&&(i.classList.add(n),i.addEventListener("animationend",()=>i.classList.remove(n),{once:!0}))}this.keysToAnimate.clear()}renderGrandTotalFooter(){if(!this.pivotResult)return;const e=this.shadowRoot;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 n={__pivotRowKey:"__grandTotal",__pivotLabel:"Grand Total",__pivotIsGrandTotal:!0,__pivotTotal:this.pivotResult.grandTotal,...this.pivotResult.totals};zn(n,this.grandTotalFooter,this.gridColumns)}cleanupGrandTotalFooter(){this.grandTotalFooter&&(this.grandTotalFooter.remove(),this.grandTotalFooter=null)}toggle(e){this.expandedKeys.has(e)?this.expandedKeys.delete(e):this.expandedKeys.add(e),this.requestRender()}expand(e){this.expandedKeys.add(e),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}expandAll(){if(this.pivotResult){const e=Te(this.pivotResult.rows);for(const t of e)this.expandedKeys.add(t);this.requestRender()}}collapseAll(){this.expandedKeys.clear(),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}enablePivot(){this.originalColumns.length===0&&this.captureOriginalColumns(),this.isActive=!0,this.requestRender()}disablePivot(){this.isActive=!1,this.pivotResult=null,this.requestRender()}isPivotActive(){return this.isActive}getPivotResult(){return this.pivotResult}setRowGroupFields(e){this.config.rowGroupFields=e,this.requestRender()}setColumnGroupFields(e){this.config.columnGroupFields=e,this.requestRender()}setValueFields(e){this.config.valueFields=e,this.requestRender()}refresh(){this.pivotResult=null,this.requestRender()}showPanel(){this.grid.openToolPanel(Y.PANEL_ID)}hidePanel(){this.grid.closeToolPanel()}togglePanel(){this.grid.toggleToolPanel(Y.PANEL_ID)}isPanelVisible(){return this.grid.activeToolPanel===Y.PANEL_ID}get gridColumns(){return this.grid.columns??[]}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(){const e=this.grid;try{const t=e.getAllColumns?.()??e.columns??[];return this.originalColumns=t.filter(n=>!n.field.startsWith("__pivot")).map(n=>({field:n.field,header:n.header??n.field})),this.originalColumns}catch{return[]}}renderPanel(e){this.panelContainer=e,this.originalColumns.length===0&&this.captureOriginalColumns();const t={onTogglePivot:n=>{n?this.enablePivot():this.disablePivot(),this.refreshPanel()},onAddFieldToZone:(n,i)=>this.addFieldToZone(n,i),onRemoveFieldFromZone:(n,i)=>this.removeFieldFromZone(n,i),onAddValueField:(n,i)=>this.addValueField(n,i),onRemoveValueField:n=>this.removeValueField(n),onUpdateValueAggFunc:(n,i)=>this.updateValueAggFunc(n,i),onOptionChange:(n,i)=>{this.config[n]=i,this.isActive&&this.refresh()},getAvailableFields:()=>this.getAvailableFields()};return Ln(e,this.config,this.isActive,t)}refreshPanel(){this.panelContainer&&(this.panelContainer.innerHTML="",this.renderPanel(this.panelContainer))}addFieldToZone(e,t){if(t==="rowGroups"){const n=this.config.rowGroupFields??[];n.includes(e)||(this.config.rowGroupFields=[...n,e])}else{const n=this.config.columnGroupFields??[];n.includes(e)||(this.config.columnGroupFields=[...n,e])}this.removeFromOtherZones(e,t),this.isActive&&this.refresh(),this.refreshPanel()}removeFieldFromZone(e,t){t==="rowGroups"?this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(n=>n!==e):this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(n=>n!==e),this.isActive&&this.refresh(),this.refreshPanel()}removeFromOtherZones(e,t){t!=="rowGroups"&&(this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(n=>n!==e)),t!=="columnGroups"&&(this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(n=>n!==e)),t!=="values"&&(this.config.valueFields=(this.config.valueFields??[]).filter(n=>n.field!==e))}addValueField(e,t){const n=this.config.valueFields??[];n.some(i=>i.field===e)||(this.config.valueFields=[...n,{field:e,aggFunc:t}]),this.removeFromOtherZones(e,"values"),this.isActive&&this.refresh(),this.refreshPanel()}removeValueField(e){this.config.valueFields=(this.config.valueFields??[]).filter(t=>t.field!==e),this.isActive&&this.refresh(),this.refreshPanel()}updateValueAggFunc(e,t){const n=this.config.valueFields??[],i=n.findIndex(r=>r.field===e);i>=0&&(n[i]={...n[i],aggFunc:t},this.config.valueFields=[...n]),this.isActive&&this.refresh()}styles=Fn}function yt(o){const e=o.meta??{};return e.lockPosition!==!0&&e.suppressMovable!==!0}function Ct(o,e,t){if(e===t||e<0||e>=o.length||t<0||t>o.length)return o;const n=[...o],[i]=n.splice(e,1);return n.splice(t,0,i),n}const qn='.header-row>.cell[draggable=true]{cursor:grab;position:relative}.header-row>.cell.dragging{opacity:.5;cursor:grabbing}.header-row>.cell.drop-before:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.header-row>.cell.drop-after:after{content:"";position:absolute;right:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.cell.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}@keyframes reorder-fade-in{0%{opacity:0}to{opacity:1}}.cell.fade-animating{animation:reorder-fade-in var(--tbw-animation-duration, .2s) ease-out backwards}';class Bn extends L{name="reorder";version="1.0.0";get defaultConfig(){return{animation:"flip"}}get animationType(){return this.isAnimationEnabled?this.config.animation!==void 0?this.config.animation:this.config.viewTransition===!1?!1:(this.config.viewTransition===!0,"flip"):!1}get isAnimationEnabled(){const t=this.grid.effectiveConfig?.animation?.mode??"reduced-motion";if(t===!1||t==="off")return!1;if(t===!0||t==="on")return!0;const n=this.shadowRoot?.host;return n?getComputedStyle(n).getPropertyValue("--tbw-animation-enabled").trim()!=="0":!0}get animationDuration(){if(this.config.animationDuration!==void 0)return this.config.animationDuration;const e=this.shadowRoot?.host;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),n=parseInt(t,10);if(!isNaN(n))return n}return 200}isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;attach(e){super.attach(e),e.addEventListener("column-reorder-request",t=>{const n=t.detail;n?.field&&typeof n.toIndex=="number"&&this.moveColumn(n.field,n.toIndex)},{signal:this.disconnectSignal})}detach(){this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}afterRender(){const e=this.shadowRoot;if(!e)return;e.querySelectorAll(".header-row > .cell").forEach(n=>{const i=n,r=i.getAttribute("data-field");if(!r)return;const s=this.columns.find(d=>d.field===r),c=!this.grid.queryPlugins({type:ee.CAN_MOVE_COLUMN,context:s}).includes(!1);if(!s||!yt(s)||!c){i.draggable=!1;return}i.draggable=!0,!i.getAttribute("data-dragstart-bound")&&(i.setAttribute("data-dragstart-bound","true"),i.addEventListener("dragstart",d=>{const f=this.getColumnOrder().indexOf(r);this.isDragging=!0,this.draggedField=r,this.draggedIndex=f,d.dataTransfer&&(d.dataTransfer.effectAllowed="move",d.dataTransfer.setData("text/plain",r)),i.classList.add("dragging")}),i.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,e.querySelectorAll(".header-row > .cell").forEach(d=>{d.classList.remove("dragging","drop-target","drop-before","drop-after")})}),i.addEventListener("dragover",d=>{if(d.preventDefault(),!this.isDragging||this.draggedField===r)return;const u=i.getBoundingClientRect(),f=u.left+u.width/2,p=this.getColumnOrder().indexOf(r);this.dropIndex=d.clientX<f?p:p+1,i.classList.add("drop-target"),i.classList.toggle("drop-before",d.clientX<f),i.classList.toggle("drop-after",d.clientX>=f)}),i.addEventListener("dragleave",()=>{i.classList.remove("drop-target","drop-before","drop-after")}),i.addEventListener("drop",d=>{d.preventDefault();const u=this.draggedField,f=this.draggedIndex,h=this.dropIndex;if(!this.isDragging||u===null||f===null||h===null)return;const p=h>f?h-1:h,g=this.getColumnOrder(),w=Ct(g,f,p),y={field:u,fromIndex:f,toIndex:p,columnOrder:w};this.updateColumnOrder(w),this.emit("column-move",y)}))})}onKeyDown(e){if(!e.altKey||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const t=this.grid,n=t._focusCol,i=t._visibleColumns;if(n<0||n>=i.length)return;const r=i[n];if(!r||!yt(r))return;const s=this.grid;if(s.queryPlugins({type:ee.CAN_MOVE_COLUMN,context:r}).includes(!1))return;const a=this.getColumnOrder(),c=a.indexOf(r.field);if(c===-1)return;const d=e.key==="ArrowLeft"?c-1:c+1;if(d<0||d>=a.length)return;const u=i.find(f=>f.field===a[d]);if(!(u&&s.queryPlugins({type:ee.CAN_MOVE_COLUMN,context:u}).includes(!1)))return this.moveColumn(r.field,d),t._focusCol=d,D(this.grid),e.preventDefault(),e.stopPropagation(),!0}getColumnOrder(){return this.grid.getColumnOrder()}moveColumn(e,t){const n=this.getColumnOrder(),i=n.indexOf(e);if(i===-1)return;const r=Ct(n,i,t);this.updateColumnOrder(r),this.emit("column-move",{field:e,fromIndex:i,toIndex:t,columnOrder:r})}setColumnOrder(e){this.updateColumnOrder(e)}resetColumnOrder(){const e=this.columns.map(t=>t.field);this.updateColumnOrder(e)}captureHeaderPositions(){const e=new Map;return this.shadowRoot?.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const n=t.getAttribute("data-field");n&&e.set(n,t.getBoundingClientRect().left)}),e}animateFLIP(e){const t=this.shadowRoot;if(!t||e.size===0)return;const n=new Map;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(s=>{const l=s.getAttribute("data-field");if(!l)return;const a=e.get(l);if(a===void 0)return;const c=a-s.getBoundingClientRect().left;Math.abs(c)>1&&n.set(l,c)}),n.size===0)return;const i=[];if(t.querySelectorAll(".cell[data-field]").forEach(s=>{const l=n.get(s.getAttribute("data-field")??"");if(l!==void 0){const a=s;a.style.transform=`translateX(${l}px)`,i.push(a)}}),i.length===0)return;t.host.offsetHeight;const r=this.animationDuration;requestAnimationFrame(()=>{i.forEach(s=>{s.classList.add("flip-animating"),s.style.transform=""}),setTimeout(()=>{i.forEach(s=>{s.style.transform="",s.classList.remove("flip-animating")})},r+50)})}animateFade(e){const t=this.shadowRoot;if(!t){e();return}const n=this.captureHeaderPositions();e();const i=new Set;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(l=>{const a=l.getAttribute("data-field");if(!a)return;const c=n.get(a);if(c===void 0)return;const d=l.getBoundingClientRect().left;Math.abs(c-d)>1&&i.add(a)}),i.size===0)return;const r=[];if(t.querySelectorAll(".cell[data-field]").forEach(l=>{const a=l.getAttribute("data-field");if(a&&i.has(a)){const c=l;c.classList.add("fade-animating"),r.push(c)}}),r.length===0)return;const s=this.animationDuration;setTimeout(()=>{r.forEach(l=>l.classList.remove("fade-animating"))},s+50)}updateColumnOrder(e){const t=this.grid,n=this.animationType;if(n==="flip"&&this.shadowRoot){const i=this.captureHeaderPositions();t.setColumnOrder(e),this.shadowRoot.host.offsetHeight,this.animateFLIP(i)}else n==="fade"?this.animateFade(()=>t.setColumnOrder(e)):t.setColumnOrder(e);t.requestStateChange?.()}styles=qn}function re(o){return{startRow:Math.min(o.startRow,o.endRow),startCol:Math.min(o.startCol,o.endCol),endRow:Math.max(o.startRow,o.endRow),endCol:Math.max(o.startCol,o.endCol)}}function Kn(o){const e=re(o);return{from:{row:e.startRow,col:e.startCol},to:{row:e.endRow,col:e.endCol}}}function Pe(o){return o.map(Kn)}function Vn(o,e,t){const n=re(t);return o>=n.startRow&&o<=n.endRow&&e>=n.startCol&&e<=n.endCol}function xt(o,e,t){return t.some(n=>Vn(o,e,n))}function $n(o){const e=[],t=re(o);for(let n=t.startRow;n<=t.endRow;n++)for(let i=t.startCol;i<=t.endCol;i++)e.push({row:n,col:i});return e}function Gn(o){const e=new Map;for(const t of o)for(const n of $n(t))e.set(`${n.row},${n.col}`,n);return[...e.values()]}function Me(o,e){return{startRow:o.row,startCol:o.col,endRow:e.row,endCol:e.col}}const Wn=':host .selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}:host .data-grid-row.row-focus{background-color:var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%))}:host([data-selection-mode="row"]) .cell-focus{outline:none}:host .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg)}:host .data-grid-row>.cell.selected.top{border-top:2px solid var(--tbw-range-border-color)}:host .data-grid-row>.cell.selected.bottom{border-bottom:2px solid var(--tbw-range-border-color)}:host .data-grid-row>.cell.selected.first{border-left:2px solid var(--tbw-range-border-color)}:host .data-grid-row>.cell.selected.last{border-right:2px solid var(--tbw-range-border-color)}';function Un(o,e,t){if(o==="cell"&&e.selectedCell)return{mode:o,ranges:[{from:{row:e.selectedCell.row,col:e.selectedCell.col},to:{row:e.selectedCell.row,col:e.selectedCell.col}}]};if(o==="row"&&e.selected.size>0){const n=[...e.selected].map(i=>({from:{row:i,col:0},to:{row:i,col:t-1}}));return{mode:o,ranges:n}}return o==="range"&&e.ranges.length>0?{mode:o,ranges:Pe(e.ranges)}:{mode:o,ranges:[]}}class jn extends L{name="selection";version="1.0.0";get defaultConfig(){return{mode:"cell"}}selected=new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;selectedCell=null;detach(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.pendingKeyboardUpdate=null}onCellClick(e){const{rowIndex:t,colIndex:n,originalEvent:i}=e,{mode:r}=this.config;if(r==="cell")return this.selectedCell={row:t,col:n},this.emit("selection-change",this.#r()),this.requestAfterRender(),!1;if(r==="row")return this.selected.clear(),this.selected.add(t),this.lastSelected=t,this.emit("selection-change",this.#r()),this.requestAfterRender(),!1;if(r==="range"){const s=i.shiftKey,l=i.ctrlKey||i.metaKey;if(s&&this.cellAnchor){const a=Me(this.cellAnchor,{row:t,col:n});l?this.ranges.length>0?this.ranges[this.ranges.length-1]=a:this.ranges.push(a):this.ranges=[a],this.activeRange=a}else if(l){const a={startRow:t,startCol:n,endRow:t,endCol:n};this.ranges.push(a),this.activeRange=a,this.cellAnchor={row:t,col:n}}else{const a={startRow:t,startCol:n,endRow:t,endCol:n};this.ranges=[a],this.activeRange=a,this.cellAnchor={row:t,col:n}}return this.emit("selection-change",this.#r()),this.requestAfterRender(),!1}return!1}onKeyDown(e){const{mode:t}=this.config,i=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"].includes(e.key);if(e.key==="Escape")return t==="cell"?this.selectedCell=null:t==="row"?(this.selected.clear(),this.anchor=null):t==="range"&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#r()),this.requestAfterRender(),!0;if(t==="cell"&&i)return queueMicrotask(()=>{this.selectedCell={row:this.grid._focusRow,col:this.grid._focusCol},this.emit("selection-change",this.#r()),this.requestAfterRender()}),!1;if(t==="row"&&(e.key==="ArrowUp"||e.key==="ArrowDown"))return queueMicrotask(()=>{this.selected.clear(),this.selected.add(this.grid._focusRow),this.lastSelected=this.grid._focusRow,this.emit("selection-change",this.#r()),this.requestAfterRender()}),!1;if(t==="range"&&i)return e.shiftKey&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:e.shiftKey},queueMicrotask(()=>this.requestAfterRender()),!1;if(t==="range"&&e.key==="a"&&(e.ctrlKey||e.metaKey)){const r=this.rows.length,s=this.columns.length;if(r>0&&s>0){const l={startRow:0,startCol:0,endRow:r-1,endCol:s-1};return this.ranges=[l],this.activeRange=l,this.emit("selection-change",this.#r()),this.requestAfterRender(),!0}}return!1}onCellMouseDown(e){if(this.config.mode!=="range"||e.rowIndex===void 0||e.colIndex===void 0||e.rowIndex<0||e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const t=e.rowIndex,n=e.colIndex;this.cellAnchor={row:t,col:n},e.originalEvent.ctrlKey||e.originalEvent.metaKey||(this.ranges=[]);const r={startRow:t,startCol:n,endRow:t,endCol:n};return this.ranges.push(r),this.activeRange=r,this.emit("selection-change",this.#r()),this.requestAfterRender(),!0}onCellMouseMove(e){if(this.config.mode!=="range"||!this.isDragging||!this.cellAnchor||e.rowIndex===void 0||e.colIndex===void 0||e.rowIndex<0)return;const t=Me(this.cellAnchor,{row:e.rowIndex,col:e.colIndex});return this.ranges.length>0?this.ranges[this.ranges.length-1]=t:this.ranges.push(t),this.activeRange=t,this.emit("selection-change",this.#r()),this.requestAfterRender(),!0}onCellMouseUp(e){if(this.config.mode==="range"&&this.isDragging)return this.isDragging=!1,!0}#o(){const e=this.shadowRoot;if(!e)return;const{mode:t}=this.config;e.querySelectorAll(".cell").forEach(r=>{r.classList.remove("selected","top","bottom","first","last")});const i=e.querySelectorAll(".data-grid-row");if(i.forEach(r=>{r.classList.remove("selected","row-focus")}),t==="row"&&(e.querySelectorAll(".cell-focus").forEach(r=>r.classList.remove("cell-focus")),i.forEach(r=>{const s=r.querySelector(".cell[data-row]"),l=parseInt(s?.getAttribute("data-row")??"-1",10);l>=0&&this.selected.has(l)&&r.classList.add("selected","row-focus")})),t==="range"&&this.ranges.length>0){const r=this.activeRange?re(this.activeRange):null;e.querySelectorAll(".cell[data-row][data-col]").forEach(l=>{const a=parseInt(l.getAttribute("data-row")??"-1",10),c=parseInt(l.getAttribute("data-col")??"-1",10);a>=0&&c>=0&&xt(a,c,this.ranges)&&(l.classList.add("selected"),l.classList.remove("cell-focus"),r&&(a===r.startRow&&l.classList.add("top"),a===r.endRow&&l.classList.add("bottom"),c===r.startCol&&l.classList.add("first"),c===r.endCol&&l.classList.add("last")))})}t==="cell"&&this.selectedCell&&e.querySelectorAll(".cell-focus").forEach(r=>r.classList.remove("cell-focus"))}afterRender(){const e=this.shadowRoot;if(!e)return;const t=e.children[0],{mode:n}=this.config;if(this.pendingKeyboardUpdate&&n==="range"){const{shiftKey:i}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const r=this.grid._focusRow,s=this.grid._focusCol;if(i&&this.cellAnchor){const l=Me(this.cellAnchor,{row:r,col:s});this.ranges=[l],this.activeRange=l}else i||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:r,col:s});this.emit("selection-change",this.#r())}this.grid.setAttribute("data-selection-mode",n),t&&t.classList.toggle("selecting",this.isDragging),this.#o()}onScrollRender(){this.#o()}getSelectedCell(){return this.selectedCell}getSelectedRows(){return[...this.selected]}getRanges(){return Pe(this.ranges)}getSelectedCells(){return Gn(this.ranges)}isCellSelected(e,t){return xt(e,t,this.ranges)}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.emit("selection-change",{mode:this.config.mode,ranges:[]}),this.requestAfterRender()}setRanges(e){this.ranges=e.map(t=>({startRow:t.from.row,startCol:t.from.col,endRow:t.to.row,endCol:t.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",{mode:this.config.mode,ranges:Pe(this.ranges)}),this.requestAfterRender()}#r(){return Un(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}styles=Wn}function se(o,e){return Math.floor(o/e)}function Xn(o,e){return{start:o*e,end:(o+1)*e}}function Yn(o,e,t){const n=se(o,t),i=se(e-1,t),r=[];for(let s=n;s<=i;s++)r.push(s);return r}async function Et(o,e,t,n){const i=Xn(e,t);return o.getRows({startRow:i.start,endRow:i.end,sortModel:n.sortModel,filterModel:n.filterModel})}function Zn(o,e,t){const n=se(o,e),i=t.get(n);if(!i)return;const r=o%e;return i[r]}const Jn=100;class Qn extends L{name="serverSide";version="1.0.0";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,n={startRow:e._virtualization.start,endRow:e._virtualization.end},i=Yn(n.startRow,n.endRow,t);for(const r of i)if(!(this.loadedBlocks.has(r)||this.loadingBlocks.has(r))){if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2))break;this.loadingBlocks.add(r),Et(this.dataSource,r,t,{}).then(s=>{this.loadedBlocks.set(r,s.rows),this.totalRowCount=s.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 n=0;n<this.totalRowCount;n++){const i=Zn(n,this.config.cacheBlockSize??100,this.loadedBlocks);t.push(i??{__loading:!0,__index:n})}return t}onScroll(e){this.dataSource&&(this.loadRequiredBlocks(),this.scrollDebounceTimer&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.loadRequiredBlocks()},Jn))}setDataSource(e){this.dataSource=e,this.loadedBlocks.clear(),this.loadingBlocks.clear();const t=this.config.cacheBlockSize??100;Et(e,0,t,{}).then(n=>{this.loadedBlocks.set(0,n.rows),this.totalRowCount=n.totalRowCount,this.requestRender()})}refresh(){this.dataSource&&(this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.requestRender())}purgeCache(){this.loadedBlocks.clear()}getTotalRowCount(){return this.totalRowCount}isRowLoaded(e){const t=this.config.cacheBlockSize??100,n=se(e,t);return this.loadedBlocks.has(n)}getLoadedBlockCount(){return this.loadedBlocks.size}}function Rt(o,e,t){return o.id!==void 0?String(o.id):t?`${t}-${e}`:String(e)}function _t(o,e){const t=new Set(o);return t.has(e)?t.delete(e):t.add(e),t}function Ie(o,e,t=null,n=0){const i=e.childrenField??"children",r=new Set;for(let s=0;s<o.length;s++){const l=o[s],a=Rt(l,s,t),c=l[i];if(Array.isArray(c)&&c.length>0){r.add(a);const d=Ie(c,e,a,n+1);for(const u of d)r.add(u)}}return r}function ei(){return new Set}function St(o,e,t,n=null,i=0){const r=t.childrenField??"children";for(let s=0;s<o.length;s++){const l=o[s],a=Rt(l,s,n);if(a===e)return[a];const c=l[r];if(Array.isArray(c)&&c.length>0){const d=St(c,e,t,a,i+1);if(d)return[a,...d]}}return null}function ti(o,e,t,n){const i=St(o,e,t);if(!i)return n;const r=new Set(n);for(let s=0;s<i.length-1;s++)r.add(i[s]);return r}function At(o,e="children"){if(!Array.isArray(o)||o.length===0)return!1;for(const t of o)if(t&&Array.isArray(t[e])&&t[e].length>0)return!0;return!1}function oi(o){if(!Array.isArray(o)||o.length===0)return null;const e=["children","items","nodes","subRows","nested"];for(const t of o)if(!(!t||typeof t!="object")){for(const n of e)if(Array.isArray(t[n])&&t[n].length>0)return n}return null}const ni=".tree-cell{display:flex;align-items:center;padding-left:calc(var(--tree-depth, 0) * var(--tbw-tree-indent, 20px))}.tree-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;margin-right:4px}.tree-toggle:hover{color:var(--tbw-tree-accent, var(--tbw-color-accent))}.tree-spacer{width:14px;display:inline-block}.data-grid-row.tbw-tree-slide-in{animation:tbw-tree-slide-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)}}.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-fade-in{0%{opacity:0}to{opacity:1}}";class ii extends L{name="tree";version="1.0.0";styles=ni;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}get animationStyle(){const t=this.grid.effectiveConfig?.animation?.mode??"reduced-motion";if(t===!1||t==="off")return!1;if(t!==!0&&t!=="on"){const n=this.shadowRoot?.host;if(n&&getComputedStyle(n).getPropertyValue("--tbw-animation-enabled").trim()==="0")return!1}return this.config.animation??"slide"}detect(e){if(!this.config.autoDetect)return!1;const t=this.config.childrenField??oi(e)??"children";return At(e,t)}processRows(e){const t=this.config.childrenField??"children";if(!At(e,t))return this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),[...e];let n=this.withStableKeys(e);this.sortState&&(n=this.sortTree(n,this.sortState.field,this.sortState.direction)),this.config.defaultExpanded&&!this.initialExpansionDone&&(this.expandedKeys=Ie(n,this.config),this.initialExpansionDone=!0),this.flattenedRows=this.flattenTree(n,this.expandedKeys),this.rowKeyMap.clear(),this.keysToAnimate.clear();const i=new Set;for(const r of this.flattenedRows)this.rowKeyMap.set(r.key,r),i.add(r.key),!this.previousVisibleKeys.has(r.key)&&r.depth>0&&this.keysToAnimate.add(r.key);return this.previousVisibleKeys=i,this.flattenedRows.map(r=>({...r.data,__treeKey:r.key,__treeDepth:r.depth,__treeHasChildren:r.hasChildren,__treeExpanded:r.isExpanded}))}withStableKeys(e,t=null){const n=this.config.childrenField??"children";return e.map((i,r)=>{const s=i.id!==void 0?String(i.id):i.__stableKey??(t?`${t}-${r}`:String(r)),l=i[n],a=Array.isArray(l)&&l.length>0;return{...i,__stableKey:s,...a?{[n]:this.withStableKeys(l,s)}:{}}})}flattenTree(e,t,n=0){const i=this.config.childrenField??"children",r=[];for(const s of e){const l=s.__stableKey??s.id??"?",a=s[i],c=Array.isArray(a)&&a.length>0,d=t.has(l);r.push({key:l,data:s,depth:n,hasChildren:c,isExpanded:d,parentKey:n>0&&l.substring(0,l.lastIndexOf("-"))||null}),c&&d&&r.push(...this.flattenTree(a,t,n+1))}return r}sortTree(e,t,n){const i=this.config.childrenField??"children";return[...e].sort((s,l)=>{const a=s[t],c=l[t];return a==null&&c==null?0:a==null?-1:c==null?1:a>c?n:a<c?-n:0}).map(s=>{const l=s[i];return Array.isArray(l)&&l.length>0?{...s,[i]:this.sortTree(l,t,n)}:s})}processColumns(e){if(this.flattenedRows.length===0)return[...e];const t=[...e];if(t.length===0)return t;const n={...t[0]},i=n.viewRenderer;if(i?.__treeWrapped)return t;const r=()=>this.config,s=this.setIcon.bind(this),l=this.resolveIcon.bind(this),a=c=>{const{value:d,row:u}=c,{indentWidth:f=20,showExpandIcons:h=!0}=r(),p=document.createElement("span");if(p.className="tree-cell",p.style.setProperty("--tree-depth",String(u.__treeDepth??0)),p.style.setProperty("--tbw-tree-indent",`${f}px`),u.__treeHasChildren&&h){const w=document.createElement("span");w.className=`tree-toggle${u.__treeExpanded?" expanded":""}`,s(w,l(u.__treeExpanded?"collapse":"expand")),w.setAttribute("data-tree-key",u.__treeKey),p.appendChild(w)}else if(h){const w=document.createElement("span");w.className="tree-spacer",p.appendChild(w)}const g=document.createElement("span");if(i){const w=i(c);w instanceof Node?g.appendChild(w):g.textContent=String(w??d??"")}else g.textContent=String(d??"");return p.appendChild(g),p};return a.__treeWrapped=!0,n.viewRenderer=a,t[0]=n,t}onCellClick(e){const t=e.originalEvent?.target;if(!t?.classList.contains("tree-toggle"))return!1;const n=t.getAttribute("data-tree-key"),i=n?this.rowKeyMap.get(n):null;return i?(this.expandedKeys=_t(this.expandedKeys,n),this.emit("tree-expand",{key:n,row:i.data,expanded:this.expandedKeys.has(n),depth:i.depth}),this.requestRender(),!0):!1}onHeaderClick(e){if(this.flattenedRows.length===0||!e.column.sortable)return!1;const{field:t}=e.column;!this.sortState||this.sortState.field!==t?this.sortState={field:t,direction:1}:this.sortState.direction===1?this.sortState={field:t,direction:-1}:this.sortState=null;const n=this.grid;return n._sortState!==void 0&&(n._sortState=this.sortState?{...this.sortState}:null),this.emit("sort-change",{field:t,direction:this.sortState?.direction??0}),this.requestRender(),!0}afterRender(){const e=this.animationStyle;if(e===!1||this.keysToAnimate.size===0)return;const t=this.shadowRoot?.querySelector(".rows");if(!t)return;const n=e==="fade"?"tbw-tree-fade-in":"tbw-tree-slide-in";for(const i of t.querySelectorAll(".data-grid-row")){const r=i.querySelector(".cell[data-row]"),s=r?parseInt(r.getAttribute("data-row")??"-1",10):-1,l=this.flattenedRows[s]?.key;l&&this.keysToAnimate.has(l)&&(i.classList.add(n),i.addEventListener("animationend",()=>i.classList.remove(n),{once:!0}))}this.keysToAnimate.clear()}expand(e){this.expandedKeys.add(e),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}toggle(e){this.expandedKeys=_t(this.expandedKeys,e),this.requestRender()}expandAll(){this.expandedKeys=Ie(this.rows,this.config),this.requestRender()}collapseAll(){this.expandedKeys=ei(),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=ti(this.rows,e,this.config,this.expandedKeys),this.requestRender()}}function ri(o,e,t){const n=[...o.undoStack,e];for(;n.length>t;)n.shift();return{undoStack:n,redoStack:[]}}function kt(o){if(o.undoStack.length===0)return{newState:o,action:null};const e=[...o.undoStack],t=e.pop();return t?{newState:{undoStack:e,redoStack:[...o.redoStack,t]},action:t}:{newState:o,action:null}}function Tt(o){if(o.redoStack.length===0)return{newState:o,action:null};const e=[...o.redoStack],t=e.pop();return t?{newState:{undoStack:[...o.undoStack,t],redoStack:e},action:t}:{newState:o,action:null}}function si(o){return o.undoStack.length>0}function li(o){return o.redoStack.length>0}function ai(){return{undoStack:[],redoStack:[]}}function ci(o,e,t,n){return{type:"cell-edit",rowIndex:o,field:e,oldValue:t,newValue:n,timestamp:Date.now()}}class di extends L{name="undoRedo";version="1.0.0";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];detach(){this.undoStack=[],this.redoStack=[]}onKeyDown(e){const t=(e.ctrlKey||e.metaKey)&&e.key==="z"&&!e.shiftKey,n=(e.ctrlKey||e.metaKey)&&(e.key==="y"||e.key==="z"&&e.shiftKey);if(t){const i=kt({undoStack:this.undoStack,redoStack:this.redoStack});if(i.action){const r=this.rows;r[i.action.rowIndex]&&(r[i.action.rowIndex][i.action.field]=i.action.oldValue),this.undoStack=i.newState.undoStack,this.redoStack=i.newState.redoStack,this.emit("undo",{action:i.action,type:"undo"}),this.requestRender()}return!0}if(n){const i=Tt({undoStack:this.undoStack,redoStack:this.redoStack});if(i.action){const r=this.rows;r[i.action.rowIndex]&&(r[i.action.rowIndex][i.action.field]=i.action.newValue),this.undoStack=i.newState.undoStack,this.redoStack=i.newState.redoStack,this.emit("redo",{action:i.action,type:"redo"}),this.requestRender()}return!0}return!1}recordEdit(e,t,n,i){const r=ci(e,t,n,i),s=ri({undoStack:this.undoStack,redoStack:this.redoStack},r,this.config.maxHistorySize??100);this.undoStack=s.undoStack,this.redoStack=s.redoStack}undo(){const e=kt({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=Tt({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 si({undoStack:this.undoStack,redoStack:this.redoStack})}canRedo(){return li({undoStack:this.undoStack,redoStack:this.redoStack})}clearHistory(){const e=ai();this.undoStack=e.undoStack,this.redoStack=e.redoStack}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}}const ui='.tbw-visibility-content{display:flex;flex-direction:column;height:100%}.tbw-visibility-list{flex:1;overflow-y:auto;padding:8px}.tbw-visibility-row{display:flex;align-items:center;gap:8px;padding:6px 4px;cursor:pointer;font-size:13px;border-radius:var(--tbw-border-radius, 4px);position:relative}.tbw-visibility-row:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover, #f3f4f6))}.tbw-visibility-row input[type=checkbox]{cursor:pointer}.tbw-visibility-row.locked span{color:var(--tbw-color-fg-muted, #888)}.tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted, #888);font-size:10px;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, #1f2937)}.tbw-visibility-label{display:flex;align-items:center;gap:8px;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-reorder-indicator, var(--tbw-color-accent, #3b82f6))}.tbw-visibility-row.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent, #3b82f6))}.tbw-visibility-show-all{margin:8px;padding:8px 12px;border:1px solid var(--tbw-visibility-border, var(--tbw-color-border, #e5e7eb));border-radius:var(--tbw-border-radius, 4px);background:var(--tbw-visibility-btn-bg, var(--tbw-color-header-bg, #f9fafb));color:var(--tbw-color-fg, #1f2937);cursor:pointer;font-size:13px}.tbw-visibility-show-all:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover, #f3f4f6))}';function Lt(o){const e=o.meta??{};return e.lockPosition!==!0&&e.suppressMovable!==!0}class Z extends L{name="visibility";version="1.0.0";static PANEL_ID="columns";get defaultConfig(){return{allowHideAll:!1}}columnListElement=null;isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;detach(){this.columnListElement=null,this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}getToolPanel(){return{id:Z.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(Z.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.toggleToolPanel(Z.PANEL_ID)}isColumnVisible(e){return this.grid.isColumnVisible(e)}setColumnVisible(e,t){this.grid.setColumnVisible(e,t)}getVisibleColumns(){return this.grid.getAllColumns().filter(t=>t.visible).map(t=>t.field)}getHiddenColumns(){return this.grid.getAllColumns().filter(t=>!t.visible).map(t=>t.field)}showAll(){this.grid.showAllColumns()}toggleColumn(e){this.grid.toggleColumnVisibility(e)}showColumn(e){this.grid.setColumnVisible(e,!0)}hideColumn(e){this.grid.setColumnVisible(e,!1)}getAllColumns(){return this.grid.getAllColumns()}isPanelVisible(){return this.grid.activeToolPanel===Z.PANEL_ID}renderPanelContent(e){const t=this.grid,n=document.createElement("div");n.className="tbw-visibility-content";const i=document.createElement("div");i.className="tbw-visibility-list",n.appendChild(i);const r=document.createElement("button");return r.className="tbw-visibility-show-all",r.textContent="Show All",r.addEventListener("click",()=>{t.showAllColumns(),this.rebuildToggles(i)}),n.appendChild(r),this.columnListElement=i,this.rebuildToggles(i),e.appendChild(n),()=>{this.columnListElement=null,n.remove()}}hasReorderPlugin(){const e=this.grid?.getPluginByName?.("reorder");return!!(e&&typeof e.moveColumn=="function")}rebuildToggles(e){const t=this.grid,n=this.hasReorderPlugin();e.innerHTML="";const i=t.getAllColumns();for(let r=0;r<i.length;r++){const s=i[r],l=s.header||s.field,a=document.createElement("div");a.className=s.lockVisible?"tbw-visibility-row locked":"tbw-visibility-row",a.setAttribute("data-field",s.field),a.setAttribute("data-index",String(r)),n&&Lt(s)&&(a.draggable=!0,a.classList.add("reorderable"),this.setupDragListeners(a,s.field,r,e));const c=document.createElement("label");c.className="tbw-visibility-label";const d=document.createElement("input");d.type="checkbox",d.checked=s.visible,d.disabled=s.lockVisible??!1,d.addEventListener("change",()=>{t.toggleColumnVisibility(s.field),setTimeout(()=>this.rebuildToggles(e),0)});const u=document.createElement("span");if(u.textContent=l,c.appendChild(d),c.appendChild(u),n&&Lt(s)){const f=document.createElement("span");f.className="tbw-visibility-handle",this.setIcon(f,this.resolveIcon("dragHandle")),f.title="Drag to reorder",a.appendChild(f)}a.appendChild(c),e.appendChild(a)}}setupDragListeners(e,t,n,i){e.addEventListener("dragstart",r=>{this.isDragging=!0,this.draggedField=t,this.draggedIndex=n,r.dataTransfer&&(r.dataTransfer.effectAllowed="move",r.dataTransfer.setData("text/plain",t)),e.classList.add("dragging")}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,i.querySelectorAll(".tbw-visibility-row").forEach(r=>{r.classList.remove("dragging","drop-target","drop-before","drop-after")})}),e.addEventListener("dragover",r=>{if(r.preventDefault(),!this.isDragging||this.draggedField===t)return;const s=e.getBoundingClientRect(),l=s.top+s.height/2;this.dropIndex=r.clientY<l?n:n+1,i.querySelectorAll(".tbw-visibility-row").forEach(a=>{a!==e&&a.classList.remove("drop-target","drop-before","drop-after")}),e.classList.add("drop-target"),e.classList.toggle("drop-before",r.clientY<l),e.classList.toggle("drop-after",r.clientY>=l)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",r=>{r.preventDefault();const s=this.draggedField,l=this.draggedIndex,a=this.dropIndex;if(!this.isDragging||s===null||l===null||a===null)return;const c=a>l?a-1:a;if(c!==l){const d={field:s,fromIndex:l,toIndex:c};this.emit("column-reorder-request",d),setTimeout(()=>{this.rebuildToggles(i)},0)}})}styles=ui}C.BaseGridPlugin=L,C.ClipboardPlugin=Ro,C.ColumnVirtualizationPlugin=ko,C.ContextMenuPlugin=Po,C.DEFAULT_ANIMATION_CONFIG=Ne,C.DEFAULT_GRID_ICONS=I,C.DGEvents=bo,C.DataGridElement=V,C.ExportPlugin=Oo,C.FilteringPlugin=q,C.FitModeEnum=$,C.GridCSSVars=wo,C.GridClasses=M,C.GridDataAttrs=te,C.GridElement=V,C.GridSelectors=go,C.GroupingColumnsPlugin=Xo,C.GroupingRowsPlugin=on,C.MasterDetailPlugin=cn,C.MultiSortPlugin=pn,C.PLUGIN_QUERIES=ee,C.PinnedColumnsPlugin=bn,C.PinnedRowsPlugin=Cn,C.PivotPlugin=Y,C.PluginEvents=mo,C.PluginManager=Ze,C.ReorderPlugin=Bn,C.SelectionPlugin=jn,C.ServerSidePlugin=Qn,C.TreePlugin=ii,C.UndoRedoPlugin=di,C.VisibilityPlugin=Z,C.aggregatorRegistry=N,C.builtInSort=Ve,C.defaultComparator=Ke,C.getAggregator=ge,C.getValueAggregator=pe,C.listAggregators=xo,C.registerAggregator=yo,C.runAggregator=we,C.runValueAggregator=vo,C.unregisterAggregator=Co,Object.defineProperty(C,Symbol.toStringTag,{value:"Module"})}));
92
+ </Workbook>`,n}function No(o,e){const t=e.endsWith(".xls")?e:`${e}.xls`,n=new Blob([o],{type:"application/vnd.ms-excel;charset=utf-8;"});Re(n,t)}class Do extends L{name="export";version="1.0.0";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;performExport(e,t){const n=this.config,i={format:e,fileName:t?.fileName??n.fileName??"export",includeHeaders:t?.includeHeaders??n.includeHeaders,processCell:t?.processCell,processHeader:t?.processHeader,columns:t?.columns,rowIndices:t?.rowIndices};let r=[...this.columns];if(n.onlyVisible&&(r=r.filter(a=>!a.hidden&&!a.field.startsWith("__"))),t?.columns){const a=new Set(t.columns);r=r.filter(c=>a.has(c.field))}let s=[...this.rows];if(n.onlySelected){const a=this.getSelectionState();a?.selected?.size&&(s=[...a.selected].sort((d,u)=>d-u).map(d=>this.rows[d]).filter(Boolean))}t?.rowIndices&&(s=t.rowIndices.map(a=>this.rows[a]).filter(Boolean)),this.isExportingFlag=!0;let l=i.fileName;try{switch(e){case"csv":{const a=Mo(s,r,i,{bom:!0});l=l.endsWith(".csv")?l:`${l}.csv`,Io(a,l);break}case"excel":{const a=Ho(s,r,i);l=l.endsWith(".xls")?l:`${l}.xls`,No(a,l);break}case"json":{const a=s.map(u=>{const f={};for(const h of r){let p=u[h.field];i.processCell&&(p=i.processCell(p,h.field,u)),f[h.field]=p}return f}),c=JSON.stringify(a,null,2);l=l.endsWith(".json")?l:`${l}.json`;const d=new Blob([c],{type:"application/json"});Re(d,l);break}}this.lastExportInfo={format:e,timestamp:new Date},this.emit("export-complete",{format:e,fileName:l,rowCount:s.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}}function Oo(o){const{totalRows:e,viewportHeight:t,scrollTop:n,rowHeight:i,overscan:r}=o,s=Math.ceil(t/i);let l=Math.floor(n/i)-r;l<0&&(l=0);let a=l+s+r*2;return a>e&&(a=e),a===e&&l>0&&(l=Math.max(0,a-s-r*2)),{start:l,end:a,offsetY:l*i,totalHeight:e*i}}function zo(o,e){return o<=e}function Fo(o,e,t=!1){const n=o[e.field];if(e.operator==="blank")return n==null||n==="";if(e.operator==="notBlank")return n!=null&&n!=="";if(n==null)return!1;const i=String(n),r=t?i:i.toLowerCase(),s=t?String(e.value):String(e.value).toLowerCase();switch(e.operator){case"contains":return r.includes(s);case"notContains":return!r.includes(s);case"equals":return r===s;case"notEquals":return r!==s;case"startsWith":return r.startsWith(s);case"endsWith":return r.endsWith(s);case"lessThan":return Number(n)<Number(e.value);case"lessThanOrEqual":return Number(n)<=Number(e.value);case"greaterThan":return Number(n)>Number(e.value);case"greaterThanOrEqual":return Number(n)>=Number(e.value);case"between":return Number(n)>=Number(e.value)&&Number(n)<=Number(e.valueTo);case"in":return Array.isArray(e.value)&&e.value.includes(n);case"notIn":return Array.isArray(e.value)&&!e.value.includes(n);default:return!0}}function qo(o,e,t=!1){return e.length?o.filter(n=>e.every(i=>Fo(n,i,t))):o}function Bo(o){return JSON.stringify(o.map(e=>({field:e.field,operator:e.operator,value:e.value,valueTo:e.valueTo})))}function at(o,e){const t=new Set;for(const n of o){const i=n[e];i!=null&&t.add(i)}return[...t].sort((n,i)=>typeof n=="number"&&typeof i=="number"?n-i:String(n).localeCompare(String(i)))}const Ko='.header-cell.filtered:before{content:"";position:absolute;top:4px;right:4px;width:6px;height:6px;background:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));border-radius:50%}.tbw-filter-btn{display:inline-flex;align-items:center;justify-content:center;background:transparent;border:none;cursor:pointer;padding:2px;margin-left:4px;opacity:.4;transition:opacity .15s;color:inherit;vertical-align:middle}.tbw-filter-btn:hover,.tbw-filter-btn.active{opacity:1}.tbw-filter-btn.active{color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6))}',Vo=".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, 4px));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:12px;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, 13px)}.tbw-filter-search{margin-bottom:8px}.tbw-filter-search-input{width:100%;padding:6px 10px;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, 4px);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:4px 2px;margin-bottom:8px;border-bottom:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)))}.tbw-filter-action-btn{background:transparent;border:none;color:var(--tbw-filter-accent, var(--tbw-color-accent, #3b82f6));cursor:pointer;font-size:12px;padding:2px 0}.tbw-filter-action-btn:hover{text-decoration:underline}.tbw-filter-values{flex:1;overflow-y:auto;margin-bottom:8px;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:8px;padding:4px 2px;cursor:pointer;border-radius:3px}.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:8px 0;text-align:center;font-style:italic}.tbw-filter-buttons{display:flex;gap:8px;padding-top:8px;border-top:1px solid var(--tbw-filter-divider, var(--tbw-color-border, light-dark(#d0d0d4, #454545)))}.tbw-filter-apply-btn{flex:1;padding:6px 12px;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:4px;cursor:pointer;font-size:13px}.tbw-filter-apply-btn:hover{filter:brightness(.9)}.tbw-filter-clear-btn{flex:1;padding:6px 12px;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:4px;cursor:pointer;font-size:13px}.tbw-filter-clear-btn:hover{background:var(--tbw-filter-hover, var(--tbw-color-row-hover, light-dark(#f0f6ff, #1c1c1c)))}";class q extends L{name="filtering";version="1.0.0";get defaultConfig(){return{debounceMs:300,caseSensitive:!1,trimInput:!0,useWorker:!0}}filters=new Map;cachedResult=null;cacheKey=null;openPanelField=null;panelElement=null;searchText=new Map;excludedValues=new Map;panelAbortController=null;globalStylesInjected=!1;static LIST_ITEM_HEIGHT=28;static LIST_OVERSCAN=3;static LIST_BYPASS_THRESHOLD=50;attach(e){super.attach(e),this.injectGlobalStyles()}detach(){this.filters.clear(),this.cachedResult=null,this.cacheKey=null,this.openPanelField=null,this.panelElement&&(this.panelElement.remove(),this.panelElement=null),this.searchText.clear(),this.excludedValues.clear(),this.panelAbortController?.abort(),this.panelAbortController=null}processRows(e){const t=[...this.filters.values()];if(!t.length)return[...e];if(this.config.filterHandler)return this.cachedResult?this.cachedResult:[...e];const n=Bo(t);if(this.cacheKey===n&&this.cachedResult)return this.cachedResult;const i=qo([...e],t,this.config.caseSensitive);return this.cachedResult=i,this.cacheKey=n,i}afterRender(){const e=this.shadowRoot;if(!e)return;e.querySelectorAll('[part~="header-cell"]').forEach(n=>{const i=n.getAttribute("data-col");if(i===null)return;const r=this.visibleColumns[parseInt(i,10)];if(!r||r.filterable===!1)return;const s=r.field;if(!s)return;const l=this.filters.has(s);let a=n.querySelector(".tbw-filter-btn");if(a){a.classList.toggle("active",l),n.classList.toggle("filtered",l);return}a=document.createElement("button"),a.className="tbw-filter-btn",a.setAttribute("aria-label",`Filter ${r.header??s}`),a.innerHTML='<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>',l&&(a.classList.add("active"),n.classList.add("filtered")),a.addEventListener("click",c=>{c.stopPropagation(),this.toggleFilterPanel(s,r,a)}),n.appendChild(a)})}setFilter(e,t){t===null?(this.filters.delete(e),this.excludedValues.delete(e)):(this.filters.set(e,{...t,field:e}),t.type==="set"&&t.operator==="notIn"&&Array.isArray(t.value)?this.excludedValues.set(e,new Set(t.value)):t.type==="set"&&this.excludedValues.delete(e)),this.cachedResult=null,this.cacheKey=null,this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0}),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),t.type==="set"&&t.operator==="notIn"&&Array.isArray(t.value)&&this.excludedValues.set(t.field,new Set(t.value));this.cachedResult=null,this.cacheKey=null,this.emit("filter-change",{filters:[...this.filters.values()],filteredRowCount:0}),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){return at(this.sourceRows,e)}injectGlobalStyles(){if(this.globalStylesInjected)return;if(document.getElementById("tbw-filter-panel-styles")){this.globalStylesInjected=!0;return}const e=document.createElement("style");e.id="tbw-filter-panel-styles",e.textContent=Vo,document.head.appendChild(e),this.globalStylesInjected=!0}toggleFilterPanel(e,t,n){if(this.openPanelField===e){this.closeFilterPanel();return}this.closeFilterPanel();const i=document.createElement("div");if(i.className="tbw-filter-panel",this.panelElement=i,this.openPanelField=e,this.config.valuesHandler){i.innerHTML='<div class="tbw-filter-loading">Loading...</div>',document.body.appendChild(i),this.positionPanel(i,n),this.setupPanelCloseHandler(i,n),this.config.valuesHandler(e,t).then(s=>{this.openPanelField!==e||!this.panelElement||(i.innerHTML="",this.renderPanelContent(e,t,i,s))});return}const r=at(this.sourceRows,e);this.renderPanelContent(e,t,i,r),document.body.appendChild(i),this.positionPanel(i,n),this.setupPanelCloseHandler(i,n)}renderPanelContent(e,t,n,i){let r=this.excludedValues.get(e);r||(r=new Set,this.excludedValues.set(e,r));const s=this.searchText.get(e)??"",l={field:e,column:t,uniqueValues:i,excludedValues:r,searchText:s,applySetFilter:c=>{this.applySetFilter(e,c),this.closeFilterPanel()},applyTextFilter:(c,d,u)=>{this.applyTextFilter(e,c,d,u),this.closeFilterPanel()},clearFilter:()=>{this.clearFieldFilter(e),this.closeFilterPanel()},closePanel:()=>this.closeFilterPanel()};let a=!1;this.config.filterPanelRenderer&&(this.config.filterPanelRenderer(n,l),a=n.children.length>0),a||this.renderDefaultFilterPanel(n,l,i,r)}setupPanelCloseHandler(e,t){this.panelAbortController=new AbortController,setTimeout(()=>{document.addEventListener("click",n=>{!e.contains(n.target)&&n.target!==t&&this.closeFilterPanel()},{signal:this.panelAbortController?.signal})},0)}closeFilterPanel(){this.panelElement&&(this.panelElement.remove(),this.panelElement=null),this.openPanelField=null,this.panelAbortController?.abort(),this.panelAbortController=null}positionPanel(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.top=`${n.bottom+4}px`,e.style.left=`${n.left}px`,requestAnimationFrame(()=>{const i=e.getBoundingClientRect();i.right>window.innerWidth-8&&(e.style.left=`${window.innerWidth-i.width-8}px`),i.bottom>window.innerHeight-8&&(e.style.top=`${n.top-i.height-4}px`)})}renderDefaultFilterPanel(e,t,n,i){const{field:r}=t,s=document.createElement("div");s.className="tbw-filter-search";const l=document.createElement("input");l.type="text",l.placeholder="Search...",l.className="tbw-filter-search-input",l.value=this.searchText.get(r)??"",s.appendChild(l),e.appendChild(s);const a=document.createElement("div");a.className="tbw-filter-actions";const c=document.createElement("label");c.className="tbw-filter-value-item",c.style.padding="0",c.style.margin="0";const d=document.createElement("input");d.type="checkbox",d.className="tbw-filter-checkbox";const u=document.createElement("span");u.textContent="Select All",c.appendChild(d),c.appendChild(u),a.appendChild(c);const f=()=>{const v=[...w.values()],x=v.every(k=>k),_=v.every(k=>!k);d.checked=x,d.indeterminate=!x&&!_};d.addEventListener("change",()=>{const v=d.checked;for(const x of w.keys())w.set(x,v);f(),T()}),e.appendChild(a);const h=document.createElement("div");h.className="tbw-filter-values";const p=document.createElement("div");p.className="tbw-filter-values-spacer",h.appendChild(p);const g=document.createElement("div");g.className="tbw-filter-values-content",h.appendChild(g);const w=new Map;n.forEach(v=>{const x=v==null?"__null__":String(v);w.set(x,!i.has(v))}),f();let y=[];const R=(v,x)=>{const _=v==null?"(Blank)":String(v),k=v==null?"__null__":String(v),P=document.createElement("label");P.className="tbw-filter-value-item",P.style.position="absolute",P.style.top=`${x*q.LIST_ITEM_HEIGHT}px`,P.style.left="0",P.style.right="0",P.style.height=`${q.LIST_ITEM_HEIGHT}px`,P.style.boxSizing="border-box";const z=document.createElement("input");z.type="checkbox",z.className="tbw-filter-checkbox",z.checked=w.get(k)??!0,z.dataset.value=k,z.addEventListener("change",()=>{w.set(k,z.checked),f()});const Pt=document.createElement("span");return Pt.textContent=_,P.appendChild(z),P.appendChild(Pt),P},T=()=>{const v=y.length,x=h.clientHeight,_=h.scrollTop;if(p.style.height=`${v*q.LIST_ITEM_HEIGHT}px`,zo(v,q.LIST_BYPASS_THRESHOLD/3)){g.innerHTML="",g.style.transform="translateY(0px)",y.forEach((P,z)=>{g.appendChild(R(P,z))});return}const k=Oo({totalRows:v,viewportHeight:x,scrollTop:_,rowHeight:q.LIST_ITEM_HEIGHT,overscan:q.LIST_OVERSCAN});g.style.transform=`translateY(${k.offsetY}px)`,g.innerHTML="";for(let P=k.start;P<k.end;P++)g.appendChild(R(y[P],P-k.start))},S=v=>{const x=v.toLowerCase();if(y=n.filter(_=>{const k=_==null?"(Blank)":String(_);return!v||k.toLowerCase().includes(x)}),y.length===0){p.style.height="0px",g.innerHTML="";const _=document.createElement("div");_.className="tbw-filter-no-match",_.textContent="No matching values",g.appendChild(_);return}T()};h.addEventListener("scroll",()=>{y.length>0&&T()},{passive:!0}),S(l.value),e.appendChild(h);let b;l.addEventListener("input",()=>{clearTimeout(b),b=setTimeout(()=>{this.searchText.set(r,l.value),S(l.value)},this.config.debounceMs??150)});const m=document.createElement("div");m.className="tbw-filter-buttons";const A=document.createElement("button");A.className="tbw-filter-apply-btn",A.textContent="Apply",A.addEventListener("click",()=>{const v=[];for(const[x,_]of w)if(!_)if(x==="__null__")v.push(null);else{const k=n.find(P=>String(P)===x);v.push(k!==void 0?k:x)}t.applySetFilter(v)}),m.appendChild(A);const E=document.createElement("button");E.className="tbw-filter-clear-btn",E.textContent="Clear Filter",E.addEventListener("click",()=>{t.clearFilter()}),m.appendChild(E),e.appendChild(m)}applySetFilter(e,t){this.excludedValues.set(e,new Set(t)),t.length===0?this.filters.delete(e):this.filters.set(e,{field:e,type:"set",operator:"notIn",value:t}),this.applyFiltersInternal()}applyTextFilter(e,t,n,i){this.filters.set(e,{field:e,type:"text",operator:t,value:n,valueTo:i}),this.applyFiltersInternal()}applyFiltersInternal(){this.cachedResult=null,this.cacheKey=null;const e=[...this.filters.values()];if(this.config.filterHandler){const t=this.grid;t.setAttribute("aria-busy","true");const n=this.config.filterHandler(e,this.sourceRows),i=r=>{t.removeAttribute("aria-busy"),this.cachedResult=r,this.grid.rows=r,this.emit("filter-change",{filters:e,filteredRowCount:r.length}),this.requestRender()};n&&typeof n.then=="function"?n.then(i):i(n);return}this.emit("filter-change",{filters:e,filteredRowCount:0}),this.requestRender()}getColumnState(e){const t=this.filters.get(e);if(t)return{filter:{type:t.type,operator:t.operator,value:t.value,valueTo:t.valueTo}}}applyColumnState(e,t){if(!t.filter){this.filters.delete(e);return}const n={field:e,type:t.filter.type,operator:t.filter.operator,value:t.filter.value,valueTo:t.filter.valueTo};this.filters.set(e,n),this.cachedResult=null,this.cacheKey=null}styles=Ko}function $o(o){if(!o.length)return[];const e=new Map,t=[],n=(s,l)=>{if(!l.length)return;const a=t[t.length-1];if(a&&a.implicit&&a.firstIndex+a.columns.length===s){a.columns.push(...l);return}t.push({id:"__implicit__"+s,label:void 0,columns:l,firstIndex:s,implicit:!0})};let i=[],r=0;return o.forEach((s,l)=>{const a=s.group;if(!a){i.length===0&&(r=l),i.push(s);return}i.length&&(n(r,i.slice()),i=[]);const c=typeof a=="string"?a:a.id;let d=e.get(c);d||(d={id:c,label:typeof a=="string"?void 0:a.label,columns:[],firstIndex:l},e.set(c,d),t.push(d)),d.columns.push(s)}),i.length&&n(r,i),t.length===1&&t[0].implicit&&t[0].columns.length===o.length?[]:t}function Go(o,e,t){if(!e.length||!o)return;const n=new Map;for(const r of e)for(const s of r.columns)s?.field&&n.set(s.field,r.id);const i=Array.from(o.querySelectorAll(".cell[data-field]"));i.forEach(r=>{const s=r.getAttribute("data-field")||"",l=n.get(s);l&&(r.classList.add("grouped"),r.getAttribute("data-group")||r.setAttribute("data-group",l))});for(const r of e){const s=r.columns[r.columns.length-1],l=i.find(a=>a.getAttribute("data-field")===s.field);l&&l.classList.add("group-end")}}function Wo(o,e){if(o.length===0)return null;const t=document.createElement("div");t.className="header-group-row",t.setAttribute("role","row");for(const n of o){const i=n.firstIndex!=null?n.firstIndex:e.findIndex(a=>n.columns.includes(a)),r=String(n.id).startsWith("__implicit__"),s=r?"":n.label||n.id,l=document.createElement("div");l.className="cell header-group-cell",r&&l.classList.add("implicit-group"),l.setAttribute("data-group",String(n.id)),l.style.gridColumn=`${i+1} / span ${n.columns.length}`,l.textContent=s,t.appendChild(l)}return t}function Uo(o){return o.some(e=>e.group!=null)}const jo=".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:4px 8px;font-weight:600;font-size:.9em;text-transform:uppercase;letter-spacing:.5px;border-right:1px solid var(--tbw-grouping-columns-border, 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))}.header-row .cell.group-end:last-child{border-right:none}.header-group-row.no-borders{border-bottom:none}.header-group-row.no-borders .header-group-cell{border-right:none}.header-row.no-group-borders .cell.group-end{border-right:1px solid var(--tbw-color-border)}";class Xo extends L{name="groupingColumns";version="1.0.0";get defaultConfig(){return{showGroupBorders:!0}}groups=[];isActive=!1;detach(){this.groups=[],this.isActive=!1}static detect(e,t){const n=t?.columns;return Array.isArray(n)?Uo(n):!1}processColumns(e){const t=$o(e);return t.length===0?(this.isActive=!1,this.groups=[],[...e]):(this.isActive=!0,this.groups=t,[...e])}afterRender(){if(!this.isActive||this.groups.length===0){const s=this.shadowRoot?.querySelector(".header")?.querySelector(".header-group-row");s&&s.remove();return}const e=this.shadowRoot?.querySelector(".header");if(!e)return;const t=e.querySelector(".header-group-row");t&&t.remove();const n=Wo(this.groups,this.columns);if(n){n.classList.toggle("no-borders",!this.config.showGroupBorders);const r=e.querySelector(".header-row");r?e.insertBefore(n,r):e.appendChild(n)}const i=e.querySelector(".header-row");i&&(i.classList.toggle("no-group-borders",!this.config.showGroupBorders),Go(i,this.groups,this.columns))}isGroupingActive(){return this.isActive}getGroups(){return this.groups}getGroupColumns(e){const t=this.groups.find(n=>n.id===e);return t?t.columns:[]}refresh(){this.requestRender()}styles=jo}function Yo({rows:o,config:e,expanded:t}){const n=e.groupOn;if(typeof n!="function")return[];const i={key:"__root__",value:null,depth:-1,rows:[],children:new Map};if(o.forEach(l=>{let a=n(l);a==null||a===!1?a=["__ungrouped__"]:Array.isArray(a)||(a=[a]);let c=i;a.forEach((d,u)=>{const f=d==null?"∅":String(d),h=c.key==="__root__"?f:c.key+"||"+f;let p=c.children.get(f);p||(p={key:h,value:d,depth:u,rows:[],children:new Map,parent:c},c.children.set(f,p)),c=p}),c.rows.push(l)}),i.children.size===1&&i.children.has("__ungrouped__")&&i.children.get("__ungrouped__").rows.length===o.length)return[];const r=[],s=l=>{if(l===i){l.children.forEach(c=>s(c));return}const a=t.has(l.key);r.push({kind:"group",key:l.key,value:l.value,depth:l.depth,rows:l.rows,expanded:a}),a&&(l.children.size?l.children.forEach(c=>s(c)):l.rows.forEach(c=>r.push({kind:"data",row:c,rowIndex:o.indexOf(c)})))};return s(i),r}function Zo(o,e){const t=new Set(o);return t.has(e)?t.delete(e):t.add(e),t}function Jo(o){const e=new Set;for(const t of o)t.kind==="group"&&e.add(t.key);return e}function Qo(){return new Set}function en(o){return o.kind!=="group"?0:o.rows.length}const tn='.group-row{background:var(--tbw-grouping-rows-bg, var(--tbw-color-panel-bg));font-weight:500}.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:20px;height:20px;margin-right:4px}.group-toggle:hover{background:var(--tbw-grouping-rows-toggle-hover, var(--tbw-color-row-hover));border-radius:2px}.group-label{display:inline-flex;align-items:center;gap:8px}.group-count{color:var(--tbw-grouping-rows-count-color, var(--tbw-color-fg-muted));font-size:.85em;font-weight:400}[data-group-depth="0"] .group-label{padding-left:0}[data-group-depth="1"] .group-label{padding-left:20px}[data-group-depth="2"] .group-label{padding-left:40px}[data-group-depth="3"] .group-label{padding-left:60px}[data-group-depth="4"] .group-label{padding-left:80px}.data-grid-row.tbw-group-slide-in{animation:tbw-group-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.data-grid-row.tbw-group-fade-in{animation:tbw-group-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-fade-in{0%{opacity:0}to{opacity:1}}';class on extends L{name="groupingRows";version="1.0.0";get defaultConfig(){return{defaultExpanded:!1,showRowCount:!0,indentWidth:20,aggregators:{},animation:"slide"}}expandedKeys=new Set;flattenedRows=[];isActive=!1;previousVisibleKeys=new Set;keysToAnimate=new Set;get animationStyle(){const t=this.grid.effectiveConfig?.animation?.mode??"reduced-motion";if(t===!1||t==="off")return!1;if(t!==!0&&t!=="on"){const n=this.shadowRoot?.host;if(n&&getComputedStyle(n).getPropertyValue("--tbw-animation-enabled").trim()==="0")return!1}return this.config.animation??"slide"}detach(){this.expandedKeys.clear(),this.flattenedRows=[],this.isActive=!1,this.previousVisibleKeys.clear(),this.keysToAnimate.clear()}static detect(e,t){return typeof t?.groupOn=="function"||typeof t?.enableRowGrouping=="boolean"}processRows(e){const t=this.config;if(typeof t.groupOn!="function")return this.isActive=!1,this.flattenedRows=[],[...e];const n=Yo({rows:e,config:t,expanded:this.expandedKeys});if(n.length===0)return this.isActive=!1,this.flattenedRows=[],[...e];this.isActive=!0,this.flattenedRows=n,this.keysToAnimate.clear();const i=new Set;return n.forEach((r,s)=>{if(r.kind==="data"){const l=`data-${s}`;i.add(l),this.previousVisibleKeys.has(l)||this.keysToAnimate.add(l)}}),this.previousVisibleKeys=i,n.map(r=>r.kind==="group"?{__isGroupRow:!0,__groupKey:r.key,__groupValue:r.value,__groupDepth:r.depth,__groupRows:r.rows,__groupExpanded:r.expanded,__groupRowCount:en(r)}:r.row)}onCellClick(e){const t=e.row;if(t?.__isGroupRow&&e.originalEvent.target?.closest(".group-toggle"))return this.toggle(t.__groupKey),!0}renderRow(e,t,n){if(!e?.__isGroupRow)return!1;const i=this.config;if(i.groupRowRenderer){const l=()=>{this.toggle(e.__groupKey)},a=i.groupRowRenderer({key:e.__groupKey,value:e.__groupValue,depth:e.__groupDepth,rows:e.__groupRows,expanded:e.__groupExpanded,toggleExpand:l});if(a)return t.className="group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),typeof a=="string"?t.innerHTML=a:(t.innerHTML="",t.appendChild(a)),!0}const r=()=>{this.toggle(e.__groupKey)};return t.className="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.paddingLeft=`${(e.__groupDepth||0)*(i.indentWidth??20)}px`,t.innerHTML="",i.fullWidth!==!1?this.renderFullWidthGroupRow(e,t,r):this.renderPerColumnGroupRow(e,t,r),!0}afterRender(){const e=this.animationStyle;if(e===!1||this.keysToAnimate.size===0)return;const t=this.shadowRoot?.querySelector(".rows");if(!t)return;const n=e==="fade"?"tbw-group-fade-in":"tbw-group-slide-in";for(const i of t.querySelectorAll(".data-grid-row:not(.group-row)")){const r=i.querySelector(".cell[data-row]"),s=r?parseInt(r.getAttribute("data-row")??"-1",10):-1,a=this.flattenedRows[s]?.kind==="data"?`data-${s}`:void 0;a&&this.keysToAnimate.has(a)&&(i.classList.add(n),i.addEventListener("animationend",()=>i.classList.remove(n),{once:!0}))}this.keysToAnimate.clear()}renderFullWidthGroupRow(e,t,n){const i=this.config,r=document.createElement("div");r.className="cell group-full",r.style.gridColumn="1 / -1",r.setAttribute("role","gridcell");const s=document.createElement("button");s.type="button",s.className=`group-toggle${e.__groupExpanded?" expanded":""}`,s.setAttribute("aria-label",e.__groupExpanded?"Collapse group":"Expand group"),this.setIcon(s,this.resolveIcon(e.__groupExpanded?"collapse":"expand")),s.addEventListener("click",c=>{c.stopPropagation(),n()}),r.appendChild(s);const l=document.createElement("span");l.className="group-label";const a=i.formatLabel?i.formatLabel(e.__groupValue,e.__groupDepth||0,e.__groupKey):String(e.__groupValue);if(l.textContent=a,r.appendChild(l),i.showRowCount!==!1){const c=document.createElement("span");c.className="group-count",c.textContent=`(${e.__groupRowCount??e.__groupRows?.length??0})`,r.appendChild(c)}t.appendChild(r)}renderPerColumnGroupRow(e,t,n){const i=this.config,r=i.aggregators??{},s=this.columns,l=e.__groupRows??[],c=this.shadowRoot?.querySelector(".body")?.style.gridTemplateColumns||"";c&&(t.style.display="grid",t.style.gridTemplateColumns=c),s.forEach((d,u)=>{const f=document.createElement("div");if(f.className="cell group-cell",f.setAttribute("data-col",String(u)),f.setAttribute("role","gridcell"),u===0){const h=document.createElement("button");h.type="button",h.className=`group-toggle${e.__groupExpanded?" expanded":""}`,h.setAttribute("aria-label",e.__groupExpanded?"Collapse group":"Expand group"),this.setIcon(h,this.resolveIcon(e.__groupExpanded?"collapse":"expand")),h.addEventListener("click",w=>{w.stopPropagation(),n()}),f.appendChild(h);const p=document.createElement("span"),g=r[d.field];if(g){const w=we(g,l,d.field,d);p.textContent=w!=null?String(w):String(e.__groupValue)}else{const w=i.formatLabel?i.formatLabel(e.__groupValue,e.__groupDepth||0,e.__groupKey):String(e.__groupValue);p.textContent=w}if(f.appendChild(p),i.showRowCount!==!1){const w=document.createElement("span");w.className="group-count",w.textContent=` (${l.length})`,f.appendChild(w)}}else{const h=r[d.field];if(h){const p=we(h,l,d.field,d);f.textContent=p!=null?String(p):""}else f.textContent=""}t.appendChild(f)})}expandAll(){this.expandedKeys=Jo(this.flattenedRows),this.requestRender()}collapseAll(){this.expandedKeys=Qo(),this.requestRender()}toggle(e){this.expandedKeys=Zo(this.expandedKeys,e);const t=this.flattenedRows.find(n=>n.kind==="group"&&n.key===e);this.emit("group-toggle",{key:e,expanded:this.expandedKeys.has(e),value:t?.value,depth:t?.depth??0}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}expand(e){this.expandedKeys.has(e)||(this.expandedKeys=new Set([...this.expandedKeys,e]),this.requestRender())}collapse(e){if(this.expandedKeys.has(e)){const t=new Set(this.expandedKeys);t.delete(e),this.expandedKeys=t,this.requestRender()}}getGroupState(){const e=this.flattenedRows.filter(t=>t.kind==="group");return{isActive:this.isActive,expandedCount:this.expandedKeys.size,totalGroups:e.length,expandedKeys:[...this.expandedKeys]}}getRowCount(){return this.flattenedRows.length}refreshGroups(){this.requestRender()}getExpandedGroups(){return[...this.expandedKeys]}getFlattenedRows(){return this.flattenedRows}isGroupingActive(){return this.isActive}setGroupOn(e){this.config.groupOn=e,this.requestRender()}styles=tn}function _e(o,e){const t=new Set(o);return t.has(e)?t.delete(e):t.add(e),t}function nn(o,e){const t=new Set(o);return t.add(e),t}function rn(o,e){const t=new Set(o);return t.delete(e),t}function sn(o,e){return o.has(e)}function ln(o,e,t,n){const i=document.createElement("div");i.className="master-detail-row",i.setAttribute("data-detail-for",String(e)),i.setAttribute("role","row");const r=document.createElement("div");r.className="master-detail-cell",r.setAttribute("role","cell"),r.style.gridColumn=`1 / ${n+1}`;const s=t(o,e);return typeof s=="string"?r.innerHTML=s:s instanceof HTMLElement&&r.appendChild(s),i.appendChild(r),i}const an=".master-detail-cell-wrapper{display:flex;align-items:center;gap:4px}.master-detail-toggle{cursor:pointer;opacity:.7;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center}.master-detail-toggle:hover{opacity:1}.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}.master-detail-cell{padding:16px;overflow:auto}.master-detail-row.tbw-expanding{animation:tbw-detail-expand var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}.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:500px;padding-top:16px;padding-bottom:16px}}@keyframes tbw-detail-collapse{0%{opacity:1;max-height:500px}to{opacity:0;max-height:0}}";class cn extends L{name="masterDetail";version="1.0.0";get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,showExpandColumn:!0,animation:"slide"}}get isAnimationEnabled(){const t=this.grid.effectiveConfig?.animation?.mode??"reduced-motion";if(t===!1||t==="off")return!1;if(t===!0||t==="on")return!0;const n=this.shadowRoot?.host;return n?getComputedStyle(n).getPropertyValue("--tbw-animation-enabled").trim()!=="0":!0}get animationStyle(){return this.isAnimationEnabled?this.config.animation??"slide":!1}get animationDuration(){const e=this.shadowRoot?.host;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),n=parseInt(t,10);if(!isNaN(n))return n}return 200}animateExpand(e){!this.isAnimationEnabled||this.animationStyle===!1||(e.classList.add("tbw-expanding"),e.addEventListener("animationend",()=>{e.classList.remove("tbw-expanding")},{once:!0}))}animateCollapse(e,t){if(!this.isAnimationEnabled||this.animationStyle===!1){t();return}e.classList.add("tbw-collapsing");const n=()=>{e.classList.remove("tbw-collapsing"),t()};e.addEventListener("animationend",n,{once:!0}),setTimeout(n,this.animationDuration+50)}expandedRows=new Set;detailElements=new Map;detach(){this.expandedRows.clear(),this.detailElements.clear()}processColumns(e){if(!this.config.detailRenderer)return[...e];const t=[...e];if(t.length>0){const n={...t[0]},i=n.viewRenderer;if(i?.__masterDetailWrapped)return t;const r=s=>{const{value:l,row:a}=s,c=this.expandedRows.has(a),d=document.createElement("span");d.className="master-detail-cell-wrapper";const u=document.createElement("span");u.className=`master-detail-toggle${c?" expanded":""}`,this.setIcon(u,this.resolveIcon(c?"collapse":"expand")),u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-expanded",String(c)),u.setAttribute("aria-label",c?"Collapse details":"Expand details"),u.addEventListener("click",h=>{h.stopPropagation();const p=this.rows.indexOf(a);this.expandedRows=_e(this.expandedRows,a),this.emit("detail-expand",{rowIndex:p,row:a,expanded:this.expandedRows.has(a)}),this.requestRender()}),d.appendChild(u);const f=document.createElement("span");if(i){const h=i(s);h instanceof Node?f.appendChild(h):f.textContent=String(h??l??"")}else f.textContent=String(l??"");return d.appendChild(f),d};r.__masterDetailWrapped=!0,n.viewRenderer=r,t[0]=n}return t}onRowClick(e){if(!(!this.config.expandOnRowClick||!this.config.detailRenderer))return this.expandedRows=_e(this.expandedRows,e.row),this.emit("detail-expand",{rowIndex:e.rowIndex,row:e.row,expanded:this.expandedRows.has(e.row)}),this.requestRender(),!1}onCellClick(){this.expandedRows.size>0&&queueMicrotask(()=>this.#o())}afterRender(){this.#o()}onScrollRender(){!this.config.detailRenderer||this.expandedRows.size===0||this.#o()}#o(){if(!this.config.detailRenderer)return;const e=this.shadowRoot?.querySelector(".rows");if(!e)return;const t=new Map,n=e.querySelectorAll(".data-grid-row"),i=this.columns.length;for(const s of n){const l=s.querySelector(".cell[data-row]"),a=l?parseInt(l.getAttribute("data-row")??"-1",10):-1;a>=0&&t.set(a,s)}const r=e.querySelectorAll(".master-detail-row");for(const s of r){const l=parseInt(s.getAttribute("data-detail-for")??"-1",10),a=l>=0?this.rows[l]:void 0,c=a&&this.expandedRows.has(a),d=t.has(l);(!c||!d)&&(s.remove(),a&&this.detailElements.delete(a))}for(const[s,l]of t){const a=this.rows[s];if(!a||!this.expandedRows.has(a))continue;const c=this.detailElements.get(a);if(c){c.previousElementSibling!==l&&l.after(c);continue}const d=ln(a,s,this.config.detailRenderer,i);typeof this.config.detailHeight=="number"&&(d.style.height=`${this.config.detailHeight}px`),l.after(d),this.detailElements.set(a,d),this.animateExpand(d)}}getExtraHeight(){let e=0;for(const t of this.expandedRows){const n=this.detailElements.get(t);if(n)e+=n.offsetHeight;else{const i=this.config?.detailHeight;e+=typeof i=="number"?i:150}}return e}getExtraHeightBefore(e){let t=0;for(const n of this.expandedRows){const i=this.rows.indexOf(n);if(i>=0&&i<e){const r=this.detailElements.get(n);if(r)t+=r.offsetHeight;else{const s=this.config?.detailHeight;t+=typeof s=="number"?s:150}}}return t}adjustVirtualStart(e,t,n){if(this.expandedRows.size===0)return e;const i=[];for(const l of this.expandedRows){const a=this.rows.indexOf(l);a>=0&&i.push({index:a,row:l})}i.sort((l,a)=>l.index-a.index);let r=e,s=0;for(const{index:l,row:a}of i){const c=l*n+s,u=this.detailElements.get(a)?.offsetHeight??(typeof this.config?.detailHeight=="number"?this.config.detailHeight:150),f=c+n+u;s+=u,!(l>=e)&&f>t&&l<r&&(r=l)}return r}expand(e){const t=this.rows[e];t&&(this.expandedRows=nn(this.expandedRows,t),this.requestRender())}collapse(e){const t=this.rows[e];t&&(this.expandedRows=rn(this.expandedRows,t),this.requestRender())}toggle(e){const t=this.rows[e];t&&(this.expandedRows=_e(this.expandedRows,t),this.requestRender())}isExpanded(e){const t=this.rows[e];return t?sn(this.expandedRows,t):!1}expandAll(){for(const e of this.rows)this.expandedRows.add(e);this.requestRender()}collapseAll(){this.expandedRows.clear(),this.requestRender()}getExpandedRows(){const e=[];for(const t of this.expandedRows){const n=this.rows.indexOf(t);n>=0&&e.push(n)}return e}getDetailElement(e){const t=this.rows[e];return t?this.detailElements.get(t):void 0}styles=an}function dn(o,e,t){return e.length?[...o].sort((n,i)=>{for(const r of e){const l=t.find(u=>u.field===r.field)?.sortComparator??un,a=n[r.field],c=i[r.field],d=l(a,c,n,i);if(d!==0)return r.direction==="asc"?d:-d}return 0}):[...o]}function un(o,e){return o==null&&e==null?0:o==null?1:e==null?-1:typeof o=="number"&&typeof e=="number"?o-e:o instanceof Date&&e instanceof Date?o.getTime()-e.getTime():typeof o=="boolean"&&typeof e=="boolean"?o===e?0:o?-1:1:String(o).localeCompare(String(e))}function hn(o,e,t,n){const i=o.find(r=>r.field===e);return t?i?i.direction==="asc"?o.map(r=>r.field===e?{...r,direction:"desc"}:r):o.filter(r=>r.field!==e):o.length<n?[...o,{field:e,direction:"asc"}]:o:i?.direction==="asc"?[{field:e,direction:"desc"}]:i?.direction==="desc"?[]:[{field:e,direction:"asc"}]}function ct(o,e){const t=o.findIndex(n=>n.field===e);return t>=0?t+1:void 0}function dt(o,e){return o.find(t=>t.field===e)?.direction}const fn='.header-cell[data-sort=asc]:after{content:"↑";margin-left:4px;opacity:.8}.header-cell[data-sort=desc]:after{content:"↓";margin-left:4px;opacity:.8}.sort-indicator{margin-left:4px;opacity:.8}.sort-index{font-size:10px;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:14px;height:14px;display:inline-flex;align-items:center;justify-content:center;margin-left:2px;font-weight:600}';class pn extends L{name="multiSort";version="1.0.0";get defaultConfig(){return{maxSortColumns:3,showSortIndex:!0}}sortModel=[];detach(){this.sortModel=[]}processRows(e){return this.sortModel.length===0?[...e]:dn([...e],this.sortModel,[...this.columns])}onHeaderClick(e){if(!this.columns.find(r=>r.field===e.field)?.sortable)return!1;const n=e.originalEvent.shiftKey,i=this.config.maxSortColumns??3;return this.sortModel=hn(this.sortModel,e.field,n,i),this.emit("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),!0}afterRender(){const e=this.shadowRoot;if(!e)return;const t=this.config.showSortIndex!==!1;e.querySelectorAll(".header-row .cell[data-field]").forEach(i=>{const r=i.getAttribute("data-field");if(!r)return;const s=ct(this.sortModel,r),l=dt(this.sortModel,r);if(i.querySelector(".sort-index")?.remove(),l){i.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove(),i.setAttribute("data-sort",l);const d=document.createElement("span");if(d.className="sort-indicator",this.setIcon(d,this.resolveIcon(l==="asc"?"sortAsc":"sortDesc")),i.appendChild(d),t&&this.sortModel.length>1&&s!==void 0){const u=document.createElement("span");u.className="sort-index",u.textContent=String(s),i.appendChild(u)}}else i.removeAttribute("data-sort")})}getSortModel(){return[...this.sortModel]}setSortModel(e){this.sortModel=[...e],this.emit("sort-change",{sortModel:[...e]}),this.requestRender()}clearSort(){this.sortModel=[],this.emit("sort-change",{sortModel:[]}),this.requestRender()}getSortIndex(e){return ct(this.sortModel,e)}getSortDirection(e){return dt(this.sortModel,e)}getColumnState(e){const t=this.sortModel.findIndex(i=>i.field===e);return t===-1?void 0:{sort:{direction:this.sortModel[t].direction,priority:t}}}applyColumnState(e,t){if(!t.sort){this.sortModel=this.sortModel.filter(r=>r.field!==e);return}const n=this.sortModel.findIndex(r=>r.field===e),i={field:e,direction:t.sort.direction};n!==-1?this.sortModel[n]=i:this.sortModel.splice(t.sort.priority,0,i)}styles=fn}function gn(o){return o.filter(e=>e.sticky==="left")}function wn(o){return o.filter(e=>e.sticky==="right")}function Se(o){return o.some(e=>e.sticky==="left"||e.sticky==="right")}function ut(o,e){const t=o.shadowRoot;if(!t)return;const n=Array.from(t.querySelectorAll(".header-row .cell"));if(!n.length)return;const i=new Map;e.forEach((l,a)=>{l.field&&i.set(l.field,a)});let r=0;for(const l of e)if(l.sticky==="left"){const a=i.get(l.field),c=n.find(d=>d.getAttribute("data-field")===l.field);c&&(c.classList.add("sticky-left"),c.style.position="sticky",c.style.left=r+"px",a!==void 0&&t.querySelectorAll(`.data-grid-row .cell[data-col="${a}"]`).forEach(d=>{d.classList.add("sticky-left"),d.style.position="sticky",d.style.left=r+"px"}),r+=c.offsetWidth)}let s=0;for(const l of[...e].reverse())if(l.sticky==="right"){const a=i.get(l.field),c=n.find(d=>d.getAttribute("data-field")===l.field);c&&(c.classList.add("sticky-right"),c.style.position="sticky",c.style.right=s+"px",a!==void 0&&t.querySelectorAll(`.data-grid-row .cell[data-col="${a}"]`).forEach(d=>{d.classList.add("sticky-right"),d.style.position="sticky",d.style.right=s+"px"}),s+=c.offsetWidth)}}function ht(o){const e=o.shadowRoot;if(!e)return;e.querySelectorAll(".sticky-left, .sticky-right").forEach(n=>{n.classList.remove("sticky-left","sticky-right"),n.style.position="",n.style.left="",n.style.right=""})}class bn extends L{name="pinnedColumns";version="1.0.0";get defaultConfig(){return{}}isApplied=!1;leftOffsets=new Map;rightOffsets=new Map;detach(){this.leftOffsets.clear(),this.rightOffsets.clear(),this.isApplied=!1}static detect(e,t){const n=t?.columns;return Array.isArray(n)?Se(n):!1}processColumns(e){return this.isApplied=Se([...e]),[...e]}afterRender(){if(!this.isApplied)return;const e=this.grid,t=[...this.columns];if(!Se(t)){ht(e),this.isApplied=!1;return}queueMicrotask(()=>{ut(e,t)})}onPluginQuery(e){switch(e.type){case ee.CAN_MOVE_COLUMN:{const t=e.context,n=t.sticky;if(n==="left"||n==="right")return!1;const i=t.meta?.sticky;return i==="left"||i==="right"?!1:void 0}default:return}}refreshStickyOffsets(){const e=[...this.columns];ut(this.grid,e)}getLeftPinnedColumns(){const e=[...this.columns];return gn(e)}getRightPinnedColumns(){const e=[...this.columns];return wn(e)}clearStickyPositions(){ht(this.grid)}getHorizontalScrollOffsets(e,t){if(!this.isApplied)return;let n=0,i=0;if(e){const s=e.querySelectorAll(".sticky-left"),l=e.querySelectorAll(".sticky-right");s.forEach(a=>{n+=a.offsetWidth}),l.forEach(a=>{i+=a.offsetWidth})}else{const l=this.grid.shadowRoot;l&&l.querySelectorAll(".header-row .cell").forEach(c=>{c.classList.contains("sticky-left")?n+=c.offsetWidth:c.classList.contains("sticky-right")&&(i+=c.offsetWidth)})}const r=t?.classList.contains("sticky-left")||t?.classList.contains("sticky-right");return{left:n,right:i,skipScroll:r}}}function mn(o){return typeof o=="object"&&o!==null&&"aggFunc"in o}function Ae(o,e){const t=document.createElement("div");t.className="tbw-pinned-rows",t.setAttribute("role","presentation"),t.setAttribute("aria-live","polite");const n=document.createElement("div");n.className="tbw-pinned-rows-left";const i=document.createElement("div");i.className="tbw-pinned-rows-center";const r=document.createElement("div");if(r.className="tbw-pinned-rows-right",o.showRowCount!==!1){const s=document.createElement("span");s.className="tbw-status-panel tbw-status-panel-row-count",s.textContent=`Total: ${e.totalRows} rows`,n.appendChild(s)}if(o.showFilteredCount&&e.filteredRows!==e.totalRows){const s=document.createElement("span");s.className="tbw-status-panel tbw-status-panel-filtered-count",s.textContent=`Filtered: ${e.filteredRows}`,n.appendChild(s)}if(o.showSelectedCount&&e.selectedRows>0){const s=document.createElement("span");s.className="tbw-status-panel tbw-status-panel-selected-count",s.textContent=`Selected: ${e.selectedRows}`,r.appendChild(s)}if(o.customPanels)for(const s of o.customPanels){const l=vn(s,e);switch(s.position){case"left":n.appendChild(l);break;case"center":i.appendChild(l);break;case"right":r.appendChild(l);break}}return t.appendChild(n),t.appendChild(i),t.appendChild(r),t}function ft(o){const e=document.createElement("div");return e.className=`tbw-aggregation-rows tbw-aggregation-rows-${o}`,e.setAttribute("role","presentation"),e}function pt(o,e,t,n){o.innerHTML="";for(const i of e){const r=document.createElement("div");if(r.className="tbw-aggregation-row",r.setAttribute("role","presentation"),i.id&&r.setAttribute("data-aggregation-id",i.id),i.fullWidth){const s=document.createElement("div");s.className="tbw-aggregation-cell tbw-aggregation-cell-full",s.style.gridColumn="1 / -1",s.textContent=i.label||"",r.appendChild(s)}else for(const s of t){const l=document.createElement("div");l.className="tbw-aggregation-cell",l.setAttribute("data-field",s.field);let a,c;const d=i.aggregators?.[s.field];if(d)if(mn(d)){const u=ge(d.aggFunc);u&&(a=u(n,s.field,s)),c=d.formatter}else{const u=ge(d);u&&(a=u(n,s.field,s))}else if(i.cells&&Object.prototype.hasOwnProperty.call(i.cells,s.field)){const u=i.cells[s.field];typeof u=="function"?a=u(n,s.field,s):a=u}a!=null?l.textContent=c?c(a,s.field,s):String(a):l.textContent="",r.appendChild(l)}o.appendChild(r)}}function vn(o,e){const t=document.createElement("div");t.className="tbw-status-panel tbw-status-panel-custom",t.id=`status-panel-${o.id}`;const n=o.render(e);return typeof n=="string"?t.innerHTML=n:t.appendChild(n),t}function gt(o,e,t,n,i){return{totalRows:o.length,filteredRows:i?.cachedResult?.length??o.length,selectedRows:n?.selected?.size??0,columns:e,rows:o,grid:t}}const yn=".tbw-footer{position:sticky;bottom: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:8px 12px;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:12px;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:16px}.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, 2px 8px);min-height:var(--tbw-row-height, 28px);display:flex;align-items:center;border-right:1px solid var(--tbw-color-border-cell)}.tbw-aggregation-cell:last-child{border-right:0}.tbw-aggregation-cell-full{grid-column:1 / -1;border-right:0}";class Cn extends L{name="pinnedRows";version="1.0.0";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.shadowRoot;if(!e)return;const t=e.querySelector(".tbw-scroll-area")??e.querySelector(".tbw-grid-content")??e.children[0];if(!t)return;const n=this.getSelectionState(),i=this.getFilterState(),r=gt(this.rows,this.columns,this.grid,n,i),s=this.config.aggregationRows||[],l=s.filter(f=>f.position==="top"),a=s.filter(f=>f.position!=="top");if(l.length>0){if(!this.topAggregationContainer){this.topAggregationContainer=ft("top");const f=e.querySelector(".header");f&&f.nextSibling?t.insertBefore(this.topAggregationContainer,f.nextSibling):t.appendChild(this.topAggregationContainer)}pt(this.topAggregationContainer,l,this.visibleColumns,this.rows)}else this.topAggregationContainer&&(this.topAggregationContainer.remove(),this.topAggregationContainer=null);const c=this.config.showRowCount!==!1||this.config.showSelectedCount&&r.selectedRows>0||this.config.showFilteredCount&&r.filteredRows!==r.totalRows||this.config.customPanels&&this.config.customPanels.length>0,d=c&&this.config.position!=="top",u=a.length>0||d;if(c&&this.config.position==="top")if(!this.infoBarElement)this.infoBarElement=Ae(this.config,r),t.insertBefore(this.infoBarElement,t.firstChild);else{const f=Ae(this.config,r);this.infoBarElement.replaceWith(f),this.infoBarElement=f}else this.config.position==="top"&&this.infoBarElement&&(this.infoBarElement.remove(),this.infoBarElement=null);u?(this.footerWrapper||(this.footerWrapper=document.createElement("div"),this.footerWrapper.className="tbw-footer",t.appendChild(this.footerWrapper)),this.footerWrapper.innerHTML="",a.length>0&&(this.bottomAggregationContainer||(this.bottomAggregationContainer=ft("bottom")),this.footerWrapper.appendChild(this.bottomAggregationContainer),pt(this.bottomAggregationContainer,a,this.visibleColumns,this.rows)),d&&(this.infoBarElement=Ae(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&&this.config.position!=="top"&&(this.infoBarElement.remove(),this.infoBarElement=null)}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}getFilterState(){try{return this.grid?.getPluginState?.("filtering")??null}catch{return null}}refresh(){this.requestRender()}getContext(){const e=this.getSelectionState(),t=this.getFilterState();return gt(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())}styles=yn}const xn=pe;function En(o){const e=[];return!o.rowGroupFields?.length&&!o.columnGroupFields?.length&&e.push("At least one row or column group field is required"),o.valueFields?.length||e.push("At least one value field is required"),e}function ke(o,e){return[...o,e].join("|")}function Rn(o,e){const t=e.rowGroupFields??[],n=e.columnGroupFields??[],i=e.valueFields??[],r=_n(o,n),s=wt(o,t,n,r,i,0,""),l=An(s,r,i),a=Object.values(l).reduce((c,d)=>c+d,0);return{rows:s,columnKeys:r,totals:l,grandTotal:a}}function _n(o,e){if(e.length===0)return["value"];const t=new Set;for(const n of o){const i=e.map(r=>String(n[r]??"")).join("|");t.add(i)}return[...t].sort()}function Sn(o,e){const t=new Map;for(const n of o){const i=String(n[e]??""),r=t.get(i);r?r.push(n):t.set(i,[n])}return t}function wt(o,e,t,n,i,r,s){const l=[];if(e.length===0){const f=bt(o,t,n,i),h=mt(f);return l.push({rowKey:s||"all",rowLabel:s||"All",depth:r,values:f,total:h,isGroup:!1,rowCount:o.length}),l}const a=e[0],c=e.slice(1),d=c.length>0,u=Sn(o,a);for(const[f,h]of u){const p=s?`${s}|${f}`:f,g=bt(h,t,n,i),w=mt(g);let y;d&&(y=wt(h,c,t,n,i,r+1,p)),l.push({rowKey:p,rowLabel:f||"(blank)",depth:r,values:g,total:w,isGroup:d,children:y,rowCount:h.length})}return l}function bt(o,e,t,n){const i={};for(const r of t)for(const s of n){const a=(e.length>0?o.filter(f=>e.map(h=>String(f[h]??"")).join("|")===r):o).map(f=>Number(f[s.field])||0),c=xn(s.aggFunc),d=a.length>0?c(a):null,u=ke([r],s.field);i[u]=d}return i}function mt(o){let e=0;for(const t of Object.values(o))e+=t??0;return e}function An(o,e,t){const n={};function i(r){for(const s of r)if(!s.isGroup||!s.children?.length)for(const l of e)for(const a of t){const c=ke([l],a.field);n[c]=(n[c]??0)+(s.values[c]??0)}else s.children&&i(s.children)}return i(o),n}function kn(o,e,t=!0){const n=[];function i(r){n.push(r);const s=e?e.has(r.rowKey):t;if(r.children&&s)for(const l of r.children)i(l)}for(const r of o)i(r);return n}function Te(o){const e=[];function t(n){if(n.isGroup&&e.push(n.rowKey),n.children)for(const i of n.children)t(i)}for(const n of o)t(n);return e}const Tn=["sum","avg","count","min","max","first","last"];function Ln(o,e,t,n){const i=new AbortController,r={config:e,callbacks:n,signal:i.signal},s=document.createElement("div");return s.className="tbw-pivot-panel",s.appendChild(ne("Options",()=>Nn(t,r))),s.appendChild(ne("Row Groups",()=>vt("rowGroups",r))),s.appendChild(ne("Column Groups",()=>vt("columnGroups",r))),s.appendChild(ne("Values",()=>Mn(r))),s.appendChild(ne("Available Fields",()=>Hn(r))),o.appendChild(s),()=>{i.abort(),s.remove()}}function ne(o,e){const t=document.createElement("div");t.className="tbw-pivot-section";const n=document.createElement("div");n.className="tbw-pivot-section-header",n.textContent=o;const i=document.createElement("div");return i.className="tbw-pivot-section-content",i.appendChild(e()),t.appendChild(n),t.appendChild(i),t}function vt(o,e){const{config:t,callbacks:n,signal:i}=e,r=document.createElement("div");r.className="tbw-pivot-drop-zone",r.setAttribute("data-zone",o);const s=o==="rowGroups"?t.rowGroupFields??[]:t.columnGroupFields??[];if(s.length===0){const l=document.createElement("div");l.className="tbw-pivot-placeholder",l.textContent="Drag fields here or click to add",r.appendChild(l)}else for(const l of s)r.appendChild(Pn(l,o,e));return r.addEventListener("dragover",l=>{l.preventDefault(),r.classList.add("drag-over")},{signal:i}),r.addEventListener("dragleave",()=>{r.classList.remove("drag-over")},{signal:i}),r.addEventListener("drop",l=>{l.preventDefault(),r.classList.remove("drag-over");const a=l.dataTransfer?.getData("text/plain");a&&n.onAddFieldToZone(a,o)},{signal:i}),r}function Pn(o,e,t){const{callbacks:n,signal:i}=t,r=document.createElement("div");r.className="tbw-pivot-field-chip",r.draggable=!0;const s=n.getAvailableFields().find(c=>c.field===o),l=document.createElement("span");l.className="tbw-pivot-chip-label",l.textContent=s?.header??o;const a=document.createElement("button");return a.className="tbw-pivot-chip-remove",a.innerHTML="×",a.title="Remove field",a.addEventListener("click",c=>{c.stopPropagation(),n.onRemoveFieldFromZone(o,e)},{signal:i}),r.appendChild(l),r.appendChild(a),r.addEventListener("dragstart",c=>{c.dataTransfer?.setData("text/plain",o),c.dataTransfer?.setData("source-zone",e),r.classList.add("dragging")},{signal:i}),r.addEventListener("dragend",()=>{r.classList.remove("dragging")},{signal:i}),r}function Mn(o){const{config:e,callbacks:t,signal:n}=o,i=document.createElement("div");i.className="tbw-pivot-drop-zone tbw-pivot-values-zone",i.setAttribute("data-zone","values");const r=e.valueFields??[];if(r.length===0){const s=document.createElement("div");s.className="tbw-pivot-placeholder",s.textContent="Drag numeric fields here for aggregation",i.appendChild(s)}else for(const s of r)i.appendChild(In(s,o));return i.addEventListener("dragover",s=>{s.preventDefault(),i.classList.add("drag-over")},{signal:n}),i.addEventListener("dragleave",()=>{i.classList.remove("drag-over")},{signal:n}),i.addEventListener("drop",s=>{s.preventDefault(),i.classList.remove("drag-over");const l=s.dataTransfer?.getData("text/plain");l&&t.onAddValueField(l,"sum")},{signal:n}),i}function In(o,e){const{callbacks:t,signal:n}=e,i=document.createElement("div");i.className="tbw-pivot-field-chip tbw-pivot-value-chip";const r=t.getAvailableFields().find(d=>d.field===o.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=r?.header??o.field;const a=document.createElement("select");a.className="tbw-pivot-agg-select",a.title="Aggregation function";for(const d of Tn){const u=document.createElement("option");u.value=d,u.textContent=d.toUpperCase(),u.selected=d===o.aggFunc,a.appendChild(u)}a.addEventListener("change",()=>{t.onUpdateValueAggFunc(o.field,a.value)},{signal:n});const c=document.createElement("button");return c.className="tbw-pivot-chip-remove",c.innerHTML="×",c.title="Remove value field",c.addEventListener("click",d=>{d.stopPropagation(),t.onRemoveValueField(o.field)},{signal:n}),s.appendChild(l),s.appendChild(a),i.appendChild(s),i.appendChild(c),i}function Hn(o){const{config:e,callbacks:t,signal:n}=o,i=document.createElement("div");i.className="tbw-pivot-available-fields";const r=t.getAvailableFields(),s=new Set([...e.rowGroupFields??[],...e.columnGroupFields??[],...e.valueFields?.map(a=>a.field)??[]]),l=r.filter(a=>!s.has(a.field));if(l.length===0){const a=document.createElement("div");a.className="tbw-pivot-placeholder",a.textContent="All fields are in use",i.appendChild(a)}else for(const a of l){const c=document.createElement("div");c.className="tbw-pivot-field-chip available",c.textContent=a.header,c.draggable=!0,c.title=`Drag to add "${a.field}" to a zone`,c.addEventListener("dragstart",d=>{d.dataTransfer?.setData("text/plain",a.field),c.classList.add("dragging")},{signal:n}),c.addEventListener("dragend",()=>{c.classList.remove("dragging")},{signal:n}),i.appendChild(c)}return i}function Nn(o,e){const{config:t,callbacks:n,signal:i}=e,r=document.createElement("div");return r.className="tbw-pivot-options",r.appendChild(Le("Enable Pivot View",o,s=>{n.onTogglePivot(s)},i)),r.appendChild(Le("Show Row Totals",t.showTotals??!0,s=>{n.onOptionChange("showTotals",s)},i)),r.appendChild(Le("Show Grand Total",t.showGrandTotal??!0,s=>{n.onOptionChange("showGrandTotal",s)},i)),r}function Le(o,e,t,n){const i=document.createElement("label");i.className="tbw-pivot-checkbox";const r=document.createElement("input");r.type="checkbox",r.checked=e,r.addEventListener("change",()=>t(r.checked),{signal:n});const s=document.createElement("span");return s.textContent=o,i.appendChild(r),i.appendChild(s),i}function Dn(o,e,t){return e.className="pivot-group-row",e.setAttribute("data-pivot-depth",String(o.__pivotDepth??0)),e.setAttribute("data-pivot-key",String(o.__pivotRowKey??"")),e.setAttribute("role","row"),e.innerHTML="",t.columns.forEach((n,i)=>{const r=document.createElement("div");if(r.className="cell",r.setAttribute("data-col",String(i)),r.setAttribute("role","gridcell"),i===0){const s=Number(o.__pivotIndent)||0;r.style.paddingLeft=`${s}px`;const l=String(o.__pivotRowKey),a=document.createElement("button");a.type="button",a.className="pivot-toggle",a.setAttribute("aria-label",o.__pivotExpanded?"Collapse group":"Expand group"),t.setIcon(a,t.resolveIcon(o.__pivotExpanded?"collapse":"expand")),a.addEventListener("click",u=>{u.stopPropagation(),t.onToggle(l)}),r.appendChild(a);const c=document.createElement("span");c.className="pivot-label",c.textContent=String(o.__pivotLabel??""),r.appendChild(c);const d=document.createElement("span");d.className="pivot-count",d.textContent=` (${Number(o.__pivotRowCount)||0})`,r.appendChild(d)}else{const s=o[n.field];r.textContent=s!=null?String(s):""}e.appendChild(r)}),!0}function On(o,e,t){return e.className="pivot-leaf-row",e.setAttribute("data-pivot-depth",String(o.__pivotDepth??0)),e.setAttribute("data-pivot-key",String(o.__pivotRowKey??"")),e.innerHTML="",t.forEach((n,i)=>{const r=document.createElement("div");if(r.className="cell",r.setAttribute("data-col",String(i)),r.setAttribute("role","gridcell"),i===0){const s=Number(o.__pivotIndent)||0;r.style.paddingLeft=`${s+20}px`;const l=document.createElement("span");l.className="pivot-label",l.textContent=String(o.__pivotLabel??""),r.appendChild(l)}else{const s=o[n.field];r.textContent=s!=null?String(s):""}e.appendChild(r)}),!0}function zn(o,e,t){return e.className="pivot-grand-total-row",e.setAttribute("role","presentation"),e.innerHTML="",t.forEach((n,i)=>{const r=document.createElement("div");if(r.className="cell",r.setAttribute("data-col",String(i)),i===0){const s=document.createElement("span");s.className="pivot-label",s.textContent="Grand Total",r.appendChild(s)}else{const s=o[n.field];r.textContent=s!=null?String(s):""}e.appendChild(r)}),!0}const Fn='.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:18px;height:18px;margin-right:6px;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 .15s,color .15s}.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:12px;padding:12px;height:100%;overflow-y:auto;font-size:13px}.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:8px 12px;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:8px}.tbw-pivot-toggle-wrapper{display:flex;align-items:center}.tbw-pivot-toggle-label{display:flex;align-items:center;gap:8px;cursor:pointer}.tbw-pivot-toggle-label input{width:16px;height:16px;cursor:pointer}.tbw-pivot-drop-zone{min-height:60px;padding:8px;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:6px;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:8px;text-align:center;width:100%}.tbw-pivot-field-chip{display:inline-flex;align-items:center;gap:6px;padding:4px 8px;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:12px;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:16px;height:16px;padding:0;border:none;background:transparent;color:var(--tbw-color-fg-muted);font-size:14px;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:4px 8px}.tbw-pivot-value-label-wrapper{display:flex;align-items:center;gap:8px;flex:1;min-width:0}.tbw-pivot-agg-select{padding:2px 4px;font-size:11px;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:6px;min-height:40px}.tbw-pivot-options{display:flex;flex-direction:column;gap:8px}.tbw-pivot-checkbox{display:flex;align-items:center;gap:8px;cursor:pointer}.tbw-pivot-checkbox input{width:14px;height:14px;cursor:pointer}.pivot-group-row.tbw-pivot-slide-in,.pivot-leaf-row.tbw-pivot-slide-in{animation:tbw-pivot-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-pivot-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.pivot-group-row.tbw-pivot-fade-in,.pivot-leaf-row.tbw-pivot-fade-in{animation:tbw-pivot-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-pivot-fade-in{0%{opacity:0}to{opacity:1}}';class Y extends L{name="pivot";version="1.0.0";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;originalColumns=[];panelContainer=null;grandTotalFooter=null;previousVisibleKeys=new Set;keysToAnimate=new Set;hasValidPivotConfig(){return(this.config.valueFields?.length??0)>0}get animationStyle(){const t=this.grid.effectiveConfig?.animation?.mode??"reduced-motion";if(t===!1||t==="off")return!1;if(t!==!0&&t!=="on"){const n=this.shadowRoot?.host;if(n&&getComputedStyle(n).getPropertyValue("--tbw-animation-enabled").trim()==="0")return!1}return 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()}getToolPanel(){if((this.config?.showToolPanel??this.userConfig?.showToolPanel??!0)!==!1)return{id:Y.PANEL_ID,title:"Pivot",icon:"⊞",tooltip:"Configure pivot table",order:90,render:t=>this.renderPanel(t)}}processRows(e){if(!this.hasInitialized&&this.config.active!==!1&&this.hasValidPivotConfig()&&(this.hasInitialized=!0,this.isActive=!0),!this.isActive)return[...e];const t=En(this.config);if(t.length>0)return this.warn(`Config errors: ${t.join(", ")}`),[...e];if(this.buildFieldHeaderMap(),this.defaultExpanded=this.config.defaultExpanded??!0,this.expandedKeys.size===0&&this.defaultExpanded&&this.pivotResult){const s=Te(this.pivotResult.rows);for(const l of s)this.expandedKeys.add(l)}if(this.pivotResult=Rn(e,this.config),this.expandedKeys.size===0&&this.defaultExpanded){const s=Te(this.pivotResult.rows);for(const l of s)this.expandedKeys.add(l)}const n=this.config.indentWidth??20,i=kn(this.pivotResult.rows,this.expandedKeys,this.defaultExpanded).map(s=>({__pivotRowKey:s.rowKey,__pivotLabel:s.rowLabel,__pivotDepth:s.depth,__pivotIsGroup:s.isGroup,__pivotHasChildren:!!s.children?.length,__pivotExpanded:this.expandedKeys.has(s.rowKey),__pivotRowCount:s.rowCount??0,__pivotIndent:s.depth*n,__pivotTotal:s.total,...s.values}));this.keysToAnimate.clear();const r=new Set;for(const s of i){const l=s.__pivotRowKey;r.add(l),!this.previousVisibleKeys.has(l)&&s.__pivotDepth>0&&this.keysToAnimate.add(l)}return this.previousVisibleKeys=r,i}processColumns(e){if(!this.isActive||!this.pivotResult)return[...e];const t=[],n=(this.config.rowGroupFields??[]).map(i=>this.fieldHeaderMap.get(i)??i).join(" / ");t.push({field:"__pivotLabel",header:n||"Group",width:200});for(const i of this.pivotResult.columnKeys)for(const r of this.config.valueFields??[]){const s=ke([i],r.field),l=r.header||this.fieldHeaderMap.get(r.field)||r.field;t.push({field:s,header:`${i} - ${l} (${r.aggFunc})`,width:120,type:"number"})}return this.config.showTotals&&t.push({field:"__pivotTotal",header:"Total",width:100,type:"number"}),t}renderRow(e,t){const n=e;return n.__pivotRowKey&&n.__pivotHasChildren?Dn(n,t,{columns:this.gridColumns,onToggle:i=>this.toggle(i),resolveIcon:i=>this.resolveIcon(i),setIcon:(i,r)=>this.setIcon(i,r)}):n.__pivotRowKey!==void 0&&this.isActive?On(n,t,this.gridColumns):(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="")}afterRender(){this.isActive&&this.config.showGrandTotal&&this.pivotResult?this.renderGrandTotalFooter():this.cleanupGrandTotalFooter();const e=this.animationStyle;if(e===!1||this.keysToAnimate.size===0)return;const t=this.shadowRoot?.querySelector(".rows");if(!t)return;const n=e==="fade"?"tbw-pivot-fade-in":"tbw-pivot-slide-in";for(const i of t.querySelectorAll(".pivot-group-row, .pivot-leaf-row")){const r=i.dataset.pivotKey;r&&this.keysToAnimate.has(r)&&(i.classList.add(n),i.addEventListener("animationend",()=>i.classList.remove(n),{once:!0}))}this.keysToAnimate.clear()}renderGrandTotalFooter(){if(!this.pivotResult)return;const e=this.shadowRoot;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 n={__pivotRowKey:"__grandTotal",__pivotLabel:"Grand Total",__pivotIsGrandTotal:!0,__pivotTotal:this.pivotResult.grandTotal,...this.pivotResult.totals};zn(n,this.grandTotalFooter,this.gridColumns)}cleanupGrandTotalFooter(){this.grandTotalFooter&&(this.grandTotalFooter.remove(),this.grandTotalFooter=null)}toggle(e){this.expandedKeys.has(e)?this.expandedKeys.delete(e):this.expandedKeys.add(e),this.requestRender()}expand(e){this.expandedKeys.add(e),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}expandAll(){if(this.pivotResult){const e=Te(this.pivotResult.rows);for(const t of e)this.expandedKeys.add(t);this.requestRender()}}collapseAll(){this.expandedKeys.clear(),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}enablePivot(){this.originalColumns.length===0&&this.captureOriginalColumns(),this.isActive=!0,this.requestRender()}disablePivot(){this.isActive=!1,this.pivotResult=null,this.requestRender()}isPivotActive(){return this.isActive}getPivotResult(){return this.pivotResult}setRowGroupFields(e){this.config.rowGroupFields=e,this.requestRender()}setColumnGroupFields(e){this.config.columnGroupFields=e,this.requestRender()}setValueFields(e){this.config.valueFields=e,this.requestRender()}refresh(){this.pivotResult=null,this.requestRender()}showPanel(){this.grid.openToolPanel(Y.PANEL_ID)}hidePanel(){this.grid.closeToolPanel()}togglePanel(){this.grid.toggleToolPanel(Y.PANEL_ID)}isPanelVisible(){return this.grid.activeToolPanel===Y.PANEL_ID}get gridColumns(){return this.grid.columns??[]}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(){const e=this.grid;try{const t=e.getAllColumns?.()??e.columns??[];return this.originalColumns=t.filter(n=>!n.field.startsWith("__pivot")).map(n=>({field:n.field,header:n.header??n.field})),this.originalColumns}catch{return[]}}renderPanel(e){this.panelContainer=e,this.originalColumns.length===0&&this.captureOriginalColumns();const t={onTogglePivot:n=>{n?this.enablePivot():this.disablePivot(),this.refreshPanel()},onAddFieldToZone:(n,i)=>this.addFieldToZone(n,i),onRemoveFieldFromZone:(n,i)=>this.removeFieldFromZone(n,i),onAddValueField:(n,i)=>this.addValueField(n,i),onRemoveValueField:n=>this.removeValueField(n),onUpdateValueAggFunc:(n,i)=>this.updateValueAggFunc(n,i),onOptionChange:(n,i)=>{this.config[n]=i,this.isActive&&this.refresh()},getAvailableFields:()=>this.getAvailableFields()};return Ln(e,this.config,this.isActive,t)}refreshPanel(){this.panelContainer&&(this.panelContainer.innerHTML="",this.renderPanel(this.panelContainer))}addFieldToZone(e,t){if(t==="rowGroups"){const n=this.config.rowGroupFields??[];n.includes(e)||(this.config.rowGroupFields=[...n,e])}else{const n=this.config.columnGroupFields??[];n.includes(e)||(this.config.columnGroupFields=[...n,e])}this.removeFromOtherZones(e,t),this.isActive&&this.refresh(),this.refreshPanel()}removeFieldFromZone(e,t){t==="rowGroups"?this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(n=>n!==e):this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(n=>n!==e),this.isActive&&this.refresh(),this.refreshPanel()}removeFromOtherZones(e,t){t!=="rowGroups"&&(this.config.rowGroupFields=(this.config.rowGroupFields??[]).filter(n=>n!==e)),t!=="columnGroups"&&(this.config.columnGroupFields=(this.config.columnGroupFields??[]).filter(n=>n!==e)),t!=="values"&&(this.config.valueFields=(this.config.valueFields??[]).filter(n=>n.field!==e))}addValueField(e,t){const n=this.config.valueFields??[];n.some(i=>i.field===e)||(this.config.valueFields=[...n,{field:e,aggFunc:t}]),this.removeFromOtherZones(e,"values"),this.isActive&&this.refresh(),this.refreshPanel()}removeValueField(e){this.config.valueFields=(this.config.valueFields??[]).filter(t=>t.field!==e),this.isActive&&this.refresh(),this.refreshPanel()}updateValueAggFunc(e,t){const n=this.config.valueFields??[],i=n.findIndex(r=>r.field===e);i>=0&&(n[i]={...n[i],aggFunc:t},this.config.valueFields=[...n]),this.isActive&&this.refresh()}styles=Fn}function yt(o){const e=o.meta??{};return e.lockPosition!==!0&&e.suppressMovable!==!0}function Ct(o,e,t){if(e===t||e<0||e>=o.length||t<0||t>o.length)return o;const n=[...o],[i]=n.splice(e,1);return n.splice(t,0,i),n}const qn='.header-row>.cell[draggable=true]{cursor:grab;position:relative}.header-row>.cell.dragging{opacity:.5;cursor:grabbing}.header-row>.cell.drop-before:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.header-row>.cell.drop-after:after{content:"";position:absolute;right:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.cell.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}@keyframes reorder-fade-in{0%{opacity:0}to{opacity:1}}.cell.fade-animating{animation:reorder-fade-in var(--tbw-animation-duration, .2s) ease-out backwards}';class Bn extends L{name="reorder";version="1.0.0";get defaultConfig(){return{animation:"flip"}}get animationType(){return this.isAnimationEnabled?this.config.animation!==void 0?this.config.animation:this.config.viewTransition===!1?!1:(this.config.viewTransition===!0,"flip"):!1}get isAnimationEnabled(){const t=this.grid.effectiveConfig?.animation?.mode??"reduced-motion";if(t===!1||t==="off")return!1;if(t===!0||t==="on")return!0;const n=this.shadowRoot?.host;return n?getComputedStyle(n).getPropertyValue("--tbw-animation-enabled").trim()!=="0":!0}get animationDuration(){if(this.config.animationDuration!==void 0)return this.config.animationDuration;const e=this.shadowRoot?.host;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),n=parseInt(t,10);if(!isNaN(n))return n}return 200}isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;attach(e){super.attach(e),e.addEventListener("column-reorder-request",t=>{const n=t.detail;n?.field&&typeof n.toIndex=="number"&&this.moveColumn(n.field,n.toIndex)},{signal:this.disconnectSignal})}detach(){this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}afterRender(){const e=this.shadowRoot;if(!e)return;e.querySelectorAll(".header-row > .cell").forEach(n=>{const i=n,r=i.getAttribute("data-field");if(!r)return;const s=this.columns.find(d=>d.field===r),c=!this.grid.queryPlugins({type:ee.CAN_MOVE_COLUMN,context:s}).includes(!1);if(!s||!yt(s)||!c){i.draggable=!1;return}i.draggable=!0,!i.getAttribute("data-dragstart-bound")&&(i.setAttribute("data-dragstart-bound","true"),i.addEventListener("dragstart",d=>{const f=this.getColumnOrder().indexOf(r);this.isDragging=!0,this.draggedField=r,this.draggedIndex=f,d.dataTransfer&&(d.dataTransfer.effectAllowed="move",d.dataTransfer.setData("text/plain",r)),i.classList.add("dragging")}),i.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,e.querySelectorAll(".header-row > .cell").forEach(d=>{d.classList.remove("dragging","drop-target","drop-before","drop-after")})}),i.addEventListener("dragover",d=>{if(d.preventDefault(),!this.isDragging||this.draggedField===r)return;const u=i.getBoundingClientRect(),f=u.left+u.width/2,p=this.getColumnOrder().indexOf(r);this.dropIndex=d.clientX<f?p:p+1,i.classList.add("drop-target"),i.classList.toggle("drop-before",d.clientX<f),i.classList.toggle("drop-after",d.clientX>=f)}),i.addEventListener("dragleave",()=>{i.classList.remove("drop-target","drop-before","drop-after")}),i.addEventListener("drop",d=>{d.preventDefault();const u=this.draggedField,f=this.draggedIndex,h=this.dropIndex;if(!this.isDragging||u===null||f===null||h===null)return;const p=h>f?h-1:h,g=this.getColumnOrder(),w=Ct(g,f,p),y={field:u,fromIndex:f,toIndex:p,columnOrder:w};this.updateColumnOrder(w),this.emit("column-move",y)}))})}onKeyDown(e){if(!e.altKey||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const t=this.grid,n=t._focusCol,i=t._visibleColumns;if(n<0||n>=i.length)return;const r=i[n];if(!r||!yt(r))return;const s=this.grid;if(s.queryPlugins({type:ee.CAN_MOVE_COLUMN,context:r}).includes(!1))return;const a=this.getColumnOrder(),c=a.indexOf(r.field);if(c===-1)return;const d=e.key==="ArrowLeft"?c-1:c+1;if(d<0||d>=a.length)return;const u=i.find(f=>f.field===a[d]);if(!(u&&s.queryPlugins({type:ee.CAN_MOVE_COLUMN,context:u}).includes(!1)))return this.moveColumn(r.field,d),t._focusCol=d,O(this.grid),e.preventDefault(),e.stopPropagation(),!0}getColumnOrder(){return this.grid.getColumnOrder()}moveColumn(e,t){const n=this.getColumnOrder(),i=n.indexOf(e);if(i===-1)return;const r=Ct(n,i,t);this.updateColumnOrder(r),this.emit("column-move",{field:e,fromIndex:i,toIndex:t,columnOrder:r})}setColumnOrder(e){this.updateColumnOrder(e)}resetColumnOrder(){const e=this.columns.map(t=>t.field);this.updateColumnOrder(e)}captureHeaderPositions(){const e=new Map;return this.shadowRoot?.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const n=t.getAttribute("data-field");n&&e.set(n,t.getBoundingClientRect().left)}),e}animateFLIP(e){const t=this.shadowRoot;if(!t||e.size===0)return;const n=new Map;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(s=>{const l=s.getAttribute("data-field");if(!l)return;const a=e.get(l);if(a===void 0)return;const c=a-s.getBoundingClientRect().left;Math.abs(c)>1&&n.set(l,c)}),n.size===0)return;const i=[];if(t.querySelectorAll(".cell[data-field]").forEach(s=>{const l=n.get(s.getAttribute("data-field")??"");if(l!==void 0){const a=s;a.style.transform=`translateX(${l}px)`,i.push(a)}}),i.length===0)return;t.host.offsetHeight;const r=this.animationDuration;requestAnimationFrame(()=>{i.forEach(s=>{s.classList.add("flip-animating"),s.style.transform=""}),setTimeout(()=>{i.forEach(s=>{s.style.transform="",s.classList.remove("flip-animating")})},r+50)})}animateFade(e){const t=this.shadowRoot;if(!t){e();return}const n=this.captureHeaderPositions();e();const i=new Set;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(l=>{const a=l.getAttribute("data-field");if(!a)return;const c=n.get(a);if(c===void 0)return;const d=l.getBoundingClientRect().left;Math.abs(c-d)>1&&i.add(a)}),i.size===0)return;const r=[];if(t.querySelectorAll(".cell[data-field]").forEach(l=>{const a=l.getAttribute("data-field");if(a&&i.has(a)){const c=l;c.classList.add("fade-animating"),r.push(c)}}),r.length===0)return;const s=this.animationDuration;setTimeout(()=>{r.forEach(l=>l.classList.remove("fade-animating"))},s+50)}updateColumnOrder(e){const t=this.grid,n=this.animationType;if(n==="flip"&&this.shadowRoot){const i=this.captureHeaderPositions();t.setColumnOrder(e),this.shadowRoot.host.offsetHeight,this.animateFLIP(i)}else n==="fade"?this.animateFade(()=>t.setColumnOrder(e)):t.setColumnOrder(e);t.requestStateChange?.()}styles=qn}function re(o){return{startRow:Math.min(o.startRow,o.endRow),startCol:Math.min(o.startCol,o.endCol),endRow:Math.max(o.startRow,o.endRow),endCol:Math.max(o.startCol,o.endCol)}}function Kn(o){const e=re(o);return{from:{row:e.startRow,col:e.startCol},to:{row:e.endRow,col:e.endCol}}}function Pe(o){return o.map(Kn)}function Vn(o,e,t){const n=re(t);return o>=n.startRow&&o<=n.endRow&&e>=n.startCol&&e<=n.endCol}function xt(o,e,t){return t.some(n=>Vn(o,e,n))}function $n(o){const e=[],t=re(o);for(let n=t.startRow;n<=t.endRow;n++)for(let i=t.startCol;i<=t.endCol;i++)e.push({row:n,col:i});return e}function Gn(o){const e=new Map;for(const t of o)for(const n of $n(t))e.set(`${n.row},${n.col}`,n);return[...e.values()]}function Me(o,e){return{startRow:o.row,startCol:o.col,endRow:e.row,endCol:e.col}}const Wn=':host .selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}:host .data-grid-row.row-focus{background-color:var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%))}:host([data-selection-mode="row"]) .cell-focus{outline:none}:host .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg)}:host .data-grid-row>.cell.selected.top{border-top:2px solid var(--tbw-range-border-color)}:host .data-grid-row>.cell.selected.bottom{border-bottom:2px solid var(--tbw-range-border-color)}:host .data-grid-row>.cell.selected.first{border-left:2px solid var(--tbw-range-border-color)}:host .data-grid-row>.cell.selected.last{border-right:2px solid var(--tbw-range-border-color)}';function Un(o,e,t){if(o==="cell"&&e.selectedCell)return{mode:o,ranges:[{from:{row:e.selectedCell.row,col:e.selectedCell.col},to:{row:e.selectedCell.row,col:e.selectedCell.col}}]};if(o==="row"&&e.selected.size>0){const n=[...e.selected].map(i=>({from:{row:i,col:0},to:{row:i,col:t-1}}));return{mode:o,ranges:n}}return o==="range"&&e.ranges.length>0?{mode:o,ranges:Pe(e.ranges)}:{mode:o,ranges:[]}}class jn extends L{name="selection";version="1.0.0";get defaultConfig(){return{mode:"cell"}}selected=new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;selectedCell=null;detach(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.pendingKeyboardUpdate=null}onCellClick(e){const{rowIndex:t,colIndex:n,originalEvent:i}=e,{mode:r}=this.config;if(r==="cell")return this.selectedCell={row:t,col:n},this.emit("selection-change",this.#r()),this.requestAfterRender(),!1;if(r==="row")return this.selected.clear(),this.selected.add(t),this.lastSelected=t,this.emit("selection-change",this.#r()),this.requestAfterRender(),!1;if(r==="range"){const s=i.shiftKey,l=i.ctrlKey||i.metaKey;if(s&&this.cellAnchor){const a=Me(this.cellAnchor,{row:t,col:n});l?this.ranges.length>0?this.ranges[this.ranges.length-1]=a:this.ranges.push(a):this.ranges=[a],this.activeRange=a}else if(l){const a={startRow:t,startCol:n,endRow:t,endCol:n};this.ranges.push(a),this.activeRange=a,this.cellAnchor={row:t,col:n}}else{const a={startRow:t,startCol:n,endRow:t,endCol:n};this.ranges=[a],this.activeRange=a,this.cellAnchor={row:t,col:n}}return this.emit("selection-change",this.#r()),this.requestAfterRender(),!1}return!1}onKeyDown(e){const{mode:t}=this.config,i=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"].includes(e.key);if(e.key==="Escape")return t==="cell"?this.selectedCell=null:t==="row"?(this.selected.clear(),this.anchor=null):t==="range"&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#r()),this.requestAfterRender(),!0;if(t==="cell"&&i)return queueMicrotask(()=>{this.selectedCell={row:this.grid._focusRow,col:this.grid._focusCol},this.emit("selection-change",this.#r()),this.requestAfterRender()}),!1;if(t==="row"&&(e.key==="ArrowUp"||e.key==="ArrowDown"))return queueMicrotask(()=>{this.selected.clear(),this.selected.add(this.grid._focusRow),this.lastSelected=this.grid._focusRow,this.emit("selection-change",this.#r()),this.requestAfterRender()}),!1;if(t==="range"&&i)return e.shiftKey&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:e.shiftKey},queueMicrotask(()=>this.requestAfterRender()),!1;if(t==="range"&&e.key==="a"&&(e.ctrlKey||e.metaKey)){const r=this.rows.length,s=this.columns.length;if(r>0&&s>0){const l={startRow:0,startCol:0,endRow:r-1,endCol:s-1};return this.ranges=[l],this.activeRange=l,this.emit("selection-change",this.#r()),this.requestAfterRender(),!0}}return!1}onCellMouseDown(e){if(this.config.mode!=="range"||e.rowIndex===void 0||e.colIndex===void 0||e.rowIndex<0||e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const t=e.rowIndex,n=e.colIndex;this.cellAnchor={row:t,col:n},e.originalEvent.ctrlKey||e.originalEvent.metaKey||(this.ranges=[]);const r={startRow:t,startCol:n,endRow:t,endCol:n};return this.ranges.push(r),this.activeRange=r,this.emit("selection-change",this.#r()),this.requestAfterRender(),!0}onCellMouseMove(e){if(this.config.mode!=="range"||!this.isDragging||!this.cellAnchor||e.rowIndex===void 0||e.colIndex===void 0||e.rowIndex<0)return;const t=Me(this.cellAnchor,{row:e.rowIndex,col:e.colIndex});return this.ranges.length>0?this.ranges[this.ranges.length-1]=t:this.ranges.push(t),this.activeRange=t,this.emit("selection-change",this.#r()),this.requestAfterRender(),!0}onCellMouseUp(e){if(this.config.mode==="range"&&this.isDragging)return this.isDragging=!1,!0}#o(){const e=this.shadowRoot;if(!e)return;const{mode:t}=this.config;e.querySelectorAll(".cell").forEach(r=>{r.classList.remove("selected","top","bottom","first","last")});const i=e.querySelectorAll(".data-grid-row");if(i.forEach(r=>{r.classList.remove("selected","row-focus")}),t==="row"&&(e.querySelectorAll(".cell-focus").forEach(r=>r.classList.remove("cell-focus")),i.forEach(r=>{const s=r.querySelector(".cell[data-row]"),l=parseInt(s?.getAttribute("data-row")??"-1",10);l>=0&&this.selected.has(l)&&r.classList.add("selected","row-focus")})),t==="range"&&this.ranges.length>0){const r=this.activeRange?re(this.activeRange):null;e.querySelectorAll(".cell[data-row][data-col]").forEach(l=>{const a=parseInt(l.getAttribute("data-row")??"-1",10),c=parseInt(l.getAttribute("data-col")??"-1",10);a>=0&&c>=0&&xt(a,c,this.ranges)&&(l.classList.add("selected"),l.classList.remove("cell-focus"),r&&(a===r.startRow&&l.classList.add("top"),a===r.endRow&&l.classList.add("bottom"),c===r.startCol&&l.classList.add("first"),c===r.endCol&&l.classList.add("last")))})}t==="cell"&&this.selectedCell&&e.querySelectorAll(".cell-focus").forEach(r=>r.classList.remove("cell-focus"))}afterRender(){const e=this.shadowRoot;if(!e)return;const t=e.children[0],{mode:n}=this.config;if(this.pendingKeyboardUpdate&&n==="range"){const{shiftKey:i}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const r=this.grid._focusRow,s=this.grid._focusCol;if(i&&this.cellAnchor){const l=Me(this.cellAnchor,{row:r,col:s});this.ranges=[l],this.activeRange=l}else i||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:r,col:s});this.emit("selection-change",this.#r())}this.grid.setAttribute("data-selection-mode",n),t&&t.classList.toggle("selecting",this.isDragging),this.#o()}onScrollRender(){this.#o()}getSelectedCell(){return this.selectedCell}getSelectedRows(){return[...this.selected]}getRanges(){return Pe(this.ranges)}getSelectedCells(){return Gn(this.ranges)}isCellSelected(e,t){return xt(e,t,this.ranges)}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.emit("selection-change",{mode:this.config.mode,ranges:[]}),this.requestAfterRender()}setRanges(e){this.ranges=e.map(t=>({startRow:t.from.row,startCol:t.from.col,endRow:t.to.row,endCol:t.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",{mode:this.config.mode,ranges:Pe(this.ranges)}),this.requestAfterRender()}#r(){return Un(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}styles=Wn}function se(o,e){return Math.floor(o/e)}function Xn(o,e){return{start:o*e,end:(o+1)*e}}function Yn(o,e,t){const n=se(o,t),i=se(e-1,t),r=[];for(let s=n;s<=i;s++)r.push(s);return r}async function Et(o,e,t,n){const i=Xn(e,t);return o.getRows({startRow:i.start,endRow:i.end,sortModel:n.sortModel,filterModel:n.filterModel})}function Zn(o,e,t){const n=se(o,e),i=t.get(n);if(!i)return;const r=o%e;return i[r]}const Jn=100;class Qn extends L{name="serverSide";version="1.0.0";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,n={startRow:e._virtualization.start,endRow:e._virtualization.end},i=Yn(n.startRow,n.endRow,t);for(const r of i)if(!(this.loadedBlocks.has(r)||this.loadingBlocks.has(r))){if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2))break;this.loadingBlocks.add(r),Et(this.dataSource,r,t,{}).then(s=>{this.loadedBlocks.set(r,s.rows),this.totalRowCount=s.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 n=0;n<this.totalRowCount;n++){const i=Zn(n,this.config.cacheBlockSize??100,this.loadedBlocks);t.push(i??{__loading:!0,__index:n})}return t}onScroll(e){this.dataSource&&(this.loadRequiredBlocks(),this.scrollDebounceTimer&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.loadRequiredBlocks()},Jn))}setDataSource(e){this.dataSource=e,this.loadedBlocks.clear(),this.loadingBlocks.clear();const t=this.config.cacheBlockSize??100;Et(e,0,t,{}).then(n=>{this.loadedBlocks.set(0,n.rows),this.totalRowCount=n.totalRowCount,this.requestRender()})}refresh(){this.dataSource&&(this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.requestRender())}purgeCache(){this.loadedBlocks.clear()}getTotalRowCount(){return this.totalRowCount}isRowLoaded(e){const t=this.config.cacheBlockSize??100,n=se(e,t);return this.loadedBlocks.has(n)}getLoadedBlockCount(){return this.loadedBlocks.size}}function Rt(o,e,t){return o.id!==void 0?String(o.id):t?`${t}-${e}`:String(e)}function _t(o,e){const t=new Set(o);return t.has(e)?t.delete(e):t.add(e),t}function Ie(o,e,t=null,n=0){const i=e.childrenField??"children",r=new Set;for(let s=0;s<o.length;s++){const l=o[s],a=Rt(l,s,t),c=l[i];if(Array.isArray(c)&&c.length>0){r.add(a);const d=Ie(c,e,a,n+1);for(const u of d)r.add(u)}}return r}function ei(){return new Set}function St(o,e,t,n=null,i=0){const r=t.childrenField??"children";for(let s=0;s<o.length;s++){const l=o[s],a=Rt(l,s,n);if(a===e)return[a];const c=l[r];if(Array.isArray(c)&&c.length>0){const d=St(c,e,t,a,i+1);if(d)return[a,...d]}}return null}function ti(o,e,t,n){const i=St(o,e,t);if(!i)return n;const r=new Set(n);for(let s=0;s<i.length-1;s++)r.add(i[s]);return r}function At(o,e="children"){if(!Array.isArray(o)||o.length===0)return!1;for(const t of o)if(t&&Array.isArray(t[e])&&t[e].length>0)return!0;return!1}function oi(o){if(!Array.isArray(o)||o.length===0)return null;const e=["children","items","nodes","subRows","nested"];for(const t of o)if(!(!t||typeof t!="object")){for(const n of e)if(Array.isArray(t[n])&&t[n].length>0)return n}return null}const ni=".tree-cell{display:flex;align-items:center;padding-left:calc(var(--tree-depth, 0) * var(--tbw-tree-indent, 20px))}.tree-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;margin-right:4px}.tree-toggle:hover{color:var(--tbw-tree-accent, var(--tbw-color-accent))}.tree-spacer{width:14px;display:inline-block}.data-grid-row.tbw-tree-slide-in{animation:tbw-tree-slide-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)}}.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-fade-in{0%{opacity:0}to{opacity:1}}";class ii extends L{name="tree";version="1.0.0";styles=ni;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}get animationStyle(){const t=this.grid.effectiveConfig?.animation?.mode??"reduced-motion";if(t===!1||t==="off")return!1;if(t!==!0&&t!=="on"){const n=this.shadowRoot?.host;if(n&&getComputedStyle(n).getPropertyValue("--tbw-animation-enabled").trim()==="0")return!1}return this.config.animation??"slide"}detect(e){if(!this.config.autoDetect)return!1;const t=this.config.childrenField??oi(e)??"children";return At(e,t)}processRows(e){const t=this.config.childrenField??"children";if(!At(e,t))return this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),[...e];let n=this.withStableKeys(e);this.sortState&&(n=this.sortTree(n,this.sortState.field,this.sortState.direction)),this.config.defaultExpanded&&!this.initialExpansionDone&&(this.expandedKeys=Ie(n,this.config),this.initialExpansionDone=!0),this.flattenedRows=this.flattenTree(n,this.expandedKeys),this.rowKeyMap.clear(),this.keysToAnimate.clear();const i=new Set;for(const r of this.flattenedRows)this.rowKeyMap.set(r.key,r),i.add(r.key),!this.previousVisibleKeys.has(r.key)&&r.depth>0&&this.keysToAnimate.add(r.key);return this.previousVisibleKeys=i,this.flattenedRows.map(r=>({...r.data,__treeKey:r.key,__treeDepth:r.depth,__treeHasChildren:r.hasChildren,__treeExpanded:r.isExpanded}))}withStableKeys(e,t=null){const n=this.config.childrenField??"children";return e.map((i,r)=>{const s=i.id!==void 0?String(i.id):i.__stableKey??(t?`${t}-${r}`:String(r)),l=i[n],a=Array.isArray(l)&&l.length>0;return{...i,__stableKey:s,...a?{[n]:this.withStableKeys(l,s)}:{}}})}flattenTree(e,t,n=0){const i=this.config.childrenField??"children",r=[];for(const s of e){const l=s.__stableKey??s.id??"?",a=s[i],c=Array.isArray(a)&&a.length>0,d=t.has(l);r.push({key:l,data:s,depth:n,hasChildren:c,isExpanded:d,parentKey:n>0&&l.substring(0,l.lastIndexOf("-"))||null}),c&&d&&r.push(...this.flattenTree(a,t,n+1))}return r}sortTree(e,t,n){const i=this.config.childrenField??"children";return[...e].sort((s,l)=>{const a=s[t],c=l[t];return a==null&&c==null?0:a==null?-1:c==null?1:a>c?n:a<c?-n:0}).map(s=>{const l=s[i];return Array.isArray(l)&&l.length>0?{...s,[i]:this.sortTree(l,t,n)}:s})}processColumns(e){if(this.flattenedRows.length===0)return[...e];const t=[...e];if(t.length===0)return t;const n={...t[0]},i=n.viewRenderer;if(i?.__treeWrapped)return t;const r=()=>this.config,s=this.setIcon.bind(this),l=this.resolveIcon.bind(this),a=c=>{const{value:d,row:u}=c,{indentWidth:f=20,showExpandIcons:h=!0}=r(),p=document.createElement("span");if(p.className="tree-cell",p.style.setProperty("--tree-depth",String(u.__treeDepth??0)),p.style.setProperty("--tbw-tree-indent",`${f}px`),u.__treeHasChildren&&h){const w=document.createElement("span");w.className=`tree-toggle${u.__treeExpanded?" expanded":""}`,s(w,l(u.__treeExpanded?"collapse":"expand")),w.setAttribute("data-tree-key",u.__treeKey),p.appendChild(w)}else if(h){const w=document.createElement("span");w.className="tree-spacer",p.appendChild(w)}const g=document.createElement("span");if(i){const w=i(c);w instanceof Node?g.appendChild(w):g.textContent=String(w??d??"")}else g.textContent=String(d??"");return p.appendChild(g),p};return a.__treeWrapped=!0,n.viewRenderer=a,t[0]=n,t}onCellClick(e){const t=e.originalEvent?.target;if(!t?.classList.contains("tree-toggle"))return!1;const n=t.getAttribute("data-tree-key"),i=n?this.rowKeyMap.get(n):null;return i?(this.expandedKeys=_t(this.expandedKeys,n),this.emit("tree-expand",{key:n,row:i.data,expanded:this.expandedKeys.has(n),depth:i.depth}),this.requestRender(),!0):!1}onHeaderClick(e){if(this.flattenedRows.length===0||!e.column.sortable)return!1;const{field:t}=e.column;!this.sortState||this.sortState.field!==t?this.sortState={field:t,direction:1}:this.sortState.direction===1?this.sortState={field:t,direction:-1}:this.sortState=null;const n=this.grid;return n._sortState!==void 0&&(n._sortState=this.sortState?{...this.sortState}:null),this.emit("sort-change",{field:t,direction:this.sortState?.direction??0}),this.requestRender(),!0}afterRender(){const e=this.animationStyle;if(e===!1||this.keysToAnimate.size===0)return;const t=this.shadowRoot?.querySelector(".rows");if(!t)return;const n=e==="fade"?"tbw-tree-fade-in":"tbw-tree-slide-in";for(const i of t.querySelectorAll(".data-grid-row")){const r=i.querySelector(".cell[data-row]"),s=r?parseInt(r.getAttribute("data-row")??"-1",10):-1,l=this.flattenedRows[s]?.key;l&&this.keysToAnimate.has(l)&&(i.classList.add(n),i.addEventListener("animationend",()=>i.classList.remove(n),{once:!0}))}this.keysToAnimate.clear()}expand(e){this.expandedKeys.add(e),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}toggle(e){this.expandedKeys=_t(this.expandedKeys,e),this.requestRender()}expandAll(){this.expandedKeys=Ie(this.rows,this.config),this.requestRender()}collapseAll(){this.expandedKeys=ei(),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=ti(this.rows,e,this.config,this.expandedKeys),this.requestRender()}}function ri(o,e,t){const n=[...o.undoStack,e];for(;n.length>t;)n.shift();return{undoStack:n,redoStack:[]}}function kt(o){if(o.undoStack.length===0)return{newState:o,action:null};const e=[...o.undoStack],t=e.pop();return t?{newState:{undoStack:e,redoStack:[...o.redoStack,t]},action:t}:{newState:o,action:null}}function Tt(o){if(o.redoStack.length===0)return{newState:o,action:null};const e=[...o.redoStack],t=e.pop();return t?{newState:{undoStack:[...o.undoStack,t],redoStack:e},action:t}:{newState:o,action:null}}function si(o){return o.undoStack.length>0}function li(o){return o.redoStack.length>0}function ai(){return{undoStack:[],redoStack:[]}}function ci(o,e,t,n){return{type:"cell-edit",rowIndex:o,field:e,oldValue:t,newValue:n,timestamp:Date.now()}}class di extends L{name="undoRedo";version="1.0.0";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];detach(){this.undoStack=[],this.redoStack=[]}onKeyDown(e){const t=(e.ctrlKey||e.metaKey)&&e.key==="z"&&!e.shiftKey,n=(e.ctrlKey||e.metaKey)&&(e.key==="y"||e.key==="z"&&e.shiftKey);if(t){const i=kt({undoStack:this.undoStack,redoStack:this.redoStack});if(i.action){const r=this.rows;r[i.action.rowIndex]&&(r[i.action.rowIndex][i.action.field]=i.action.oldValue),this.undoStack=i.newState.undoStack,this.redoStack=i.newState.redoStack,this.emit("undo",{action:i.action,type:"undo"}),this.requestRender()}return!0}if(n){const i=Tt({undoStack:this.undoStack,redoStack:this.redoStack});if(i.action){const r=this.rows;r[i.action.rowIndex]&&(r[i.action.rowIndex][i.action.field]=i.action.newValue),this.undoStack=i.newState.undoStack,this.redoStack=i.newState.redoStack,this.emit("redo",{action:i.action,type:"redo"}),this.requestRender()}return!0}return!1}recordEdit(e,t,n,i){const r=ci(e,t,n,i),s=ri({undoStack:this.undoStack,redoStack:this.redoStack},r,this.config.maxHistorySize??100);this.undoStack=s.undoStack,this.redoStack=s.redoStack}undo(){const e=kt({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=Tt({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 si({undoStack:this.undoStack,redoStack:this.redoStack})}canRedo(){return li({undoStack:this.undoStack,redoStack:this.redoStack})}clearHistory(){const e=ai();this.undoStack=e.undoStack,this.redoStack=e.redoStack}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}}const ui='.tbw-visibility-content{display:flex;flex-direction:column;height:100%}.tbw-visibility-list{flex:1;overflow-y:auto;padding:8px}.tbw-visibility-row{display:flex;align-items:center;gap:8px;padding:6px 4px;cursor:pointer;font-size:13px;border-radius:var(--tbw-border-radius, 4px);position:relative}.tbw-visibility-row:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover, #f3f4f6))}.tbw-visibility-row input[type=checkbox]{cursor:pointer}.tbw-visibility-row.locked span{color:var(--tbw-color-fg-muted, #888)}.tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted, #888);font-size:10px;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, #1f2937)}.tbw-visibility-label{display:flex;align-items:center;gap:8px;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-reorder-indicator, var(--tbw-color-accent, #3b82f6))}.tbw-visibility-row.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent, #3b82f6))}.tbw-visibility-show-all{margin:8px;padding:8px 12px;border:1px solid var(--tbw-visibility-border, var(--tbw-color-border, #e5e7eb));border-radius:var(--tbw-border-radius, 4px);background:var(--tbw-visibility-btn-bg, var(--tbw-color-header-bg, #f9fafb));color:var(--tbw-color-fg, #1f2937);cursor:pointer;font-size:13px}.tbw-visibility-show-all:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover, #f3f4f6))}';function Lt(o){const e=o.meta??{};return e.lockPosition!==!0&&e.suppressMovable!==!0}class Z extends L{name="visibility";version="1.0.0";static PANEL_ID="columns";get defaultConfig(){return{allowHideAll:!1}}columnListElement=null;isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;detach(){this.columnListElement=null,this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}getToolPanel(){return{id:Z.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(Z.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.toggleToolPanel(Z.PANEL_ID)}isColumnVisible(e){return this.grid.isColumnVisible(e)}setColumnVisible(e,t){this.grid.setColumnVisible(e,t)}getVisibleColumns(){return this.grid.getAllColumns().filter(t=>t.visible).map(t=>t.field)}getHiddenColumns(){return this.grid.getAllColumns().filter(t=>!t.visible).map(t=>t.field)}showAll(){this.grid.showAllColumns()}toggleColumn(e){this.grid.toggleColumnVisibility(e)}showColumn(e){this.grid.setColumnVisible(e,!0)}hideColumn(e){this.grid.setColumnVisible(e,!1)}getAllColumns(){return this.grid.getAllColumns()}isPanelVisible(){return this.grid.activeToolPanel===Z.PANEL_ID}renderPanelContent(e){const t=this.grid,n=document.createElement("div");n.className="tbw-visibility-content";const i=document.createElement("div");i.className="tbw-visibility-list",n.appendChild(i);const r=document.createElement("button");return r.className="tbw-visibility-show-all",r.textContent="Show All",r.addEventListener("click",()=>{t.showAllColumns(),this.rebuildToggles(i)}),n.appendChild(r),this.columnListElement=i,this.rebuildToggles(i),e.appendChild(n),()=>{this.columnListElement=null,n.remove()}}hasReorderPlugin(){const e=this.grid?.getPluginByName?.("reorder");return!!(e&&typeof e.moveColumn=="function")}rebuildToggles(e){const t=this.grid,n=this.hasReorderPlugin();e.innerHTML="";const i=t.getAllColumns();for(let r=0;r<i.length;r++){const s=i[r],l=s.header||s.field,a=document.createElement("div");a.className=s.lockVisible?"tbw-visibility-row locked":"tbw-visibility-row",a.setAttribute("data-field",s.field),a.setAttribute("data-index",String(r)),n&&Lt(s)&&(a.draggable=!0,a.classList.add("reorderable"),this.setupDragListeners(a,s.field,r,e));const c=document.createElement("label");c.className="tbw-visibility-label";const d=document.createElement("input");d.type="checkbox",d.checked=s.visible,d.disabled=s.lockVisible??!1,d.addEventListener("change",()=>{t.toggleColumnVisibility(s.field),setTimeout(()=>this.rebuildToggles(e),0)});const u=document.createElement("span");if(u.textContent=l,c.appendChild(d),c.appendChild(u),n&&Lt(s)){const f=document.createElement("span");f.className="tbw-visibility-handle",this.setIcon(f,this.resolveIcon("dragHandle")),f.title="Drag to reorder",a.appendChild(f)}a.appendChild(c),e.appendChild(a)}}setupDragListeners(e,t,n,i){e.addEventListener("dragstart",r=>{this.isDragging=!0,this.draggedField=t,this.draggedIndex=n,r.dataTransfer&&(r.dataTransfer.effectAllowed="move",r.dataTransfer.setData("text/plain",t)),e.classList.add("dragging")}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,i.querySelectorAll(".tbw-visibility-row").forEach(r=>{r.classList.remove("dragging","drop-target","drop-before","drop-after")})}),e.addEventListener("dragover",r=>{if(r.preventDefault(),!this.isDragging||this.draggedField===t)return;const s=e.getBoundingClientRect(),l=s.top+s.height/2;this.dropIndex=r.clientY<l?n:n+1,i.querySelectorAll(".tbw-visibility-row").forEach(a=>{a!==e&&a.classList.remove("drop-target","drop-before","drop-after")}),e.classList.add("drop-target"),e.classList.toggle("drop-before",r.clientY<l),e.classList.toggle("drop-after",r.clientY>=l)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",r=>{r.preventDefault();const s=this.draggedField,l=this.draggedIndex,a=this.dropIndex;if(!this.isDragging||s===null||l===null||a===null)return;const c=a>l?a-1:a;if(c!==l){const d={field:s,fromIndex:l,toIndex:c};this.emit("column-reorder-request",d),setTimeout(()=>{this.rebuildToggles(i)},0)}})}styles=ui}C.BaseGridPlugin=L,C.ClipboardPlugin=Ro,C.ColumnVirtualizationPlugin=ko,C.ContextMenuPlugin=Po,C.DEFAULT_ANIMATION_CONFIG=Ne,C.DEFAULT_GRID_ICONS=I,C.DGEvents=bo,C.DataGridElement=V,C.ExportPlugin=Do,C.FilteringPlugin=q,C.FitModeEnum=$,C.GridCSSVars=wo,C.GridClasses=M,C.GridDataAttrs=te,C.GridElement=V,C.GridSelectors=go,C.GroupingColumnsPlugin=Xo,C.GroupingRowsPlugin=on,C.MasterDetailPlugin=cn,C.MultiSortPlugin=pn,C.PLUGIN_QUERIES=ee,C.PinnedColumnsPlugin=bn,C.PinnedRowsPlugin=Cn,C.PivotPlugin=Y,C.PluginEvents=mo,C.PluginManager=Ze,C.ReorderPlugin=Bn,C.SelectionPlugin=jn,C.ServerSidePlugin=Qn,C.TreePlugin=ii,C.UndoRedoPlugin=di,C.VisibilityPlugin=Z,C.aggregatorRegistry=N,C.builtInSort=Ve,C.defaultComparator=Ke,C.getAggregator=ge,C.getValueAggregator=pe,C.listAggregators=xo,C.registerAggregator=yo,C.runAggregator=we,C.runValueAggregator=vo,C.unregisterAggregator=Co,Object.defineProperty(C,Symbol.toStringTag,{value:"Module"})}));
93
93
  //# sourceMappingURL=grid.all.umd.js.map