@toolbox-web/grid 1.16.0 → 1.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/all.js +12 -12
- package/all.js.map +1 -1
- package/index.js +11 -5
- package/index.js.map +1 -1
- package/lib/core/internal/event-delegation.d.ts.map +1 -1
- package/lib/plugins/clipboard/ClipboardPlugin.d.ts.map +1 -1
- package/lib/plugins/clipboard/copy.d.ts.map +1 -1
- package/lib/plugins/clipboard/index.js +55 -55
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/package.json +1 -1
- package/umd/grid.all.umd.js +3 -3
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +1 -1
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/clipboard.umd.js +4 -4
- package/umd/plugins/clipboard.umd.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@toolbox-web/grid",
|
|
3
|
-
"version": "1.16.
|
|
3
|
+
"version": "1.16.1",
|
|
4
4
|
"description": "Zero-dependency, framework-agnostic data grid web component with virtualization, sorting, filtering, editing, and 20+ plugins. Works in vanilla JS, React, Vue, Angular, and any framework.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
package/umd/grid.all.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(S,de){typeof exports=="object"&&typeof module<"u"?de(exports):typeof define=="function"&&define.amd?define(["exports"],de):(S=typeof globalThis<"u"?globalThis:S||self,de(S.TbwGrid={}))})(this,(function(S){"use strict";function de(){return{rowCount:-1,colCount:-1,ariaLabel:void 0,ariaDescribedBy:void 0}}function Zi(r,e,t,i,n){if(i===r.rowCount&&n===r.colCount)return!1;const o=r.rowCount;return r.rowCount=i,r.colCount=n,e&&(e.setAttribute("aria-rowcount",String(i)),e.setAttribute("aria-colcount",String(n))),i!==o&&t&&(i>0?t.setAttribute("role","rowgroup"):t.removeAttribute("role")),!0}function Ji(r,e){const t=r?.gridAriaLabel;return t||(r?.shell?.header?.title??e?.lightDomTitle??void 0)}function en(r,e,t,i){if(!e)return!1;let n=!1;const o=Ji(t,i);o!==r.ariaLabel&&(r.ariaLabel=o,o?e.setAttribute("aria-label",o):e.removeAttribute("aria-label"),n=!0);const s=t?.gridAriaDescribedBy;return s!==r.ariaDescribedBy&&(r.ariaDescribedBy=s,s?e.setAttribute("aria-describedby",s):e.removeAttribute("aria-describedby"),n=!0),n}const ne={STRETCH:"stretch",FIXED:"fixed"},vt={mode:"reduced-motion",duration:200,easing:"ease-out"},yt='<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>',W={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:yt,filterActive:yt,print:"🖨️"};function tn(r){return Array.from(r.querySelectorAll("tbw-grid-column")).map(t=>{const i=t.getAttribute("field")||"";if(!i)return null;const n=t.getAttribute("type")||void 0,s=n&&new Set(["number","string","date","boolean","select"]).has(n)?n:void 0,l=t.getAttribute("header")||void 0,a=t.hasAttribute("sortable"),c=t.hasAttribute("editable"),d={field:i,type:s,header:l,sortable:a,editable:c},u=t.getAttribute("width");if(u){const y=parseFloat(u);!isNaN(y)&&/^\d+(\.\d+)?$/.test(u.trim())?d.width=y:d.width=u}const h=t.getAttribute("minWidth")||t.getAttribute("min-width");if(h){const y=parseFloat(h);isNaN(y)||(d.minWidth=y)}t.hasAttribute("resizable")&&(d.resizable=!0),t.hasAttribute("sizable")&&(d.resizable=!0);const p=t.getAttribute("editor"),f=t.getAttribute("renderer");p&&(d.__editorName=p),f&&(d.__rendererName=f);const g=t.getAttribute("options");g&&(d.options=g.split(",").map(y=>{const[x,H]=y.includes(":")?y.split(":"):[y.trim(),y.trim()];return{value:x.trim(),label:H?.trim()||x.trim()}}));const w=t.querySelector("tbw-grid-column-view"),b=t.querySelector("tbw-grid-column-editor"),v=t.querySelector("tbw-grid-column-header");w&&(d.__viewTemplate=w),b&&(d.__editorTemplate=b),v&&(d.__headerTemplate=v);const L=globalThis.DataGridElement?.getAdapters?.()??[],_=w??t,C=L.find(y=>y.canHandle(_));if(C){const y=C.createRenderer(_);y&&(d.viewRenderer=y)}const m=b??t,R=L.find(y=>y.canHandle(m));if(R){const y=R.createEditor(m);y&&(d.editor=y)}return d}).filter(t=>!!t)}function Ct(r,e){if((!r||!r.length)&&(!e||!e.length))return[];if(!r||!r.length)return e||[];if(!e||!e.length)return r;const t={};e.forEach(n=>{const o=t[n.field];if(o){n.header&&!o.header&&(o.header=n.header),n.type&&!o.type&&(o.type=n.type),n.sortable&&(o.sortable=!0),n.editable&&(o.editable=!0),n.resizable&&(o.resizable=!0),n.width!=null&&o.width==null&&(o.width=n.width),n.minWidth!=null&&o.minWidth==null&&(o.minWidth=n.minWidth),n.__viewTemplate&&(o.__viewTemplate=n.__viewTemplate),n.__editorTemplate&&(o.__editorTemplate=n.__editorTemplate),n.__headerTemplate&&(o.__headerTemplate=n.__headerTemplate);const s=n.renderer||n.viewRenderer,l=o.renderer||o.viewRenderer;s&&!l&&(o.viewRenderer=s,n.renderer&&(o.renderer=s)),n.editor&&!o.editor&&(o.editor=n.editor)}else t[n.field]={...n}});const i=r.map(n=>{const o=t[n.field];if(!o)return n;const s={...n};o.header&&!s.header&&(s.header=o.header),o.type&&!s.type&&(s.type=o.type),s.sortable=n.sortable||o.sortable,(n.resizable===!0||o.resizable===!0)&&(s.resizable=!0),s.editable=n.editable||o.editable,o.width!=null&&s.width==null&&(s.width=o.width),o.minWidth!=null&&s.minWidth==null&&(s.minWidth=o.minWidth),o.__viewTemplate&&(s.__viewTemplate=o.__viewTemplate),o.__editorTemplate&&(s.__editorTemplate=o.__editorTemplate),o.__headerTemplate&&(s.__headerTemplate=o.__headerTemplate);const l=o.renderer||o.viewRenderer,a=s.renderer||s.viewRenderer;return l&&!a&&(s.viewRenderer=l,o.renderer&&(s.renderer=l)),o.editor&&!s.editor&&(s.editor=o.editor),delete t[n.field],s});return Object.keys(t).forEach(n=>i.push(t[n])),i}function xt(r,e){try{r.part?.add?.(e)}catch{}const t=r.getAttribute("part");t?t.split(/\s+/).includes(e)||r.setAttribute("part",t+" "+e):r.setAttribute("part",e)}function Et(r){const e=r.effectiveConfig?.fitMode||r.fitMode||ne.STRETCH;if(e!==ne.STRETCH&&e!==ne.FIXED||r.__didInitialAutoSize||!r.isConnected)return;const t=Array.from(r._headerRowEl?.children||[]);if(!t.length)return;let i=!1;r._visibleColumns.forEach((n,o)=>{if(n.width)return;const s=t[o];let l=s?s.scrollWidth:0;for(const a of r._rowPool){const c=a.children[o];if(c){const d=c.scrollWidth;d>l&&(l=d)}}l>0&&(n.width=l+2,n.__autoSized=!0,i=!0)}),i&&ue(r),r.__didInitialAutoSize=!0}const nn=/^(?:\d+(?:\.\d+)?(?:px|%|fr|em|rem|ch|vw|vh|vmin|vmax)|calc\(.+\)|min-content|max-content|minmax\(.+\)|fit-content\(.+\)|auto)$/i;function Rt(r,e){return typeof r=="number"?`${r}px`:(nn.test(r)||console.warn(`[tbw-grid] Column '${e??"?"}' has an invalid CSS width value: '${r}'. Expected a number (px) or a valid CSS unit string (e.g. '30%', '2fr', 'calc(...)').`),r)}function ue(r){(r.effectiveConfig?.fitMode||r.fitMode||ne.STRETCH)===ne.STRETCH?r._gridTemplate=r._visibleColumns.map(t=>{if(t.width!=null)return Rt(t.width,t.field);const i=t.minWidth;return i!=null?`minmax(${i}px, 1fr)`:"1fr"}).join(" ").trim():r._gridTemplate=r._visibleColumns.map(t=>t.width!=null?Rt(t.width,t.field):"max-content").join(" "),r.style.setProperty("--tbw-column-template",r._gridTemplate)}function rn(r){return r==null?"string":typeof r=="number"?"number":typeof r=="boolean"?"boolean":r instanceof Date||typeof r=="string"&&/\d{4}-\d{2}-\d{2}/.test(r)&&!isNaN(Date.parse(r))?"date":"string"}function on(r,e){const t=r[0]||{},i=Object.keys(t).map(o=>{const s=t[o],l=rn(s);return{field:o,header:o.charAt(0).toUpperCase()+o.slice(1),type:l}}),n={};return i.forEach(o=>{n[o.field]=o.type||"string"}),{columns:i,typeMap:n}}const sn=/{{\s*([^}]+)\s*}}/g,q="__DG_EMPTY__",ln=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,an=/__(proto|defineGetter|defineSetter)|constructor|window|globalThis|global|process|Function|import|eval|Reflect|Proxy|Error|arguments|document|location|cookie|localStorage|sessionStorage|indexedDB|fetch|XMLHttpRequest|WebSocket|Worker|SharedWorker|ServiceWorker|opener|parent|top|frames|self|this\b/;function cn(r){return!r||typeof r!="string"?"":r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const dn=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"]),St=/^on\w+$/i,un=new Set(["href","src","action","formaction","data","srcdoc","xlink:href","poster","srcset"]),hn=/^\s*(javascript|vbscript|data|blob):/i;function X(r){if(!r||typeof r!="string")return"";if(r.indexOf("<")===-1)return r;const e=document.createElement("template");return e.innerHTML=r,fn(e.content),e.innerHTML}function fn(r){const e=[],t=r.querySelectorAll("*");for(const i of t){const n=i.tagName.toLowerCase();if(dn.has(n)){e.push(i);continue}if((n==="svg"||i.namespaceURI==="http://www.w3.org/2000/svg")&&Array.from(i.attributes).some(l=>St.test(l.name)||l.name==="href"||l.name==="xlink:href")){e.push(i);continue}const o=[];for(const s of i.attributes){const l=s.name.toLowerCase();if(St.test(l)){o.push(s.name);continue}if(un.has(l)&&hn.test(s.value)){o.push(s.name);continue}if(l==="style"&&/expression\s*\(|javascript:|behavior\s*:/i.test(s.value)){o.push(s.name);continue}}o.forEach(s=>i.removeAttribute(s))}e.forEach(i=>i.remove())}function xe(r,e){if(!r||r.indexOf("{{")===-1)return r;const t=[],i=r.replace(sn,(l,a)=>{const c=gn(a,e);return t.push({expr:a.trim(),result:c}),c}),n=pn(i),o=t.length&&t.every(l=>l.result===""||l.result===q);return J.test(r)||o?"":n}function gn(r,e){if(r=(r||"").trim(),!r||J.test(r))return q;if(r==="value")return e.value==null?q:String(e.value);if(r.startsWith("row.")&&!/[()?]/.test(r)&&!r.includes(":")){const i=r.slice(4),n=e.row?e.row[i]:void 0;return n==null?q:String(n)}if(r.length>80||!ln.test(r)||an.test(r))return q;const t=r.match(/\./g);if(t&&t.length>1)return q;try{const n=new Function("value","row",`return (${r});`)(e.value,e.row),o=n==null?"":String(n);return J.test(o)?q:o||q}catch{return q}}const J=/Reflect|Proxy|ownKeys/;function pn(r){return r&&r.replace(new RegExp(q,"g"),"").replace(/Reflect\.[^<>{}\s]+|\bProxy\b|ownKeys\([^)]*\)/g,"")}function wn(r){if(J.test(r.textContent||"")){for(const e of r.childNodes)e.nodeType===Node.TEXT_NODE&&J.test(e.textContent||"")&&(e.textContent="");J.test(r.textContent||"")&&(r.textContent="")}}function _t(r){const e=J.test(r),t=(i=>e?"":xe(r,i));return t.__blocked=e,t}const mn=100;class bn{#t;#e;#u;#c;#n;#l={};#i={};#f=!0;#w=[];#g;#a;#b;#d;#h;constructor(e){this.#d=e}get original(){return this.#l}get effective(){return this.#i}get columns(){return this.#i.columns??[]}set columns(e){this.#i.columns=e}get lightDomColumnsCache(){return this.#c}set lightDomColumnsCache(e){this.#c=e}get originalColumnNodes(){return this.#n}set originalColumnNodes(e){this.#n=e}get lightDomTitle(){return this.#h}set lightDomTitle(e){this.#h=e}get initialColumnState(){return this.#b}set initialColumnState(e){this.#b=e}get sourcesChanged(){return this.#f}markSourcesChanged(){this.#f=!0}setGridConfig(e){this.#t=e,this.#f=!0,this.#c=void 0}getGridConfig(){return this.#t}setColumns(e){this.#e=e,this.#f=!0}getColumns(){return this.#e}setFitMode(e){this.#u=e,this.#f=!0}getFitMode(){return this.#u}merge(){const e=(this.#i.columns?.length??0)>0;if(!this.#f&&e)return;const t=this.#S();this.#f=!1,this.#l=t,Object.freeze(this.#l),this.#l.columns&&Object.freeze(this.#l.columns),this.#i=this.#E(this.#l),this.#m()}#E(e){const t={...e};return e.columns&&(t.columns=e.columns.map(i=>({...i}))),e.shell&&(t.shell={...e.shell,header:e.shell.header?{...e.shell.header}:void 0,toolPanel:e.shell.toolPanel?{...e.shell.toolPanel}:void 0,toolPanels:e.shell.toolPanels?.map(i=>({...i})),headerContents:e.shell.headerContents?.map(i=>({...i}))}),t}#m(){const e=this.#i;this.#x(),typeof e.rowHeight=="number"&&e.rowHeight>0&&this.#d.setRowHeight(e.rowHeight),e.fitMode==="fixed"&&this.columns.forEach(i=>{i.width==null&&(i.width=80)}),this.#d.applyAnimationConfig(e)}#x(){const e=this.#i.typeDefaults;if(!e)return;const t=this.columns;for(const i of t){if(!i.type)continue;const n=e[i.type];n&&(!i.renderer&&!i.viewRenderer&&n.renderer&&(i.renderer=n.renderer),!i.format&&n.format&&(i.format=n.format),!i.editor&&n.editor&&(i.editor=n.editor),!i.editorParams&&n.editorParams&&(i.editorParams=n.editorParams))}}#S(){const e=this.#t?{...this.#t}:{},t=Array.isArray(e.columns)?[...e.columns]:[],i=(this.#c??[]).map(s=>({...s}));let n=Ct(t,i);this.#e&&this.#e.length&&(n=Ct(this.#e,i));const o=this.#d.getRows();return n.length===0&&o.length&&(n=on(o).columns),n.length&&(n.forEach(s=>{s.sortable===void 0&&(s.sortable=!0),s.resizable===void 0&&(s.resizable=!0),s.__originalWidth===void 0&&typeof s.width=="number"&&(s.__originalWidth=s.width)}),n.forEach(s=>{s.__viewTemplate&&!s.__compiledView&&(s.__compiledView=_t(s.__viewTemplate.innerHTML)),s.__editorTemplate&&!s.__compiledEditor&&(s.__compiledEditor=_t(s.__editorTemplate.innerHTML))}),e.columns=n),this.#u&&(e.fitMode=this.#u),e.fitMode||(e.fitMode="stretch"),this.#C(e),e.columnState&&!this.#b&&(this.#b=e.columnState),e}#C(e){e.shell=e.shell?{...e.shell}:{},e.shell.header=e.shell.header?{...e.shell.header}:{};const t=this.#d.getShellLightDomTitle();t&&(this.#h=t),this.#h&&!e.shell.header.title&&(e.shell.header.title=this.#h);const i=this.#d.getShellLightDomHeaderContent();i?.length>0&&(e.shell.header.lightDomContent=i),this.#d.getShellHasToolButtonsContainer()&&(e.shell.header.hasToolButtonsContainer=!0);const n=this.#d.getShellToolPanels();if(n.size>0){const u=Array.from(n.values());u.sort((h,p)=>(h.order??100)-(p.order??100)),e.shell.toolPanels=u}const o=this.#d.getShellHeaderContents();if(o.size>0){const u=Array.from(o.values());u.sort((h,p)=>(h.order??100)-(p.order??100)),e.shell.headerContents=u}const s=this.#d.getShellToolbarContents(),l=Array.from(s.values()),a=this.#t?.shell?.header?.toolbarContents??[],c=new Set(a.map(u=>u.id)),d=[...a];for(const u of l)c.has(u.id)||d.push(u);d.sort((u,h)=>(u.order??0)-(h.order??0)),e.shell.header.toolbarContents=d}collectState(e){const t=this.columns,i=this.#p();return{columns:t.map((n,o)=>{const s={field:n.field,order:o,visible:!n.hidden},l=n;l.__renderedWidth!==void 0?s.width=l.__renderedWidth:n.width!==void 0&&(s.width=typeof n.width=="string"?parseFloat(n.width):n.width);const a=i.get(n.field);a&&(s.sort=a);for(const c of e)if(c.getColumnState){const d=c.getColumnState(n.field);d&&Object.assign(s,d)}return s})}}applyState(e,t){if(!e.columns||e.columns.length===0)return;const i=this.columns,n=new Map(e.columns.map(l=>[l.field,l])),o=i.map(l=>{const a=n.get(l.field);if(!a)return l;const c={...l};return a.width!==void 0&&(c.width=a.width,c.__renderedWidth=a.width),a.visible!==void 0&&(c.hidden=!a.visible),c});o.sort((l,a)=>{const c=n.get(l.field)?.order??1/0,d=n.get(a.field)?.order??1/0;return c-d}),this.columns=o;const s=e.columns.filter(l=>l.sort!==void 0).sort((l,a)=>(l.sort?.priority??0)-(a.sort?.priority??0));if(s.length>0){const l=s[0];l.sort&&this.#d.setSortState({field:l.field,direction:l.sort.direction==="asc"?1:-1})}else this.#d.setSortState(null);for(const l of t)if(l.applyColumnState)for(const a of e.columns)l.applyColumnState(a.field,a)}resetState(e){this.#b=void 0,this.#d.setSortState(null),this.#i=this.#E(this.#l),this.#m();for(const t of e)if(t.applyColumnState)for(const i of this.columns)t.applyColumnState(i.field,{field:i.field,order:0,visible:!0});this.requestStateChange(e)}#p(){const e=new Map,t=this.#d.getSortState();return t&&e.set(t.field,{direction:t.direction===1?"asc":"desc",priority:0}),e}requestStateChange(e){this.#a&&clearTimeout(this.#a),this.#a=setTimeout(()=>{this.#a=void 0;const t=this.collectState(e);this.#d.emit("column-state-change",t)},mn)}setColumnVisible(e,t){const i=this.columns,n=i.find(s=>s.field===e);return!n||!t&&n.lockVisible||!t&&i.filter(l=>!l.hidden&&l.field!==e).length===0||!!n.hidden===!t?!1:(n.hidden=!t,this.#d.emit("column-visibility",{field:e,visible:t,visibleColumns:i.filter(s=>!s.hidden).map(s=>s.field)}),this.#d.clearRowPool(),this.#d.setup(),!0)}toggleColumnVisibility(e){const t=this.columns.find(i=>i.field===e);return t?this.setColumnVisible(e,!!t.hidden):!1}isColumnVisible(e){const t=this.columns.find(i=>i.field===e);return t?!t.hidden:!1}showAllColumns(){const e=this.columns;e.some(t=>t.hidden)&&(e.forEach(t=>t.hidden=!1),this.#d.emit("column-visibility",{visibleColumns:e.map(t=>t.field)}),this.#d.clearRowPool(),this.#d.setup())}getAllColumns(){return this.columns.map(e=>({field:e.field,header:e.header||e.field,visible:!e.hidden,lockVisible:e.lockVisible,utility:e.meta?.utility===!0}))}getColumnOrder(){return this.columns.map(e=>e.field)}setColumnOrder(e){if(!e.length)return;const t=new Map(this.columns.map(n=>[n.field,n])),i=[];for(const n of e){const o=t.get(n);o&&(i.push(o),t.delete(n))}for(const n of t.values())i.push(n);this.columns=i,this.#d.renderHeader(),this.#d.updateTemplate(),this.#d.refreshVirtualWindow()}parseLightDomColumns(e){this.#c||(this.#n=Array.from(e.querySelectorAll("tbw-grid-column")),this.#c=this.#n.length?tn(e):[])}clearLightDomCache(){this.#c=void 0}#v=new Map;registerLightDomHandler(e,t){this.#v.set(e.toLowerCase(),t)}unregisterLightDomHandler(e){this.#v.delete(e.toLowerCase())}observeLightDOM(e){this.#g&&this.#g.disconnect();const t=new Set;let i=null;const n=()=>{i=null;for(const o of t)this.#v.get(o)?.();t.clear()};this.#g=new MutationObserver(o=>{for(const s of o){for(const l of s.addedNodes){if(l.nodeType!==Node.ELEMENT_NODE)continue;const c=l.tagName.toLowerCase();this.#v.has(c)&&t.add(c)}if(s.type==="attributes"&&s.target.nodeType===Node.ELEMENT_NODE){const a=s.target.tagName.toLowerCase();this.#v.has(a)&&t.add(a)}}t.size>0&&!i&&(i=setTimeout(n,0))}),this.#g.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["title","field","header","width","hidden","id","icon","tooltip","order"]})}onChange(e){this.#w.push(e)}notifyChange(){for(const e of this.#w)e()}dispose(){this.#g?.disconnect(),this.#w=[],this.#a&&clearTimeout(this.#a)}}function Oe(){if(typeof window<"u"&&window.location){const r=window.location.hostname;if(r==="localhost"||r==="127.0.0.1"||r==="::1")return!0}return typeof process<"u"&&process.env?.NODE_ENV!=="production"}function At(r){return`<span role="checkbox" aria-checked="${r}" aria-label="${r}">${r?"🗹":"☐"}</span>`}function kt(r){if(r==null||r==="")return"";if(r instanceof Date)return isNaN(r.getTime())?"":r.toLocaleDateString();if(typeof r=="number"||typeof r=="string"){const e=new Date(r);return isNaN(e.getTime())?"":e.toLocaleDateString()}return""}function Ee(r){if(!r)return-1;const e=r.getAttribute("data-row");if(e)return parseInt(e,10);const t=r.closest(".data-grid-row");if(!t)return-1;const i=t.parentElement;if(!i)return-1;const n=i.querySelectorAll(":scope > .data-grid-row");for(let o=0;o<n.length;o++)if(n[o]===t)return o;return-1}function vn(r){if(!r)return-1;const e=r.getAttribute("data-col");return e?parseInt(e,10):-1}function he(r){r&&r.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function fe(r){try{if(getComputedStyle(r).direction==="rtl")return"rtl"}catch{}try{if(r.closest?.("[dir]")?.getAttribute("dir")==="rtl")return"rtl"}catch{}return"ltr"}function Tt(r){return fe(r)==="rtl"}function yn(r,e){return r==="left"||r==="right"?r:e==="rtl"?r==="start"?"right":"left":r==="start"?"left":"right"}function Lt(r,e){const t=e.renderer||e.viewRenderer;if(t)return t;if(!e.type)return;const i=r.__frameworkAdapter;if(i?.getTypeDefault){const n=i.getTypeDefault(e.type);if(n?.renderer)return n.renderer}}function Pt(r,e){if(e.format)return e.format;if(!e.type)return;const t=r.__frameworkAdapter;if(t?.getTypeDefault){const i=t.getTypeDefault(e.type);if(i?.format)return i.format}}const K='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function Ne(r){return(r.__editingCellCount??0)>0}function qe(r){r.__editingCellCount=0,r.removeAttribute("data-has-editing"),r.querySelectorAll(".cell.editing").forEach(t=>t.classList.remove("editing"))}const Ht=document.createElement("template");Ht.innerHTML='<div class="cell" role="gridcell" part="cell"></div>';const It=document.createElement("template");It.innerHTML='<div class="data-grid-row" role="row" part="row"></div>';function Cn(){return Ht.content.firstElementChild.cloneNode(!0)}function xn(){return It.content.firstElementChild.cloneNode(!0)}function Re(r){r.__cellDisplayCache=void 0,r.__cellCacheEpoch=void 0,r.__hasSpecialColumns=void 0}function En(r,e,t,i,n){const o=Math.max(0,t-e),s=r._bodyEl,l=r._visibleColumns,a=l.length;let c=r.__cachedHeaderRowCount;for(c===void 0&&(c=r.querySelector(".header-group-row")?2:1,r.__cachedHeaderRowCount=c);r._rowPool.length<o;){const h=xn();r._rowPool.push(h)}if(r._rowPool.length>o){for(let h=o;h<r._rowPool.length;h++){const p=r._rowPool[h];p.parentNode===s&&p.remove()}r._rowPool.length=o}const d=n&&r.__hasRenderRowPlugins!==!1,u=r._hasAfterRowRenderHook?.()??!1;for(let h=0;h<o;h++){const p=e+h,f=r._rows[p],g=r._rowPool[h];if(g.setAttribute("aria-rowindex",String(p+c+1)),d&&n(f,g,p)){g.__epoch=i,g.__rowDataRef=f,g.parentNode!==s&&s.appendChild(g);continue}const w=g.__epoch,b=g.__rowDataRef;let v=g.children.length;v>a&&g.lastElementChild?.classList.contains("tbw-row-loading-overlay")&&v--;const L=w===i&&v===a,_=b!==f,C=!!r._isGridEditMode;let m=!1;if(L&&_){for(let k=0;k<a;k++)if(l[k].externalView&&!g.querySelector(`.cell[data-col="${k}"] [data-external-view]`)){m=!0;break}}if(!L||m){const k=Ne(g),E=C||r._activeEditRows===p;k&&!E?(g.__isCustomRow&&(g.className="data-grid-row",g.setAttribute("role","row"),g.__isCustomRow=!1),qe(g),ge(r,g,f,p),g.__epoch=i,g.__rowDataRef=f):k&&E?(Ge(r,g,f,p),g.__rowDataRef=f):(g.__isCustomRow&&(g.className="data-grid-row",g.setAttribute("role","row"),g.__isCustomRow=!1),ge(r,g,f,p),g.__epoch=i,g.__rowDataRef=f)}else if(_){const k=Ne(g),E=C||r._activeEditRows===p;k&&!E?(qe(g),ge(r,g,f,p),g.__epoch=i,g.__rowDataRef=f):(Ge(r,g,f,p),g.__rowDataRef=f)}else{const k=Ne(g),E=C||r._activeEditRows===p;k&&!E?(qe(g),ge(r,g,f,p),g.__epoch=i,g.__rowDataRef=f):Ge(r,g,f,p)}let R=!1;const y=r.changedRowIds;if(y&&y.length>0)try{const k=r.getRowId?.(f);k&&(R=y.includes(k))}catch{}const x=g.classList.contains("changed");R!==x&&g.classList.toggle("changed",R);const H=r.effectiveConfig?.rowClass;if(H){const k=g.getAttribute("data-dynamic-classes");k&&k.split(" ").forEach(E=>E&&g.classList.remove(E));try{const E=H(f);if(E&&E.length>0){const T=E.filter(D=>D&&typeof D=="string");T.forEach(D=>g.classList.add(D)),g.setAttribute("data-dynamic-classes",T.join(" "))}else g.removeAttribute("data-dynamic-classes")}catch(E){console.warn("[tbw-grid] rowClass callback error:",E),g.removeAttribute("data-dynamic-classes")}}u&&r._afterRowRender?.({row:f,rowIndex:p,rowElement:g}),g.parentNode!==s&&s.appendChild(g)}}function Ge(r,e,t,i){const n=e.children,o=r._visibleColumns,s=o.length,l=n.length,a=s<l?s:l,c=r._focusRow,d=r._focusCol,u=r._hasAfterCellRenderHook?.()??!1;let h=r.__hasSpecialColumns;if(h===void 0){h=!1;const f=r.__frameworkAdapter;for(let g=0;g<s;g++){const w=o[g];if(w.__viewTemplate||w.__compiledView||w.renderer||w.viewRenderer||w.externalView||w.format||w.type==="date"||w.type==="boolean"||w.type&&f?.getTypeDefault?.(w.type)?.renderer||w.type&&f?.getTypeDefault?.(w.type)?.format){h=!0;break}}r.__hasSpecialColumns=h}const p=String(i);if(!h){for(let f=0;f<a;f++){const g=n[f];if(g.classList.contains("editing"))continue;g.firstElementChild&&r.__frameworkAdapter?.releaseCell?.(g);const w=o[f],b=t[w.field];g.textContent=b==null?"":String(b),g.getAttribute("data-row")!==p&&g.setAttribute("data-row",p);const v=c===i&&d===f,A=g.classList.contains("cell-focus");v!==A&&(g.classList.toggle("cell-focus",v),g.setAttribute("aria-selected",String(v))),u&&r._afterCellRender?.({row:t,rowIndex:i,column:w,colIndex:f,value:b,cellElement:g,rowElement:e})}return}for(let f=0;f<a;f++)if(o[f].externalView&&!n[f].querySelector("[data-external-view]")){ge(r,e,t,i);return}for(let f=0;f<a;f++){const g=o[f],w=n[f];w.getAttribute("data-row")!==p&&w.setAttribute("data-row",p);const b=c===i&&d===f,v=w.classList.contains("cell-focus");b!==v&&(w.classList.toggle("cell-focus",b),w.setAttribute("aria-selected",String(b)));const A=g.cellClass;if(A){const R=w.getAttribute("data-dynamic-classes");R&&R.split(" ").forEach(y=>y&&w.classList.remove(y));try{const y=t[g.field],x=A(y,t,g);if(x&&x.length>0){const H=x.filter(k=>k&&typeof k=="string");H.forEach(k=>w.classList.add(k)),w.setAttribute("data-dynamic-classes",H.join(" "))}else w.removeAttribute("data-dynamic-classes")}catch(y){console.warn(`[tbw-grid] cellClass callback error for column '${g.field}':`,y),w.removeAttribute("data-dynamic-classes")}}if(w.classList.contains("editing"))continue;const L=Lt(r,g);if(L){const R=t[g.field],y=L({row:t,value:R,field:g.field,column:g,cellEl:w});typeof y=="string"?(r.__frameworkAdapter?.releaseCell?.(w),w.innerHTML=X(y)):y instanceof Node?y.parentElement!==w&&(r.__frameworkAdapter?.releaseCell?.(w),w.innerHTML="",w.appendChild(y)):y==null&&(r.__frameworkAdapter?.releaseCell?.(w),w.textContent=R==null?"":String(R)),u&&r._afterCellRender?.({row:t,rowIndex:i,column:g,colIndex:f,value:R,cellElement:w,rowElement:e});continue}if(g.__viewTemplate||g.__compiledView||g.externalView)continue;const _=t[g.field];let C;const m=Pt(r,g);if(m){try{const R=m(_,t);C=R==null?"":String(R)}catch(R){console.warn(`[tbw-grid] Format error in column '${g.field}':`,R),C=_==null?"":String(_)}w.textContent=C}else g.type==="date"?(C=kt(_),w.textContent=C):g.type==="boolean"?w.innerHTML=At(!!_):(C=_==null?"":String(_),w.textContent=C);u&&r._afterCellRender?.({row:t,rowIndex:i,column:g,colIndex:f,value:_,cellElement:w,rowElement:e})}}function ge(r,e,t,i){e.classList.remove("tbw-row-loading"),e.removeAttribute("aria-busy");const n=r.__frameworkAdapter;if(n?.releaseCell){const h=e.children;for(let p=h.length-1;p>=0;p--)n.releaseCell(h[p])}e.innerHTML="";const o=r._visibleColumns,s=o.length,l=r._focusRow,a=r._focusCol,c=r,d=r._hasAfterCellRenderHook?.()??!1,u=document.createDocumentFragment();for(let h=0;h<s;h++){const p=o[h],f=Cn();f.setAttribute("aria-colindex",String(h+1)),f.setAttribute("data-col",String(h)),f.setAttribute("data-row",String(i)),f.setAttribute("data-field",p.field),f.setAttribute("data-header",p.header??p.field),p.type&&f.setAttribute("data-type",p.type);let g=t[p.field];const w=Pt(r,p);if(w)try{g=w(g,t)}catch(m){console.warn(`[tbw-grid] Format error in column '${p.field}':`,m)}const b=p.__compiledView,v=p.__viewTemplate,A=Lt(r,p),L=p.externalView;let _=!1;if(A){const m=A({row:t,value:g,field:p.field,column:p,cellEl:f});typeof m=="string"?(f.innerHTML=X(m),_=!0):m instanceof Node?m.parentElement!==f&&(f.textContent="",f.appendChild(m)):m==null&&(f.textContent=g==null?"":String(g))}else if(L){const m=L,R=document.createElement("div");R.setAttribute("data-external-view",""),R.setAttribute("data-field",p.field),f.appendChild(R);const y={row:t,value:g,field:p.field,column:p};if(m.mount)try{m.mount({placeholder:R,context:y,spec:m})}catch(x){console.warn(`[tbw-grid] External view mount error for column '${p.field}':`,x)}else queueMicrotask(()=>{try{c.dispatchEvent(new CustomEvent("mount-external-view",{bubbles:!0,composed:!0,detail:{placeholder:R,spec:m,context:y}}))}catch(x){console.warn(`[tbw-grid] External view event dispatch error for column '${p.field}':`,x)}});R.setAttribute("data-mounted","")}else if(b){const m=b({row:t,value:g,field:p.field,column:p}),R=b.__blocked;f.innerHTML=R?"":X(m),_=!0,R&&(f.textContent="",f.setAttribute("data-blocked-template",""))}else if(v){const m=v.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(m)?(f.textContent="",f.setAttribute("data-blocked-template","")):(f.innerHTML=X(xe(m,{row:t,value:g})),_=!0)}else w?f.textContent=g==null?"":String(g):p.type==="date"?f.textContent=kt(g):p.type==="boolean"?f.innerHTML=At(!!g):f.textContent=g==null?"":String(g);if(_){wn(f);const m=f.textContent||"";/Proxy|Reflect\.ownKeys/.test(m)&&(f.textContent=m.replace(/Proxy|Reflect\.ownKeys/g,"").trim(),/Proxy|Reflect\.ownKeys/.test(f.textContent||"")&&(f.textContent=""))}f.hasAttribute("data-blocked-template")&&(f.textContent||"").trim().length&&(f.textContent=""),p.editable?f.tabIndex=0:p.type==="boolean"&&(f.hasAttribute("tabindex")||(f.tabIndex=0)),l===i&&a===h?(f.classList.add("cell-focus"),f.setAttribute("aria-selected","true")):f.setAttribute("aria-selected","false");const C=p.cellClass;if(C)try{const m=t[p.field],R=C(m,t,p);if(R&&R.length>0){const y=R.filter(x=>x&&typeof x=="string");y.forEach(x=>f.classList.add(x)),f.setAttribute("data-dynamic-classes",y.join(" "))}}catch(m){console.warn(`[tbw-grid] cellClass callback error for column '${p.field}':`,m)}d&&r._afterCellRender?.({row:t,rowIndex:i,column:p,colIndex:h,value:g,cellElement:f,rowElement:e}),u.appendChild(f)}e.appendChild(u)}function Dt(r,e,t){if(e.target?.closest(".resize-handle"))return;const i=t.querySelector(".cell[data-row]"),n=Ee(i);if(n<0)return;const o=r._rows[n];if(!o||r._dispatchRowClick?.(e,n,o,t))return;const s=e.target?.closest(".cell[data-col]");if(s){const l=Number(s.getAttribute("data-col"));if(!isNaN(l)){if(r._dispatchCellClick?.(e,n,l,s))return;const a=r._focusRow!==n||r._focusCol!==l;if(r._focusRow=n,r._focusCol=l,s.classList.contains("editing")){a&&(he(r._bodyEl??r),s.classList.add("cell-focus"));const c=s.querySelector(K);try{c?.focus({preventScroll:!0})}catch{}return}F(r)}}}function Rn(r,e){if(r._dispatchKeyDown?.(e))return;const t=r._rows.length-1,i=r._visibleColumns.length-1,n=r._activeEditRows!==void 0&&r._activeEditRows!==-1,s=r._visibleColumns[r._focusCol]?.type,l=e.composedPath?.()??[],a=l.length?l[0]:e.target,c=d=>{if(!d)return!1;const u=d.tagName;return!!(u==="INPUT"||u==="SELECT"||u==="TEXTAREA"||d.isContentEditable)};if(!(c(a)&&(e.key==="Home"||e.key==="End"))&&!(c(a)&&(e.key==="ArrowUp"||e.key==="ArrowDown")&&a.tagName==="INPUT"&&a.type==="number")&&!(c(a)&&(e.key==="ArrowLeft"||e.key==="ArrowRight"))&&!(c(a)&&(e.key==="Enter"||e.key==="Escape"))&&!(n&&s==="select"&&(e.key==="ArrowDown"||e.key==="ArrowUp"))){switch(e.key){case"Tab":{e.preventDefault(),!e.shiftKey?r._focusCol<i?r._focusCol+=1:(typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow<t&&(r._focusRow+=1,r._focusCol=0)):r._focusCol>0?r._focusCol-=1:r._focusRow>0&&(typeof r.commitActiveRowEdit=="function"&&r._activeEditRows===r._focusRow&&r.commitActiveRowEdit(),r._focusRow-=1,r._focusCol=i),F(r);return}case"ArrowDown":n&&typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow=Math.min(t,r._focusRow+1),e.preventDefault();break;case"ArrowUp":n&&typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow=Math.max(0,r._focusRow-1),e.preventDefault();break;case"ArrowRight":{Tt(r)?r._focusCol=Math.max(0,r._focusCol-1):r._focusCol=Math.min(i,r._focusCol+1),e.preventDefault();break}case"ArrowLeft":{Tt(r)?r._focusCol=Math.min(i,r._focusCol+1):r._focusCol=Math.max(0,r._focusCol-1),e.preventDefault();break}case"Home":(e.ctrlKey||e.metaKey)&&(n&&typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow=0),r._focusCol=0,e.preventDefault(),F(r,{forceScrollLeft:!0});return;case"End":(e.ctrlKey||e.metaKey)&&(n&&typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow=t),r._focusCol=i,e.preventDefault(),F(r,{forceScrollRight:!0});return;case"PageDown":r._focusRow=Math.min(t,r._focusRow+20),e.preventDefault();break;case"PageUp":r._focusRow=Math.max(0,r._focusRow-20),e.preventDefault();break;case"Enter":{const d=r._focusRow,u=r._focusCol,h=r._visibleColumns[u],p=r._rows[d],f=h?.field??"",g=f&&p?p[f]:void 0,w=r.querySelector(`[data-row="${d}"][data-col="${u}"]`),b={rowIndex:d,colIndex:u,field:f,value:g,row:p,cellEl:w,trigger:"keyboard",originalEvent:e},v=new CustomEvent("cell-activate",{cancelable:!0,detail:b});r.dispatchEvent(v);const A=new CustomEvent("activate-cell",{cancelable:!0,detail:{row:d,col:u}});if(r.dispatchEvent(A),v.defaultPrevented||A.defaultPrevented){e.preventDefault();return}break}default:return}F(r)}}function F(r,e){if(r._virtualization?.enabled){const{rowHeight:s,container:l,viewportEl:a}=r._virtualization,c=l,d=a?.clientHeight??c?.clientHeight??0;if(c&&d>0){const u=r._focusRow*s;u<c.scrollTop?c.scrollTop=u:u+s>c.scrollTop+d&&(c.scrollTop=u-d+s)}}const t=r._activeEditRows!==void 0&&r._activeEditRows!==-1;t||r.refreshVirtualWindow(!1),he(r._bodyEl),Array.from(r._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(s=>{s.setAttribute("aria-selected","false")});const i=r._focusRow,n=r._virtualization.start??0,o=r._virtualization.end??r._rows.length;if(i>=n&&i<o){const s=r._bodyEl.querySelectorAll(".data-grid-row")[i-n];let l=s?.children[r._focusCol];if((!l||!l.classList?.contains("cell"))&&(l=s?.querySelector(`.cell[data-col="${r._focusCol}"]`)??s?.querySelector(".cell[data-col]")),l){l.classList.add("cell-focus"),l.setAttribute("aria-selected","true");const a=r.querySelector(".tbw-scroll-area");if(a&&l&&(!t||e?.forceHorizontalScroll))if(e?.forceScrollLeft)a.scrollLeft=0;else if(e?.forceScrollRight)a.scrollLeft=a.scrollWidth-a.clientWidth;else{const c=r._getHorizontalScrollOffsets?.(s??void 0,l)??{left:0,right:0};if(!c.skipScroll){const d=l.getBoundingClientRect(),u=a.getBoundingClientRect(),h=d.left-u.left+a.scrollLeft,p=h+d.width,f=a.scrollLeft+c.left,g=a.scrollLeft+a.clientWidth-c.right;h<f?a.scrollLeft=h-c.left:p>g&&(a.scrollLeft=p-a.clientWidth+c.right)}}if(r._activeEditRows!==void 0&&r._activeEditRows!==-1&&l.classList.contains("editing")){const c=l.querySelector(K);if(c&&document.activeElement!==c)try{c.focus({preventScroll:!0})}catch{}}else if(!l.contains(document.activeElement)){l.hasAttribute("tabindex")||l.setAttribute("tabindex","-1");try{l.focus({preventScroll:!0})}catch{}}}}}const Se=new WeakMap;function Sn(r,e){const t=Ee(e),i=vn(e);t<0||i<0||(r._focusRow=t,r._focusCol=i,he(r._bodyEl),e.classList.add("cell-focus"),e.setAttribute("aria-selected","true"))}function Be(r,e,t,i){let n=null;const o=t.composedPath?.();if(o&&o.length>0?n=o[0]:n=t.target,n&&!e.contains(n)){const g=document.elementFromPoint(t.clientX,t.clientY);g&&(n=g)}const s=n?.closest?.("[data-col]"),l=n?.closest?.(".data-grid-row"),a=n?.closest?.(".header-row");let c,d,u,h,p,f;return s&&(c=parseInt(s.getAttribute("data-row")??"-1",10),d=parseInt(s.getAttribute("data-col")??"-1",10),c>=0&&d>=0&&(u=r._rows[c],f=r._columns[d],h=f?.field,p=u&&h?u[h]:void 0)),{type:i,row:u,rowIndex:c!==void 0&&c>=0?c:void 0,colIndex:d!==void 0&&d>=0?d:void 0,field:h,value:p,column:f,originalEvent:t,cellElement:s??void 0,rowElement:l??void 0,isHeader:!!a,cell:c!==void 0&&d!==void 0&&c>=0&&d>=0?{row:c,col:d}:void 0}}function _n(r,e,t){const i=Be(r,e,t,"mousedown");(r._dispatchCellMouseDown?.(i)??!1)&&Se.set(r,!0)}function An(r,e,t){if(!Se.get(r))return;const i=Be(r,e,t,"mousemove");r._dispatchCellMouseMove?.(i)}function kn(r,e,t){if(!Se.get(r))return;const i=Be(r,e,t,"mouseup");r._dispatchCellMouseUp?.(i),Se.set(r,!1)}function Tn(r,e,t){e.addEventListener("mousedown",i=>{const n=i.target.closest(".cell[data-col]");n&&(n.classList.contains("editing")||Sn(r,n))},{signal:t}),e.addEventListener("click",i=>{const n=i.target.closest(".data-grid-row");n&&Dt(r,i,n)},{signal:t}),e.addEventListener("dblclick",i=>{const n=i.target.closest(".data-grid-row");n&&Dt(r,i,n)},{signal:t})}function Ln(r,e,t,i){e.addEventListener("keydown",n=>Rn(r,n),{signal:i}),t.addEventListener("mousedown",n=>_n(r,t,n),{signal:i}),document.addEventListener("mousemove",n=>An(r,t,n),{signal:i}),document.addEventListener("mouseup",n=>kn(r,t,n),{signal:i})}function Mt(r,e){return r==null&&e==null?0:r==null?-1:e==null||r>e?1:r<e?-1:0}function zt(r,e,t){const n=t.find(l=>l.field===e.field)?.sortComparator??Mt,{field:o,direction:s}=e;return[...r].sort((l,a)=>n(l[o],a[o],l,a)*s)}function Ft(r,e,t,i){r._rows=e,r.__rowRenderEpoch++,r._rowPool.forEach(n=>n.__epoch=-1),Le(r),r.refreshVirtualWindow(!0),r.dispatchEvent(new CustomEvent("sort-change",{detail:{field:t.field,direction:i}})),r.requestStateChange?.()}function Ot(r,e){!r._sortState||r._sortState.field!==e.field?(r._sortState||(r.__originalOrder=r._rows.slice()),Nt(r,e,1)):r._sortState.direction===1?Nt(r,e,-1):(r._sortState=null,r.__rowRenderEpoch++,r._rowPool.forEach(i=>i.__epoch=-1),r._rows=r.__originalOrder.slice(),Le(r),r._headerRowEl?.querySelectorAll('[role="columnheader"].sortable')?.forEach(i=>{i.getAttribute("aria-sort")?(i.getAttribute("aria-sort")==="ascending"||i.getAttribute("aria-sort")==="descending")&&(r._sortState||i.setAttribute("aria-sort","none")):i.setAttribute("aria-sort","none")}),r.refreshVirtualWindow(!0),r.dispatchEvent(new CustomEvent("sort-change",{detail:{field:e.field,direction:0}})),r.requestStateChange?.())}function Nt(r,e,t){r._sortState={field:e.field,direction:t};const i={field:e.field,direction:t},n=r._columns,s=(r.effectiveConfig?.sortHandler??zt)(r._rows,i,n);s&&typeof s.then=="function"?s.then(l=>{Ft(r,l,e,t)}):Ft(r,s,e,t)}function pe(r,e){return r.effectiveConfig?.sortable!==!1&&e.sortable===!0}function _e(r,e){return r.effectiveConfig?.resizable!==!1&&e.resizable!==!1}function Pn(r,e){typeof e=="string"?r.textContent=e:e instanceof HTMLElement&&(r.innerHTML="",r.appendChild(e.cloneNode(!0)))}function Ae(r,e){const t=document.createElement("span");xt(t,"sort-indicator");const i=r._sortState?.field===e.field?r._sortState.direction:0,n={...W,...r.icons},o=i===1?n.sortAsc:i===-1?n.sortDesc:n.sortNone;return Pn(t,o),t}function ke(r,e,t){const i=document.createElement("div");return i.className="resize-handle",i.setAttribute("aria-hidden","true"),i.addEventListener("mousedown",n=>{n.stopPropagation(),n.preventDefault(),r._resizeController.start(n,e,t)}),i.addEventListener("dblclick",n=>{n.stopPropagation(),n.preventDefault(),r._resizeController.resetColumn(e)}),i}function Te(r,e,t,i){i.classList.add("sortable"),i.tabIndex=0;const n=r._sortState?.field===e.field?r._sortState.direction:0;i.setAttribute("aria-sort",n===0?"none":n===1?"ascending":"descending"),i.addEventListener("click",o=>{r._resizeController?.isResizing||r._dispatchHeaderClick?.(o,t,i)||Ot(r,e)}),i.addEventListener("keydown",o=>{if(o.key==="Enter"||o.key===" "){if(o.preventDefault(),r._dispatchHeaderClick?.(o,t,i))return;Ot(r,e)}})}function Hn(r,e){if(e!=null)if(typeof e=="string"){const t=document.createElement("span");for(t.innerHTML=X(e);t.firstChild;)r.appendChild(t.firstChild)}else e instanceof Node&&r.appendChild(e)}function Le(r){r._headerRowEl=r.findHeaderRow();const e=r._headerRowEl;e&&(e.innerHTML="",r._visibleColumns.forEach((t,i)=>{const n=document.createElement("div");n.className="cell",xt(n,"header-cell"),n.setAttribute("role","columnheader"),n.setAttribute("aria-colindex",String(i+1)),n.setAttribute("data-field",t.field),n.setAttribute("data-col",String(i));const o=t.header??t.field,s=r._sortState?.field===t.field?r._sortState.direction:0,l=s===1?"asc":s===-1?"desc":null;if(t.headerRenderer){const a={column:t,value:o,sortState:l,filterActive:!1,cellEl:n,renderSortIcon:()=>pe(r,t)?Ae(r,t):null,renderFilterButton:()=>null},c=t.headerRenderer(a);Hn(n,c),pe(r,t)&&Te(r,t,i,n),_e(r,t)&&(n.classList.add("resizable"),n.appendChild(ke(r,i,n)))}else if(t.headerLabelRenderer){const a={column:t,value:o},c=t.headerLabelRenderer(a),d=document.createElement("span");c==null?d.textContent=o:typeof c=="string"?d.innerHTML=X(c):c instanceof Node&&d.appendChild(c),n.appendChild(d),pe(r,t)&&(Te(r,t,i,n),n.appendChild(Ae(r,t))),_e(r,t)&&(n.classList.add("resizable"),n.appendChild(ke(r,i,n)))}else if(t.__headerTemplate)Array.from(t.__headerTemplate.childNodes).forEach(a=>n.appendChild(a.cloneNode(!0))),pe(r,t)&&(Te(r,t,i,n),n.appendChild(Ae(r,t))),_e(r,t)&&(n.classList.add("resizable"),n.appendChild(ke(r,i,n)));else{const a=document.createElement("span");a.textContent=o,n.appendChild(a),pe(r,t)&&(Te(r,t,i,n),n.appendChild(Ae(r,t))),_e(r,t)&&(n.classList.add("resizable"),n.appendChild(ke(r,i,n)))}e.appendChild(n)}),e.querySelectorAll(".cell.sortable").forEach(t=>{t.getAttribute("aria-sort")||t.setAttribute("aria-sort","none")}),e.children.length>0?(e.setAttribute("role","row"),e.setAttribute("aria-rowindex","1")):(e.removeAttribute("role"),e.removeAttribute("aria-rowindex")))}const qt=typeof requestIdleCallback=="function";function In(r,e){return qt?requestIdleCallback(r,e):window.setTimeout(()=>{const t=Date.now();r({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})},1)}function Gt(r){qt?cancelIdleCallback(r):clearTimeout(r)}function Dn(r){const e=document.createElement("div");return e.className=`tbw-spinner tbw-spinner--${r}`,e.setAttribute("role","progressbar"),e.setAttribute("aria-label","Loading"),e}function Mn(r,e){if(e){const i=e({size:r});if(typeof i=="string"){const n=document.createElement("div");return n.innerHTML=i,n}return i}return Dn(r)}function zn(r){const e=document.createElement("div");return e.className="tbw-loading-overlay",e.setAttribute("role","status"),e.setAttribute("aria-live","polite"),e.appendChild(Mn("large",r)),e}function Fn(r,e){r.appendChild(e)}function On(r){r?.remove()}function Nn(r,e){if(e){if(r.classList.add("tbw-row-loading"),r.setAttribute("aria-busy","true"),!r.querySelector(".tbw-row-loading-overlay")){const t=document.createElement("div");t.className="tbw-row-loading-overlay",t.setAttribute("aria-hidden","true");const i=document.createElement("div");i.className="tbw-row-loading-spinner",t.appendChild(i),r.appendChild(t)}}else r.classList.remove("tbw-row-loading"),r.removeAttribute("aria-busy"),r.querySelector(".tbw-row-loading-overlay")?.remove()}function qn(r,e){e?(r.classList.add("tbw-cell-loading"),r.setAttribute("aria-busy","true")):(r.classList.remove("tbw-cell-loading"),r.removeAttribute("aria-busy"))}var z=(r=>(r[r.STYLE=1]="STYLE",r[r.VIRTUALIZATION=2]="VIRTUALIZATION",r[r.HEADER=3]="HEADER",r[r.ROWS=4]="ROWS",r[r.COLUMNS=5]="COLUMNS",r[r.FULL=6]="FULL",r))(z||{});class Gn{#t;#e=0;#u=0;#c=null;#n=null;#l=null;#i=!1;constructor(e){this.#t=e}requestPhase(e,t){e>this.#e&&(this.#e=e),this.#u===0&&(this.#f(),this.#u=requestAnimationFrame(()=>this.#w()))}whenReady(){return this.#c?this.#c:Promise.resolve()}setInitialReadyResolver(e){this.#l=e}cancel(){this.#u!==0&&(cancelAnimationFrame(this.#u),this.#u=0),this.#e=0,this.#n&&(this.#n(),this.#n=null,this.#c=null)}get isPending(){return this.#e!==0}get pendingPhase(){return this.#e}#f(){this.#c||(this.#c=new Promise(e=>{this.#n=e}))}#w(){if(this.#u=0,!this.#t.isConnected()){this.#e=0,this.#n&&(this.#n(),this.#n=null,this.#c=null);return}const e=this.#e;this.#e=0,e>=5&&this.#t.mergeConfig(),e>=4&&this.#t.processRows(),e>=5&&(this.#t.processColumns(),this.#t.updateTemplate()),e>=3&&this.#t.renderHeader(),e>=2&&this.#t.renderVirtualWindow(),e>=1&&this.#t.afterRender(),!this.#i&&this.#l&&(this.#i=!0,this.#l()),this.#n&&(this.#n(),this.#n=null,this.#c=null)}}function Bt(r){let e=null,t=null,i=null,n=null;const o=a=>{if(!e)return;const c=a.clientX-e.startX,d=Math.max(40,e.startWidth+c),u=r._visibleColumns[e.colIndex];u.width=d,u.__userResized=!0,u.__renderedWidth=d,t==null&&(t=requestAnimationFrame(()=>{t=null,r.updateTemplate?.()})),r.dispatchEvent(new CustomEvent("column-resize",{detail:{field:u.field,width:d}}))};let s=!1;const l=()=>{const a=e!==null;a&&(s=!0,requestAnimationFrame(()=>{s=!1})),window.removeEventListener("mousemove",o),window.removeEventListener("mouseup",l),i!==null&&(document.documentElement.style.cursor=i,i=null),n!==null&&(document.body.style.userSelect=n,n=null),e=null,a&&r.requestStateChange&&r.requestStateChange()};return{get isResizing(){return e!==null||s},start(a,c,d){a.preventDefault();const u=r._visibleColumns[c],h=typeof u?.width=="number"?u.width:void 0,p=u?.__renderedWidth??h??d.getBoundingClientRect().width;e={startX:a.clientX,colIndex:c,startWidth:p},window.addEventListener("mousemove",o),window.addEventListener("mouseup",l),i===null&&(i=document.documentElement.style.cursor),document.documentElement.style.cursor="e-resize",n===null&&(n=document.body.style.userSelect),document.body.style.userSelect="none"},resetColumn(a){const c=r._visibleColumns[a];c&&(c.__userResized=!1,c.__renderedWidth=void 0,c.width=c.__originalWidth,r.updateTemplate?.(),r.requestStateChange?.(),r.dispatchEvent(new CustomEvent("column-resize-reset",{detail:{field:c.field,width:c.width}})))},dispose(){l()}}}const $e="data-animating",Bn={change:"--tbw-row-change-duration",insert:"--tbw-row-insert-duration",remove:"--tbw-row-remove-duration"},$n={change:500,insert:300,remove:200};function Wn(r){const e=r.trim().toLowerCase();return e.endsWith("ms")?parseFloat(e):e.endsWith("s")?parseFloat(e)*1e3:parseFloat(e)}function Kn(r,e){const t=Bn[e],i=getComputedStyle(r).getPropertyValue(t);if(i){const n=Wn(i);if(!isNaN(n)&&n>0)return n}return $n[e]}function Vn(r,e,t){r.removeAttribute($e),r.offsetWidth,r.setAttribute($e,e);const i=Kn(r,e);setTimeout(()=>{e!=="remove"&&r.removeAttribute($e)},i)}function We(r,e,t){if(e<0)return!1;const i=r.findRenderedRowElement?.(e);return i?(Vn(i,t),!0):!1}function Un(r,e,t){let i=0;for(const n of e)We(r,n,t)&&i++;return i}function jn(r,e,t){const i=r._rows??[],n=r.getRowId;if(!n)return!1;const o=i.findIndex(s=>{if(s==null)return!1;try{return n(s)===e}catch{return!1}});return o<0?!1:We(r,o,t)}function Pe(r,e,t){const i=document.createElement(r);if(e)for(const n in e){const o=e[n];o!=null&&i.setAttribute(n,o)}return i}function N(r,e){const t=document.createElement("div");if(r&&(t.className=r),e)for(const i in e){const n=e[i];n!=null&&t.setAttribute(i,n)}return t}function $t(r,e,t){const i=document.createElement("button");if(r&&(i.className=r),e)for(const n in e){const o=e[n];o!=null&&i.setAttribute(n,o)}return i}const Wt=document.createElement("template");Wt.innerHTML=`
|
|
1
|
+
(function(S,de){typeof exports=="object"&&typeof module<"u"?de(exports):typeof define=="function"&&define.amd?define(["exports"],de):(S=typeof globalThis<"u"?globalThis:S||self,de(S.TbwGrid={}))})(this,(function(S){"use strict";function de(){return{rowCount:-1,colCount:-1,ariaLabel:void 0,ariaDescribedBy:void 0}}function Zi(r,e,t,i,n){if(i===r.rowCount&&n===r.colCount)return!1;const o=r.rowCount;return r.rowCount=i,r.colCount=n,e&&(e.setAttribute("aria-rowcount",String(i)),e.setAttribute("aria-colcount",String(n))),i!==o&&t&&(i>0?t.setAttribute("role","rowgroup"):t.removeAttribute("role")),!0}function Ji(r,e){const t=r?.gridAriaLabel;return t||(r?.shell?.header?.title??e?.lightDomTitle??void 0)}function en(r,e,t,i){if(!e)return!1;let n=!1;const o=Ji(t,i);o!==r.ariaLabel&&(r.ariaLabel=o,o?e.setAttribute("aria-label",o):e.removeAttribute("aria-label"),n=!0);const s=t?.gridAriaDescribedBy;return s!==r.ariaDescribedBy&&(r.ariaDescribedBy=s,s?e.setAttribute("aria-describedby",s):e.removeAttribute("aria-describedby"),n=!0),n}const ne={STRETCH:"stretch",FIXED:"fixed"},vt={mode:"reduced-motion",duration:200,easing:"ease-out"},yt='<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>',W={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:yt,filterActive:yt,print:"🖨️"};function tn(r){return Array.from(r.querySelectorAll("tbw-grid-column")).map(t=>{const i=t.getAttribute("field")||"";if(!i)return null;const n=t.getAttribute("type")||void 0,s=n&&new Set(["number","string","date","boolean","select"]).has(n)?n:void 0,l=t.getAttribute("header")||void 0,a=t.hasAttribute("sortable"),c=t.hasAttribute("editable"),d={field:i,type:s,header:l,sortable:a,editable:c},u=t.getAttribute("width");if(u){const y=parseFloat(u);!isNaN(y)&&/^\d+(\.\d+)?$/.test(u.trim())?d.width=y:d.width=u}const h=t.getAttribute("minWidth")||t.getAttribute("min-width");if(h){const y=parseFloat(h);isNaN(y)||(d.minWidth=y)}t.hasAttribute("resizable")&&(d.resizable=!0),t.hasAttribute("sizable")&&(d.resizable=!0);const p=t.getAttribute("editor"),f=t.getAttribute("renderer");p&&(d.__editorName=p),f&&(d.__rendererName=f);const g=t.getAttribute("options");g&&(d.options=g.split(",").map(y=>{const[x,H]=y.includes(":")?y.split(":"):[y.trim(),y.trim()];return{value:x.trim(),label:H?.trim()||x.trim()}}));const w=t.querySelector("tbw-grid-column-view"),b=t.querySelector("tbw-grid-column-editor"),v=t.querySelector("tbw-grid-column-header");w&&(d.__viewTemplate=w),b&&(d.__editorTemplate=b),v&&(d.__headerTemplate=v);const L=globalThis.DataGridElement?.getAdapters?.()??[],_=w??t,C=L.find(y=>y.canHandle(_));if(C){const y=C.createRenderer(_);y&&(d.viewRenderer=y)}const m=b??t,R=L.find(y=>y.canHandle(m));if(R){const y=R.createEditor(m);y&&(d.editor=y)}return d}).filter(t=>!!t)}function Ct(r,e){if((!r||!r.length)&&(!e||!e.length))return[];if(!r||!r.length)return e||[];if(!e||!e.length)return r;const t={};e.forEach(n=>{const o=t[n.field];if(o){n.header&&!o.header&&(o.header=n.header),n.type&&!o.type&&(o.type=n.type),n.sortable&&(o.sortable=!0),n.editable&&(o.editable=!0),n.resizable&&(o.resizable=!0),n.width!=null&&o.width==null&&(o.width=n.width),n.minWidth!=null&&o.minWidth==null&&(o.minWidth=n.minWidth),n.__viewTemplate&&(o.__viewTemplate=n.__viewTemplate),n.__editorTemplate&&(o.__editorTemplate=n.__editorTemplate),n.__headerTemplate&&(o.__headerTemplate=n.__headerTemplate);const s=n.renderer||n.viewRenderer,l=o.renderer||o.viewRenderer;s&&!l&&(o.viewRenderer=s,n.renderer&&(o.renderer=s)),n.editor&&!o.editor&&(o.editor=n.editor)}else t[n.field]={...n}});const i=r.map(n=>{const o=t[n.field];if(!o)return n;const s={...n};o.header&&!s.header&&(s.header=o.header),o.type&&!s.type&&(s.type=o.type),s.sortable=n.sortable||o.sortable,(n.resizable===!0||o.resizable===!0)&&(s.resizable=!0),s.editable=n.editable||o.editable,o.width!=null&&s.width==null&&(s.width=o.width),o.minWidth!=null&&s.minWidth==null&&(s.minWidth=o.minWidth),o.__viewTemplate&&(s.__viewTemplate=o.__viewTemplate),o.__editorTemplate&&(s.__editorTemplate=o.__editorTemplate),o.__headerTemplate&&(s.__headerTemplate=o.__headerTemplate);const l=o.renderer||o.viewRenderer,a=s.renderer||s.viewRenderer;return l&&!a&&(s.viewRenderer=l,o.renderer&&(s.renderer=l)),o.editor&&!s.editor&&(s.editor=o.editor),delete t[n.field],s});return Object.keys(t).forEach(n=>i.push(t[n])),i}function xt(r,e){try{r.part?.add?.(e)}catch{}const t=r.getAttribute("part");t?t.split(/\s+/).includes(e)||r.setAttribute("part",t+" "+e):r.setAttribute("part",e)}function Et(r){const e=r.effectiveConfig?.fitMode||r.fitMode||ne.STRETCH;if(e!==ne.STRETCH&&e!==ne.FIXED||r.__didInitialAutoSize||!r.isConnected)return;const t=Array.from(r._headerRowEl?.children||[]);if(!t.length)return;let i=!1;r._visibleColumns.forEach((n,o)=>{if(n.width)return;const s=t[o];let l=s?s.scrollWidth:0;for(const a of r._rowPool){const c=a.children[o];if(c){const d=c.scrollWidth;d>l&&(l=d)}}l>0&&(n.width=l+2,n.__autoSized=!0,i=!0)}),i&&ue(r),r.__didInitialAutoSize=!0}const nn=/^(?:\d+(?:\.\d+)?(?:px|%|fr|em|rem|ch|vw|vh|vmin|vmax)|calc\(.+\)|min-content|max-content|minmax\(.+\)|fit-content\(.+\)|auto)$/i;function Rt(r,e){return typeof r=="number"?`${r}px`:(nn.test(r)||console.warn(`[tbw-grid] Column '${e??"?"}' has an invalid CSS width value: '${r}'. Expected a number (px) or a valid CSS unit string (e.g. '30%', '2fr', 'calc(...)').`),r)}function ue(r){(r.effectiveConfig?.fitMode||r.fitMode||ne.STRETCH)===ne.STRETCH?r._gridTemplate=r._visibleColumns.map(t=>{if(t.width!=null)return Rt(t.width,t.field);const i=t.minWidth;return i!=null?`minmax(${i}px, 1fr)`:"1fr"}).join(" ").trim():r._gridTemplate=r._visibleColumns.map(t=>t.width!=null?Rt(t.width,t.field):"max-content").join(" "),r.style.setProperty("--tbw-column-template",r._gridTemplate)}function rn(r){return r==null?"string":typeof r=="number"?"number":typeof r=="boolean"?"boolean":r instanceof Date||typeof r=="string"&&/\d{4}-\d{2}-\d{2}/.test(r)&&!isNaN(Date.parse(r))?"date":"string"}function on(r,e){const t=r[0]||{},i=Object.keys(t).map(o=>{const s=t[o],l=rn(s);return{field:o,header:o.charAt(0).toUpperCase()+o.slice(1),type:l}}),n={};return i.forEach(o=>{n[o.field]=o.type||"string"}),{columns:i,typeMap:n}}const sn=/{{\s*([^}]+)\s*}}/g,q="__DG_EMPTY__",ln=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,an=/__(proto|defineGetter|defineSetter)|constructor|window|globalThis|global|process|Function|import|eval|Reflect|Proxy|Error|arguments|document|location|cookie|localStorage|sessionStorage|indexedDB|fetch|XMLHttpRequest|WebSocket|Worker|SharedWorker|ServiceWorker|opener|parent|top|frames|self|this\b/;function cn(r){return!r||typeof r!="string"?"":r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const dn=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"]),St=/^on\w+$/i,un=new Set(["href","src","action","formaction","data","srcdoc","xlink:href","poster","srcset"]),hn=/^\s*(javascript|vbscript|data|blob):/i;function X(r){if(!r||typeof r!="string")return"";if(r.indexOf("<")===-1)return r;const e=document.createElement("template");return e.innerHTML=r,fn(e.content),e.innerHTML}function fn(r){const e=[],t=r.querySelectorAll("*");for(const i of t){const n=i.tagName.toLowerCase();if(dn.has(n)){e.push(i);continue}if((n==="svg"||i.namespaceURI==="http://www.w3.org/2000/svg")&&Array.from(i.attributes).some(l=>St.test(l.name)||l.name==="href"||l.name==="xlink:href")){e.push(i);continue}const o=[];for(const s of i.attributes){const l=s.name.toLowerCase();if(St.test(l)){o.push(s.name);continue}if(un.has(l)&&hn.test(s.value)){o.push(s.name);continue}if(l==="style"&&/expression\s*\(|javascript:|behavior\s*:/i.test(s.value)){o.push(s.name);continue}}o.forEach(s=>i.removeAttribute(s))}e.forEach(i=>i.remove())}function xe(r,e){if(!r||r.indexOf("{{")===-1)return r;const t=[],i=r.replace(sn,(l,a)=>{const c=gn(a,e);return t.push({expr:a.trim(),result:c}),c}),n=pn(i),o=t.length&&t.every(l=>l.result===""||l.result===q);return J.test(r)||o?"":n}function gn(r,e){if(r=(r||"").trim(),!r||J.test(r))return q;if(r==="value")return e.value==null?q:String(e.value);if(r.startsWith("row.")&&!/[()?]/.test(r)&&!r.includes(":")){const i=r.slice(4),n=e.row?e.row[i]:void 0;return n==null?q:String(n)}if(r.length>80||!ln.test(r)||an.test(r))return q;const t=r.match(/\./g);if(t&&t.length>1)return q;try{const n=new Function("value","row",`return (${r});`)(e.value,e.row),o=n==null?"":String(n);return J.test(o)?q:o||q}catch{return q}}const J=/Reflect|Proxy|ownKeys/;function pn(r){return r&&r.replace(new RegExp(q,"g"),"").replace(/Reflect\.[^<>{}\s]+|\bProxy\b|ownKeys\([^)]*\)/g,"")}function wn(r){if(J.test(r.textContent||"")){for(const e of r.childNodes)e.nodeType===Node.TEXT_NODE&&J.test(e.textContent||"")&&(e.textContent="");J.test(r.textContent||"")&&(r.textContent="")}}function _t(r){const e=J.test(r),t=(i=>e?"":xe(r,i));return t.__blocked=e,t}const mn=100;class bn{#t;#e;#u;#c;#n;#l={};#i={};#f=!0;#w=[];#g;#a;#b;#d;#h;constructor(e){this.#d=e}get original(){return this.#l}get effective(){return this.#i}get columns(){return this.#i.columns??[]}set columns(e){this.#i.columns=e}get lightDomColumnsCache(){return this.#c}set lightDomColumnsCache(e){this.#c=e}get originalColumnNodes(){return this.#n}set originalColumnNodes(e){this.#n=e}get lightDomTitle(){return this.#h}set lightDomTitle(e){this.#h=e}get initialColumnState(){return this.#b}set initialColumnState(e){this.#b=e}get sourcesChanged(){return this.#f}markSourcesChanged(){this.#f=!0}setGridConfig(e){this.#t=e,this.#f=!0,this.#c=void 0}getGridConfig(){return this.#t}setColumns(e){this.#e=e,this.#f=!0}getColumns(){return this.#e}setFitMode(e){this.#u=e,this.#f=!0}getFitMode(){return this.#u}merge(){const e=(this.#i.columns?.length??0)>0;if(!this.#f&&e)return;const t=this.#S();this.#f=!1,this.#l=t,Object.freeze(this.#l),this.#l.columns&&Object.freeze(this.#l.columns),this.#i=this.#E(this.#l),this.#m()}#E(e){const t={...e};return e.columns&&(t.columns=e.columns.map(i=>({...i}))),e.shell&&(t.shell={...e.shell,header:e.shell.header?{...e.shell.header}:void 0,toolPanel:e.shell.toolPanel?{...e.shell.toolPanel}:void 0,toolPanels:e.shell.toolPanels?.map(i=>({...i})),headerContents:e.shell.headerContents?.map(i=>({...i}))}),t}#m(){const e=this.#i;this.#x(),typeof e.rowHeight=="number"&&e.rowHeight>0&&this.#d.setRowHeight(e.rowHeight),e.fitMode==="fixed"&&this.columns.forEach(i=>{i.width==null&&(i.width=80)}),this.#d.applyAnimationConfig(e)}#x(){const e=this.#i.typeDefaults;if(!e)return;const t=this.columns;for(const i of t){if(!i.type)continue;const n=e[i.type];n&&(!i.renderer&&!i.viewRenderer&&n.renderer&&(i.renderer=n.renderer),!i.format&&n.format&&(i.format=n.format),!i.editor&&n.editor&&(i.editor=n.editor),!i.editorParams&&n.editorParams&&(i.editorParams=n.editorParams))}}#S(){const e=this.#t?{...this.#t}:{},t=Array.isArray(e.columns)?[...e.columns]:[],i=(this.#c??[]).map(s=>({...s}));let n=Ct(t,i);this.#e&&this.#e.length&&(n=Ct(this.#e,i));const o=this.#d.getRows();return n.length===0&&o.length&&(n=on(o).columns),n.length&&(n.forEach(s=>{s.sortable===void 0&&(s.sortable=!0),s.resizable===void 0&&(s.resizable=!0),s.__originalWidth===void 0&&typeof s.width=="number"&&(s.__originalWidth=s.width)}),n.forEach(s=>{s.__viewTemplate&&!s.__compiledView&&(s.__compiledView=_t(s.__viewTemplate.innerHTML)),s.__editorTemplate&&!s.__compiledEditor&&(s.__compiledEditor=_t(s.__editorTemplate.innerHTML))}),e.columns=n),this.#u&&(e.fitMode=this.#u),e.fitMode||(e.fitMode="stretch"),this.#C(e),e.columnState&&!this.#b&&(this.#b=e.columnState),e}#C(e){e.shell=e.shell?{...e.shell}:{},e.shell.header=e.shell.header?{...e.shell.header}:{};const t=this.#d.getShellLightDomTitle();t&&(this.#h=t),this.#h&&!e.shell.header.title&&(e.shell.header.title=this.#h);const i=this.#d.getShellLightDomHeaderContent();i?.length>0&&(e.shell.header.lightDomContent=i),this.#d.getShellHasToolButtonsContainer()&&(e.shell.header.hasToolButtonsContainer=!0);const n=this.#d.getShellToolPanels();if(n.size>0){const u=Array.from(n.values());u.sort((h,p)=>(h.order??100)-(p.order??100)),e.shell.toolPanels=u}const o=this.#d.getShellHeaderContents();if(o.size>0){const u=Array.from(o.values());u.sort((h,p)=>(h.order??100)-(p.order??100)),e.shell.headerContents=u}const s=this.#d.getShellToolbarContents(),l=Array.from(s.values()),a=this.#t?.shell?.header?.toolbarContents??[],c=new Set(a.map(u=>u.id)),d=[...a];for(const u of l)c.has(u.id)||d.push(u);d.sort((u,h)=>(u.order??0)-(h.order??0)),e.shell.header.toolbarContents=d}collectState(e){const t=this.columns,i=this.#p();return{columns:t.map((n,o)=>{const s={field:n.field,order:o,visible:!n.hidden},l=n;l.__renderedWidth!==void 0?s.width=l.__renderedWidth:n.width!==void 0&&(s.width=typeof n.width=="string"?parseFloat(n.width):n.width);const a=i.get(n.field);a&&(s.sort=a);for(const c of e)if(c.getColumnState){const d=c.getColumnState(n.field);d&&Object.assign(s,d)}return s})}}applyState(e,t){if(!e.columns||e.columns.length===0)return;const i=this.columns,n=new Map(e.columns.map(l=>[l.field,l])),o=i.map(l=>{const a=n.get(l.field);if(!a)return l;const c={...l};return a.width!==void 0&&(c.width=a.width,c.__renderedWidth=a.width),a.visible!==void 0&&(c.hidden=!a.visible),c});o.sort((l,a)=>{const c=n.get(l.field)?.order??1/0,d=n.get(a.field)?.order??1/0;return c-d}),this.columns=o;const s=e.columns.filter(l=>l.sort!==void 0).sort((l,a)=>(l.sort?.priority??0)-(a.sort?.priority??0));if(s.length>0){const l=s[0];l.sort&&this.#d.setSortState({field:l.field,direction:l.sort.direction==="asc"?1:-1})}else this.#d.setSortState(null);for(const l of t)if(l.applyColumnState)for(const a of e.columns)l.applyColumnState(a.field,a)}resetState(e){this.#b=void 0,this.#d.setSortState(null),this.#i=this.#E(this.#l),this.#m();for(const t of e)if(t.applyColumnState)for(const i of this.columns)t.applyColumnState(i.field,{field:i.field,order:0,visible:!0});this.requestStateChange(e)}#p(){const e=new Map,t=this.#d.getSortState();return t&&e.set(t.field,{direction:t.direction===1?"asc":"desc",priority:0}),e}requestStateChange(e){this.#a&&clearTimeout(this.#a),this.#a=setTimeout(()=>{this.#a=void 0;const t=this.collectState(e);this.#d.emit("column-state-change",t)},mn)}setColumnVisible(e,t){const i=this.columns,n=i.find(s=>s.field===e);return!n||!t&&n.lockVisible||!t&&i.filter(l=>!l.hidden&&l.field!==e).length===0||!!n.hidden===!t?!1:(n.hidden=!t,this.#d.emit("column-visibility",{field:e,visible:t,visibleColumns:i.filter(s=>!s.hidden).map(s=>s.field)}),this.#d.clearRowPool(),this.#d.setup(),!0)}toggleColumnVisibility(e){const t=this.columns.find(i=>i.field===e);return t?this.setColumnVisible(e,!!t.hidden):!1}isColumnVisible(e){const t=this.columns.find(i=>i.field===e);return t?!t.hidden:!1}showAllColumns(){const e=this.columns;e.some(t=>t.hidden)&&(e.forEach(t=>t.hidden=!1),this.#d.emit("column-visibility",{visibleColumns:e.map(t=>t.field)}),this.#d.clearRowPool(),this.#d.setup())}getAllColumns(){return this.columns.map(e=>({field:e.field,header:e.header||e.field,visible:!e.hidden,lockVisible:e.lockVisible,utility:e.meta?.utility===!0}))}getColumnOrder(){return this.columns.map(e=>e.field)}setColumnOrder(e){if(!e.length)return;const t=new Map(this.columns.map(n=>[n.field,n])),i=[];for(const n of e){const o=t.get(n);o&&(i.push(o),t.delete(n))}for(const n of t.values())i.push(n);this.columns=i,this.#d.renderHeader(),this.#d.updateTemplate(),this.#d.refreshVirtualWindow()}parseLightDomColumns(e){this.#c||(this.#n=Array.from(e.querySelectorAll("tbw-grid-column")),this.#c=this.#n.length?tn(e):[])}clearLightDomCache(){this.#c=void 0}#v=new Map;registerLightDomHandler(e,t){this.#v.set(e.toLowerCase(),t)}unregisterLightDomHandler(e){this.#v.delete(e.toLowerCase())}observeLightDOM(e){this.#g&&this.#g.disconnect();const t=new Set;let i=null;const n=()=>{i=null;for(const o of t)this.#v.get(o)?.();t.clear()};this.#g=new MutationObserver(o=>{for(const s of o){for(const l of s.addedNodes){if(l.nodeType!==Node.ELEMENT_NODE)continue;const c=l.tagName.toLowerCase();this.#v.has(c)&&t.add(c)}if(s.type==="attributes"&&s.target.nodeType===Node.ELEMENT_NODE){const a=s.target.tagName.toLowerCase();this.#v.has(a)&&t.add(a)}}t.size>0&&!i&&(i=setTimeout(n,0))}),this.#g.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["title","field","header","width","hidden","id","icon","tooltip","order"]})}onChange(e){this.#w.push(e)}notifyChange(){for(const e of this.#w)e()}dispose(){this.#g?.disconnect(),this.#w=[],this.#a&&clearTimeout(this.#a)}}function Oe(){if(typeof window<"u"&&window.location){const r=window.location.hostname;if(r==="localhost"||r==="127.0.0.1"||r==="::1")return!0}return typeof process<"u"&&process.env?.NODE_ENV!=="production"}function At(r){return`<span role="checkbox" aria-checked="${r}" aria-label="${r}">${r?"🗹":"☐"}</span>`}function kt(r){if(r==null||r==="")return"";if(r instanceof Date)return isNaN(r.getTime())?"":r.toLocaleDateString();if(typeof r=="number"||typeof r=="string"){const e=new Date(r);return isNaN(e.getTime())?"":e.toLocaleDateString()}return""}function Ee(r){if(!r)return-1;const e=r.getAttribute("data-row");if(e)return parseInt(e,10);const t=r.closest(".data-grid-row");if(!t)return-1;const i=t.parentElement;if(!i)return-1;const n=i.querySelectorAll(":scope > .data-grid-row");for(let o=0;o<n.length;o++)if(n[o]===t)return o;return-1}function vn(r){if(!r)return-1;const e=r.getAttribute("data-col");return e?parseInt(e,10):-1}function he(r){r&&r.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function fe(r){try{if(getComputedStyle(r).direction==="rtl")return"rtl"}catch{}try{if(r.closest?.("[dir]")?.getAttribute("dir")==="rtl")return"rtl"}catch{}return"ltr"}function Tt(r){return fe(r)==="rtl"}function yn(r,e){return r==="left"||r==="right"?r:e==="rtl"?r==="start"?"right":"left":r==="start"?"left":"right"}function Lt(r,e){const t=e.renderer||e.viewRenderer;if(t)return t;if(!e.type)return;const i=r.__frameworkAdapter;if(i?.getTypeDefault){const n=i.getTypeDefault(e.type);if(n?.renderer)return n.renderer}}function Pt(r,e){if(e.format)return e.format;if(!e.type)return;const t=r.__frameworkAdapter;if(t?.getTypeDefault){const i=t.getTypeDefault(e.type);if(i?.format)return i.format}}const K='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function Ne(r){return(r.__editingCellCount??0)>0}function qe(r){r.__editingCellCount=0,r.removeAttribute("data-has-editing"),r.querySelectorAll(".cell.editing").forEach(t=>t.classList.remove("editing"))}const Ht=document.createElement("template");Ht.innerHTML='<div class="cell" role="gridcell" part="cell"></div>';const It=document.createElement("template");It.innerHTML='<div class="data-grid-row" role="row" part="row"></div>';function Cn(){return Ht.content.firstElementChild.cloneNode(!0)}function xn(){return It.content.firstElementChild.cloneNode(!0)}function Re(r){r.__cellDisplayCache=void 0,r.__cellCacheEpoch=void 0,r.__hasSpecialColumns=void 0}function En(r,e,t,i,n){const o=Math.max(0,t-e),s=r._bodyEl,l=r._visibleColumns,a=l.length;let c=r.__cachedHeaderRowCount;for(c===void 0&&(c=r.querySelector(".header-group-row")?2:1,r.__cachedHeaderRowCount=c);r._rowPool.length<o;){const h=xn();r._rowPool.push(h)}if(r._rowPool.length>o){for(let h=o;h<r._rowPool.length;h++){const p=r._rowPool[h];p.parentNode===s&&p.remove()}r._rowPool.length=o}const d=n&&r.__hasRenderRowPlugins!==!1,u=r._hasAfterRowRenderHook?.()??!1;for(let h=0;h<o;h++){const p=e+h,f=r._rows[p],g=r._rowPool[h];if(g.setAttribute("aria-rowindex",String(p+c+1)),d&&n(f,g,p)){g.__epoch=i,g.__rowDataRef=f,g.parentNode!==s&&s.appendChild(g);continue}const w=g.__epoch,b=g.__rowDataRef;let v=g.children.length;v>a&&g.lastElementChild?.classList.contains("tbw-row-loading-overlay")&&v--;const L=w===i&&v===a,_=b!==f,C=!!r._isGridEditMode;let m=!1;if(L&&_){for(let k=0;k<a;k++)if(l[k].externalView&&!g.querySelector(`.cell[data-col="${k}"] [data-external-view]`)){m=!0;break}}if(!L||m){const k=Ne(g),E=C||r._activeEditRows===p;k&&!E?(g.__isCustomRow&&(g.className="data-grid-row",g.setAttribute("role","row"),g.__isCustomRow=!1),qe(g),ge(r,g,f,p),g.__epoch=i,g.__rowDataRef=f):k&&E?(Ge(r,g,f,p),g.__rowDataRef=f):(g.__isCustomRow&&(g.className="data-grid-row",g.setAttribute("role","row"),g.__isCustomRow=!1),ge(r,g,f,p),g.__epoch=i,g.__rowDataRef=f)}else if(_){const k=Ne(g),E=C||r._activeEditRows===p;k&&!E?(qe(g),ge(r,g,f,p),g.__epoch=i,g.__rowDataRef=f):(Ge(r,g,f,p),g.__rowDataRef=f)}else{const k=Ne(g),E=C||r._activeEditRows===p;k&&!E?(qe(g),ge(r,g,f,p),g.__epoch=i,g.__rowDataRef=f):Ge(r,g,f,p)}let R=!1;const y=r.changedRowIds;if(y&&y.length>0)try{const k=r.getRowId?.(f);k&&(R=y.includes(k))}catch{}const x=g.classList.contains("changed");R!==x&&g.classList.toggle("changed",R);const H=r.effectiveConfig?.rowClass;if(H){const k=g.getAttribute("data-dynamic-classes");k&&k.split(" ").forEach(E=>E&&g.classList.remove(E));try{const E=H(f);if(E&&E.length>0){const T=E.filter(D=>D&&typeof D=="string");T.forEach(D=>g.classList.add(D)),g.setAttribute("data-dynamic-classes",T.join(" "))}else g.removeAttribute("data-dynamic-classes")}catch(E){console.warn("[tbw-grid] rowClass callback error:",E),g.removeAttribute("data-dynamic-classes")}}u&&r._afterRowRender?.({row:f,rowIndex:p,rowElement:g}),g.parentNode!==s&&s.appendChild(g)}}function Ge(r,e,t,i){const n=e.children,o=r._visibleColumns,s=o.length,l=n.length,a=s<l?s:l,c=r._focusRow,d=r._focusCol,u=r._hasAfterCellRenderHook?.()??!1;let h=r.__hasSpecialColumns;if(h===void 0){h=!1;const f=r.__frameworkAdapter;for(let g=0;g<s;g++){const w=o[g];if(w.__viewTemplate||w.__compiledView||w.renderer||w.viewRenderer||w.externalView||w.format||w.type==="date"||w.type==="boolean"||w.type&&f?.getTypeDefault?.(w.type)?.renderer||w.type&&f?.getTypeDefault?.(w.type)?.format){h=!0;break}}r.__hasSpecialColumns=h}const p=String(i);if(!h){for(let f=0;f<a;f++){const g=n[f];if(g.classList.contains("editing"))continue;g.firstElementChild&&r.__frameworkAdapter?.releaseCell?.(g);const w=o[f],b=t[w.field];g.textContent=b==null?"":String(b),g.getAttribute("data-row")!==p&&g.setAttribute("data-row",p);const v=c===i&&d===f,A=g.classList.contains("cell-focus");v!==A&&(g.classList.toggle("cell-focus",v),g.setAttribute("aria-selected",String(v))),u&&r._afterCellRender?.({row:t,rowIndex:i,column:w,colIndex:f,value:b,cellElement:g,rowElement:e})}return}for(let f=0;f<a;f++)if(o[f].externalView&&!n[f].querySelector("[data-external-view]")){ge(r,e,t,i);return}for(let f=0;f<a;f++){const g=o[f],w=n[f];w.getAttribute("data-row")!==p&&w.setAttribute("data-row",p);const b=c===i&&d===f,v=w.classList.contains("cell-focus");b!==v&&(w.classList.toggle("cell-focus",b),w.setAttribute("aria-selected",String(b)));const A=g.cellClass;if(A){const R=w.getAttribute("data-dynamic-classes");R&&R.split(" ").forEach(y=>y&&w.classList.remove(y));try{const y=t[g.field],x=A(y,t,g);if(x&&x.length>0){const H=x.filter(k=>k&&typeof k=="string");H.forEach(k=>w.classList.add(k)),w.setAttribute("data-dynamic-classes",H.join(" "))}else w.removeAttribute("data-dynamic-classes")}catch(y){console.warn(`[tbw-grid] cellClass callback error for column '${g.field}':`,y),w.removeAttribute("data-dynamic-classes")}}if(w.classList.contains("editing"))continue;const L=Lt(r,g);if(L){const R=t[g.field],y=L({row:t,value:R,field:g.field,column:g,cellEl:w});typeof y=="string"?(r.__frameworkAdapter?.releaseCell?.(w),w.innerHTML=X(y)):y instanceof Node?y.parentElement!==w&&(r.__frameworkAdapter?.releaseCell?.(w),w.innerHTML="",w.appendChild(y)):y==null&&(r.__frameworkAdapter?.releaseCell?.(w),w.textContent=R==null?"":String(R)),u&&r._afterCellRender?.({row:t,rowIndex:i,column:g,colIndex:f,value:R,cellElement:w,rowElement:e});continue}if(g.__viewTemplate||g.__compiledView||g.externalView)continue;const _=t[g.field];let C;const m=Pt(r,g);if(m){try{const R=m(_,t);C=R==null?"":String(R)}catch(R){console.warn(`[tbw-grid] Format error in column '${g.field}':`,R),C=_==null?"":String(_)}w.textContent=C}else g.type==="date"?(C=kt(_),w.textContent=C):g.type==="boolean"?w.innerHTML=At(!!_):(C=_==null?"":String(_),w.textContent=C);u&&r._afterCellRender?.({row:t,rowIndex:i,column:g,colIndex:f,value:_,cellElement:w,rowElement:e})}}function ge(r,e,t,i){e.classList.remove("tbw-row-loading"),e.removeAttribute("aria-busy");const n=r.__frameworkAdapter;if(n?.releaseCell){const h=e.children;for(let p=h.length-1;p>=0;p--)n.releaseCell(h[p])}e.innerHTML="";const o=r._visibleColumns,s=o.length,l=r._focusRow,a=r._focusCol,c=r,d=r._hasAfterCellRenderHook?.()??!1,u=document.createDocumentFragment();for(let h=0;h<s;h++){const p=o[h],f=Cn();f.setAttribute("aria-colindex",String(h+1)),f.setAttribute("data-col",String(h)),f.setAttribute("data-row",String(i)),f.setAttribute("data-field",p.field),f.setAttribute("data-header",p.header??p.field),p.type&&f.setAttribute("data-type",p.type);let g=t[p.field];const w=Pt(r,p);if(w)try{g=w(g,t)}catch(m){console.warn(`[tbw-grid] Format error in column '${p.field}':`,m)}const b=p.__compiledView,v=p.__viewTemplate,A=Lt(r,p),L=p.externalView;let _=!1;if(A){const m=A({row:t,value:g,field:p.field,column:p,cellEl:f});typeof m=="string"?(f.innerHTML=X(m),_=!0):m instanceof Node?m.parentElement!==f&&(f.textContent="",f.appendChild(m)):m==null&&(f.textContent=g==null?"":String(g))}else if(L){const m=L,R=document.createElement("div");R.setAttribute("data-external-view",""),R.setAttribute("data-field",p.field),f.appendChild(R);const y={row:t,value:g,field:p.field,column:p};if(m.mount)try{m.mount({placeholder:R,context:y,spec:m})}catch(x){console.warn(`[tbw-grid] External view mount error for column '${p.field}':`,x)}else queueMicrotask(()=>{try{c.dispatchEvent(new CustomEvent("mount-external-view",{bubbles:!0,composed:!0,detail:{placeholder:R,spec:m,context:y}}))}catch(x){console.warn(`[tbw-grid] External view event dispatch error for column '${p.field}':`,x)}});R.setAttribute("data-mounted","")}else if(b){const m=b({row:t,value:g,field:p.field,column:p}),R=b.__blocked;f.innerHTML=R?"":X(m),_=!0,R&&(f.textContent="",f.setAttribute("data-blocked-template",""))}else if(v){const m=v.innerHTML;/Reflect\.|\bProxy\b|ownKeys\(/.test(m)?(f.textContent="",f.setAttribute("data-blocked-template","")):(f.innerHTML=X(xe(m,{row:t,value:g})),_=!0)}else w?f.textContent=g==null?"":String(g):p.type==="date"?f.textContent=kt(g):p.type==="boolean"?f.innerHTML=At(!!g):f.textContent=g==null?"":String(g);if(_){wn(f);const m=f.textContent||"";/Proxy|Reflect\.ownKeys/.test(m)&&(f.textContent=m.replace(/Proxy|Reflect\.ownKeys/g,"").trim(),/Proxy|Reflect\.ownKeys/.test(f.textContent||"")&&(f.textContent=""))}f.hasAttribute("data-blocked-template")&&(f.textContent||"").trim().length&&(f.textContent=""),p.editable?f.tabIndex=0:p.type==="boolean"&&(f.hasAttribute("tabindex")||(f.tabIndex=0)),l===i&&a===h?(f.classList.add("cell-focus"),f.setAttribute("aria-selected","true")):f.setAttribute("aria-selected","false");const C=p.cellClass;if(C)try{const m=t[p.field],R=C(m,t,p);if(R&&R.length>0){const y=R.filter(x=>x&&typeof x=="string");y.forEach(x=>f.classList.add(x)),f.setAttribute("data-dynamic-classes",y.join(" "))}}catch(m){console.warn(`[tbw-grid] cellClass callback error for column '${p.field}':`,m)}d&&r._afterCellRender?.({row:t,rowIndex:i,column:p,colIndex:h,value:g,cellElement:f,rowElement:e}),u.appendChild(f)}e.appendChild(u)}function Dt(r,e,t){if(e.target?.closest(".resize-handle"))return;const i=t.querySelector(".cell[data-row]"),n=Ee(i);if(n<0)return;const o=r._rows[n];if(!o||r._dispatchRowClick?.(e,n,o,t))return;const s=e.target?.closest(".cell[data-col]");if(s){const l=Number(s.getAttribute("data-col"));if(!isNaN(l)){if(r._dispatchCellClick?.(e,n,l,s))return;const a=r._focusRow!==n||r._focusCol!==l;if(r._focusRow=n,r._focusCol=l,s.classList.contains("editing")){a&&(he(r._bodyEl??r),s.classList.add("cell-focus"));const c=s.querySelector(K);try{c?.focus({preventScroll:!0})}catch{}return}F(r)}}}function Rn(r,e){if(r._dispatchKeyDown?.(e))return;const t=r._rows.length-1,i=r._visibleColumns.length-1,n=r._activeEditRows!==void 0&&r._activeEditRows!==-1,s=r._visibleColumns[r._focusCol]?.type,l=e.composedPath?.()??[],a=l.length?l[0]:e.target,c=d=>{if(!d)return!1;const u=d.tagName;return!!(u==="INPUT"||u==="SELECT"||u==="TEXTAREA"||d.isContentEditable)};if(!(c(a)&&(e.key==="Home"||e.key==="End"))&&!(c(a)&&(e.key==="ArrowUp"||e.key==="ArrowDown")&&a.tagName==="INPUT"&&a.type==="number")&&!(c(a)&&(e.key==="ArrowLeft"||e.key==="ArrowRight"))&&!(c(a)&&(e.key==="Enter"||e.key==="Escape"))&&!(n&&s==="select"&&(e.key==="ArrowDown"||e.key==="ArrowUp"))){switch(e.key){case"Tab":{e.preventDefault(),!e.shiftKey?r._focusCol<i?r._focusCol+=1:(typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow<t&&(r._focusRow+=1,r._focusCol=0)):r._focusCol>0?r._focusCol-=1:r._focusRow>0&&(typeof r.commitActiveRowEdit=="function"&&r._activeEditRows===r._focusRow&&r.commitActiveRowEdit(),r._focusRow-=1,r._focusCol=i),F(r);return}case"ArrowDown":n&&typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow=Math.min(t,r._focusRow+1),e.preventDefault();break;case"ArrowUp":n&&typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow=Math.max(0,r._focusRow-1),e.preventDefault();break;case"ArrowRight":{Tt(r)?r._focusCol=Math.max(0,r._focusCol-1):r._focusCol=Math.min(i,r._focusCol+1),e.preventDefault();break}case"ArrowLeft":{Tt(r)?r._focusCol=Math.min(i,r._focusCol+1):r._focusCol=Math.max(0,r._focusCol-1),e.preventDefault();break}case"Home":(e.ctrlKey||e.metaKey)&&(n&&typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow=0),r._focusCol=0,e.preventDefault(),F(r,{forceScrollLeft:!0});return;case"End":(e.ctrlKey||e.metaKey)&&(n&&typeof r.commitActiveRowEdit=="function"&&r.commitActiveRowEdit(),r._focusRow=t),r._focusCol=i,e.preventDefault(),F(r,{forceScrollRight:!0});return;case"PageDown":r._focusRow=Math.min(t,r._focusRow+20),e.preventDefault();break;case"PageUp":r._focusRow=Math.max(0,r._focusRow-20),e.preventDefault();break;case"Enter":{const d=r._focusRow,u=r._focusCol,h=r._visibleColumns[u],p=r._rows[d],f=h?.field??"",g=f&&p?p[f]:void 0,w=r.querySelector(`[data-row="${d}"][data-col="${u}"]`),b={rowIndex:d,colIndex:u,field:f,value:g,row:p,cellEl:w,trigger:"keyboard",originalEvent:e},v=new CustomEvent("cell-activate",{cancelable:!0,detail:b});r.dispatchEvent(v);const A=new CustomEvent("activate-cell",{cancelable:!0,detail:{row:d,col:u}});if(r.dispatchEvent(A),v.defaultPrevented||A.defaultPrevented){e.preventDefault();return}break}default:return}F(r)}}function F(r,e){if(r._virtualization?.enabled){const{rowHeight:s,container:l,viewportEl:a}=r._virtualization,c=l,d=a?.clientHeight??c?.clientHeight??0;if(c&&d>0){const u=r._focusRow*s;u<c.scrollTop?c.scrollTop=u:u+s>c.scrollTop+d&&(c.scrollTop=u-d+s)}}const t=r._activeEditRows!==void 0&&r._activeEditRows!==-1;t||r.refreshVirtualWindow(!1),he(r._bodyEl),Array.from(r._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(s=>{s.setAttribute("aria-selected","false")});const i=r._focusRow,n=r._virtualization.start??0,o=r._virtualization.end??r._rows.length;if(i>=n&&i<o){const s=r._bodyEl.querySelectorAll(".data-grid-row")[i-n];let l=s?.children[r._focusCol];if((!l||!l.classList?.contains("cell"))&&(l=s?.querySelector(`.cell[data-col="${r._focusCol}"]`)??s?.querySelector(".cell[data-col]")),l){l.classList.add("cell-focus"),l.setAttribute("aria-selected","true");const a=r.querySelector(".tbw-scroll-area");if(a&&l&&(!t||e?.forceHorizontalScroll))if(e?.forceScrollLeft)a.scrollLeft=0;else if(e?.forceScrollRight)a.scrollLeft=a.scrollWidth-a.clientWidth;else{const c=r._getHorizontalScrollOffsets?.(s??void 0,l)??{left:0,right:0};if(!c.skipScroll){const d=l.getBoundingClientRect(),u=a.getBoundingClientRect(),h=d.left-u.left+a.scrollLeft,p=h+d.width,f=a.scrollLeft+c.left,g=a.scrollLeft+a.clientWidth-c.right;h<f?a.scrollLeft=h-c.left:p>g&&(a.scrollLeft=p-a.clientWidth+c.right)}}if(r._activeEditRows!==void 0&&r._activeEditRows!==-1&&l.classList.contains("editing")){const c=l.querySelector(K);if(c&&document.activeElement!==c)try{c.focus({preventScroll:!0})}catch{}}else if(!l.contains(document.activeElement)){l.hasAttribute("tabindex")||l.setAttribute("tabindex","-1");try{l.focus({preventScroll:!0})}catch{}}}}}const Se=new WeakMap;function Sn(r,e){const t=Ee(e),i=vn(e);if(t<0||i<0)return;r._focusRow=t,r._focusCol=i,he(r._bodyEl),e.classList.add("cell-focus"),e.setAttribute("aria-selected","true");const n=e.closest("tbw-grid");n&&document.activeElement!==n&&n.focus({preventScroll:!0})}function Be(r,e,t,i){let n=null;const o=t.composedPath?.();if(o&&o.length>0?n=o[0]:n=t.target,n&&!e.contains(n)){const g=document.elementFromPoint(t.clientX,t.clientY);g&&(n=g)}const s=n?.closest?.("[data-col]"),l=n?.closest?.(".data-grid-row"),a=n?.closest?.(".header-row");let c,d,u,h,p,f;return s&&(c=parseInt(s.getAttribute("data-row")??"-1",10),d=parseInt(s.getAttribute("data-col")??"-1",10),c>=0&&d>=0&&(u=r._rows[c],f=r._columns[d],h=f?.field,p=u&&h?u[h]:void 0)),{type:i,row:u,rowIndex:c!==void 0&&c>=0?c:void 0,colIndex:d!==void 0&&d>=0?d:void 0,field:h,value:p,column:f,originalEvent:t,cellElement:s??void 0,rowElement:l??void 0,isHeader:!!a,cell:c!==void 0&&d!==void 0&&c>=0&&d>=0?{row:c,col:d}:void 0}}function _n(r,e,t){const i=Be(r,e,t,"mousedown");(r._dispatchCellMouseDown?.(i)??!1)&&Se.set(r,!0)}function An(r,e,t){if(!Se.get(r))return;const i=Be(r,e,t,"mousemove");r._dispatchCellMouseMove?.(i)}function kn(r,e,t){if(!Se.get(r))return;const i=Be(r,e,t,"mouseup");r._dispatchCellMouseUp?.(i),Se.set(r,!1)}function Tn(r,e,t){e.addEventListener("mousedown",i=>{const n=i.target.closest(".cell[data-col]");n&&(n.classList.contains("editing")||(i.preventDefault(),Sn(r,n)))},{signal:t}),e.addEventListener("click",i=>{const n=i.target.closest(".data-grid-row");if(n&&Dt(r,i,n),!document.activeElement?.closest(".cell.editing")){const o=i.target.closest("tbw-grid");o&&o.focus({preventScroll:!0})}},{signal:t}),e.addEventListener("dblclick",i=>{const n=i.target.closest(".data-grid-row");n&&Dt(r,i,n)},{signal:t})}function Ln(r,e,t,i){e.addEventListener("keydown",n=>Rn(r,n),{signal:i}),t.addEventListener("mousedown",n=>_n(r,t,n),{signal:i}),document.addEventListener("mousemove",n=>An(r,t,n),{signal:i}),document.addEventListener("mouseup",n=>kn(r,t,n),{signal:i})}function Mt(r,e){return r==null&&e==null?0:r==null?-1:e==null||r>e?1:r<e?-1:0}function zt(r,e,t){const n=t.find(l=>l.field===e.field)?.sortComparator??Mt,{field:o,direction:s}=e;return[...r].sort((l,a)=>n(l[o],a[o],l,a)*s)}function Ft(r,e,t,i){r._rows=e,r.__rowRenderEpoch++,r._rowPool.forEach(n=>n.__epoch=-1),Le(r),r.refreshVirtualWindow(!0),r.dispatchEvent(new CustomEvent("sort-change",{detail:{field:t.field,direction:i}})),r.requestStateChange?.()}function Ot(r,e){!r._sortState||r._sortState.field!==e.field?(r._sortState||(r.__originalOrder=r._rows.slice()),Nt(r,e,1)):r._sortState.direction===1?Nt(r,e,-1):(r._sortState=null,r.__rowRenderEpoch++,r._rowPool.forEach(i=>i.__epoch=-1),r._rows=r.__originalOrder.slice(),Le(r),r._headerRowEl?.querySelectorAll('[role="columnheader"].sortable')?.forEach(i=>{i.getAttribute("aria-sort")?(i.getAttribute("aria-sort")==="ascending"||i.getAttribute("aria-sort")==="descending")&&(r._sortState||i.setAttribute("aria-sort","none")):i.setAttribute("aria-sort","none")}),r.refreshVirtualWindow(!0),r.dispatchEvent(new CustomEvent("sort-change",{detail:{field:e.field,direction:0}})),r.requestStateChange?.())}function Nt(r,e,t){r._sortState={field:e.field,direction:t};const i={field:e.field,direction:t},n=r._columns,s=(r.effectiveConfig?.sortHandler??zt)(r._rows,i,n);s&&typeof s.then=="function"?s.then(l=>{Ft(r,l,e,t)}):Ft(r,s,e,t)}function pe(r,e){return r.effectiveConfig?.sortable!==!1&&e.sortable===!0}function _e(r,e){return r.effectiveConfig?.resizable!==!1&&e.resizable!==!1}function Pn(r,e){typeof e=="string"?r.textContent=e:e instanceof HTMLElement&&(r.innerHTML="",r.appendChild(e.cloneNode(!0)))}function Ae(r,e){const t=document.createElement("span");xt(t,"sort-indicator");const i=r._sortState?.field===e.field?r._sortState.direction:0,n={...W,...r.icons},o=i===1?n.sortAsc:i===-1?n.sortDesc:n.sortNone;return Pn(t,o),t}function ke(r,e,t){const i=document.createElement("div");return i.className="resize-handle",i.setAttribute("aria-hidden","true"),i.addEventListener("mousedown",n=>{n.stopPropagation(),n.preventDefault(),r._resizeController.start(n,e,t)}),i.addEventListener("dblclick",n=>{n.stopPropagation(),n.preventDefault(),r._resizeController.resetColumn(e)}),i}function Te(r,e,t,i){i.classList.add("sortable"),i.tabIndex=0;const n=r._sortState?.field===e.field?r._sortState.direction:0;i.setAttribute("aria-sort",n===0?"none":n===1?"ascending":"descending"),i.addEventListener("click",o=>{r._resizeController?.isResizing||r._dispatchHeaderClick?.(o,t,i)||Ot(r,e)}),i.addEventListener("keydown",o=>{if(o.key==="Enter"||o.key===" "){if(o.preventDefault(),r._dispatchHeaderClick?.(o,t,i))return;Ot(r,e)}})}function Hn(r,e){if(e!=null)if(typeof e=="string"){const t=document.createElement("span");for(t.innerHTML=X(e);t.firstChild;)r.appendChild(t.firstChild)}else e instanceof Node&&r.appendChild(e)}function Le(r){r._headerRowEl=r.findHeaderRow();const e=r._headerRowEl;e&&(e.innerHTML="",r._visibleColumns.forEach((t,i)=>{const n=document.createElement("div");n.className="cell",xt(n,"header-cell"),n.setAttribute("role","columnheader"),n.setAttribute("aria-colindex",String(i+1)),n.setAttribute("data-field",t.field),n.setAttribute("data-col",String(i));const o=t.header??t.field,s=r._sortState?.field===t.field?r._sortState.direction:0,l=s===1?"asc":s===-1?"desc":null;if(t.headerRenderer){const a={column:t,value:o,sortState:l,filterActive:!1,cellEl:n,renderSortIcon:()=>pe(r,t)?Ae(r,t):null,renderFilterButton:()=>null},c=t.headerRenderer(a);Hn(n,c),pe(r,t)&&Te(r,t,i,n),_e(r,t)&&(n.classList.add("resizable"),n.appendChild(ke(r,i,n)))}else if(t.headerLabelRenderer){const a={column:t,value:o},c=t.headerLabelRenderer(a),d=document.createElement("span");c==null?d.textContent=o:typeof c=="string"?d.innerHTML=X(c):c instanceof Node&&d.appendChild(c),n.appendChild(d),pe(r,t)&&(Te(r,t,i,n),n.appendChild(Ae(r,t))),_e(r,t)&&(n.classList.add("resizable"),n.appendChild(ke(r,i,n)))}else if(t.__headerTemplate)Array.from(t.__headerTemplate.childNodes).forEach(a=>n.appendChild(a.cloneNode(!0))),pe(r,t)&&(Te(r,t,i,n),n.appendChild(Ae(r,t))),_e(r,t)&&(n.classList.add("resizable"),n.appendChild(ke(r,i,n)));else{const a=document.createElement("span");a.textContent=o,n.appendChild(a),pe(r,t)&&(Te(r,t,i,n),n.appendChild(Ae(r,t))),_e(r,t)&&(n.classList.add("resizable"),n.appendChild(ke(r,i,n)))}e.appendChild(n)}),e.querySelectorAll(".cell.sortable").forEach(t=>{t.getAttribute("aria-sort")||t.setAttribute("aria-sort","none")}),e.children.length>0?(e.setAttribute("role","row"),e.setAttribute("aria-rowindex","1")):(e.removeAttribute("role"),e.removeAttribute("aria-rowindex")))}const qt=typeof requestIdleCallback=="function";function In(r,e){return qt?requestIdleCallback(r,e):window.setTimeout(()=>{const t=Date.now();r({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})},1)}function Gt(r){qt?cancelIdleCallback(r):clearTimeout(r)}function Dn(r){const e=document.createElement("div");return e.className=`tbw-spinner tbw-spinner--${r}`,e.setAttribute("role","progressbar"),e.setAttribute("aria-label","Loading"),e}function Mn(r,e){if(e){const i=e({size:r});if(typeof i=="string"){const n=document.createElement("div");return n.innerHTML=i,n}return i}return Dn(r)}function zn(r){const e=document.createElement("div");return e.className="tbw-loading-overlay",e.setAttribute("role","status"),e.setAttribute("aria-live","polite"),e.appendChild(Mn("large",r)),e}function Fn(r,e){r.appendChild(e)}function On(r){r?.remove()}function Nn(r,e){if(e){if(r.classList.add("tbw-row-loading"),r.setAttribute("aria-busy","true"),!r.querySelector(".tbw-row-loading-overlay")){const t=document.createElement("div");t.className="tbw-row-loading-overlay",t.setAttribute("aria-hidden","true");const i=document.createElement("div");i.className="tbw-row-loading-spinner",t.appendChild(i),r.appendChild(t)}}else r.classList.remove("tbw-row-loading"),r.removeAttribute("aria-busy"),r.querySelector(".tbw-row-loading-overlay")?.remove()}function qn(r,e){e?(r.classList.add("tbw-cell-loading"),r.setAttribute("aria-busy","true")):(r.classList.remove("tbw-cell-loading"),r.removeAttribute("aria-busy"))}var z=(r=>(r[r.STYLE=1]="STYLE",r[r.VIRTUALIZATION=2]="VIRTUALIZATION",r[r.HEADER=3]="HEADER",r[r.ROWS=4]="ROWS",r[r.COLUMNS=5]="COLUMNS",r[r.FULL=6]="FULL",r))(z||{});class Gn{#t;#e=0;#u=0;#c=null;#n=null;#l=null;#i=!1;constructor(e){this.#t=e}requestPhase(e,t){e>this.#e&&(this.#e=e),this.#u===0&&(this.#f(),this.#u=requestAnimationFrame(()=>this.#w()))}whenReady(){return this.#c?this.#c:Promise.resolve()}setInitialReadyResolver(e){this.#l=e}cancel(){this.#u!==0&&(cancelAnimationFrame(this.#u),this.#u=0),this.#e=0,this.#n&&(this.#n(),this.#n=null,this.#c=null)}get isPending(){return this.#e!==0}get pendingPhase(){return this.#e}#f(){this.#c||(this.#c=new Promise(e=>{this.#n=e}))}#w(){if(this.#u=0,!this.#t.isConnected()){this.#e=0,this.#n&&(this.#n(),this.#n=null,this.#c=null);return}const e=this.#e;this.#e=0,e>=5&&this.#t.mergeConfig(),e>=4&&this.#t.processRows(),e>=5&&(this.#t.processColumns(),this.#t.updateTemplate()),e>=3&&this.#t.renderHeader(),e>=2&&this.#t.renderVirtualWindow(),e>=1&&this.#t.afterRender(),!this.#i&&this.#l&&(this.#i=!0,this.#l()),this.#n&&(this.#n(),this.#n=null,this.#c=null)}}function Bt(r){let e=null,t=null,i=null,n=null;const o=a=>{if(!e)return;const c=a.clientX-e.startX,d=Math.max(40,e.startWidth+c),u=r._visibleColumns[e.colIndex];u.width=d,u.__userResized=!0,u.__renderedWidth=d,t==null&&(t=requestAnimationFrame(()=>{t=null,r.updateTemplate?.()})),r.dispatchEvent(new CustomEvent("column-resize",{detail:{field:u.field,width:d}}))};let s=!1;const l=()=>{const a=e!==null;a&&(s=!0,requestAnimationFrame(()=>{s=!1})),window.removeEventListener("mousemove",o),window.removeEventListener("mouseup",l),i!==null&&(document.documentElement.style.cursor=i,i=null),n!==null&&(document.body.style.userSelect=n,n=null),e=null,a&&r.requestStateChange&&r.requestStateChange()};return{get isResizing(){return e!==null||s},start(a,c,d){a.preventDefault();const u=r._visibleColumns[c],h=typeof u?.width=="number"?u.width:void 0,p=u?.__renderedWidth??h??d.getBoundingClientRect().width;e={startX:a.clientX,colIndex:c,startWidth:p},window.addEventListener("mousemove",o),window.addEventListener("mouseup",l),i===null&&(i=document.documentElement.style.cursor),document.documentElement.style.cursor="e-resize",n===null&&(n=document.body.style.userSelect),document.body.style.userSelect="none"},resetColumn(a){const c=r._visibleColumns[a];c&&(c.__userResized=!1,c.__renderedWidth=void 0,c.width=c.__originalWidth,r.updateTemplate?.(),r.requestStateChange?.(),r.dispatchEvent(new CustomEvent("column-resize-reset",{detail:{field:c.field,width:c.width}})))},dispose(){l()}}}const $e="data-animating",Bn={change:"--tbw-row-change-duration",insert:"--tbw-row-insert-duration",remove:"--tbw-row-remove-duration"},$n={change:500,insert:300,remove:200};function Wn(r){const e=r.trim().toLowerCase();return e.endsWith("ms")?parseFloat(e):e.endsWith("s")?parseFloat(e)*1e3:parseFloat(e)}function Kn(r,e){const t=Bn[e],i=getComputedStyle(r).getPropertyValue(t);if(i){const n=Wn(i);if(!isNaN(n)&&n>0)return n}return $n[e]}function Vn(r,e,t){r.removeAttribute($e),r.offsetWidth,r.setAttribute($e,e);const i=Kn(r,e);setTimeout(()=>{e!=="remove"&&r.removeAttribute($e)},i)}function We(r,e,t){if(e<0)return!1;const i=r.findRenderedRowElement?.(e);return i?(Vn(i,t),!0):!1}function Un(r,e,t){let i=0;for(const n of e)We(r,n,t)&&i++;return i}function jn(r,e,t){const i=r._rows??[],n=r.getRowId;if(!n)return!1;const o=i.findIndex(s=>{if(s==null)return!1;try{return n(s)===e}catch{return!1}});return o<0?!1:We(r,o,t)}function Pe(r,e,t){const i=document.createElement(r);if(e)for(const n in e){const o=e[n];o!=null&&i.setAttribute(n,o)}return i}function N(r,e){const t=document.createElement("div");if(r&&(t.className=r),e)for(const i in e){const n=e[i];n!=null&&t.setAttribute(i,n)}return t}function $t(r,e,t){const i=document.createElement("button");if(r&&(i.className=r),e)for(const n in e){const o=e[n];o!=null&&i.setAttribute(n,o)}return i}const Wt=document.createElement("template");Wt.innerHTML=`
|
|
2
2
|
<div class="tbw-scroll-area">
|
|
3
3
|
<div class="rows-body-wrapper">
|
|
4
4
|
<div class="rows-body" role="grid">
|
|
@@ -87,11 +87,11 @@ ${G(i.name)}Plugin and ${G(s.name)}Plugin are both loaded, but they are currentl
|
|
|
87
87
|
@layer tbw-base{.tbw-loading-overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:1000;pointer-events:all;animation:tbw-fade-in .15s ease-out}.tbw-spinner{--tbw-spinner-size: 48px;--tbw-spinner-border-width: 3px;--tbw-spinner-color: var(--tbw-color-accent);--tbw-spinner-track-color: var(--tbw-color-border);width:var(--tbw-spinner-size);height:var(--tbw-spinner-size);border:var(--tbw-spinner-border-width) solid var(--tbw-spinner-track-color);border-top-color:var(--tbw-spinner-color);border-radius:50%;animation:tbw-spin .8s linear infinite}.tbw-spinner--large{--tbw-spinner-size: min(48px, calc(100% - 16px) )}.tbw-spinner--small{--tbw-spinner-size: calc(var(--tbw-row-height, 28px) * .6);--tbw-spinner-border-width: 2px}.data-grid-row.tbw-row-loading{position:relative;pointer-events:none}.tbw-row-loading-overlay{position:absolute;inset:0;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:26;animation:tbw-fade-in .15s ease-out;pointer-events:none;display:flex;align-items:center}.tbw-row-loading-spinner{--_spinner-size: calc(var(--tbw-row-height, 28px) * .6);margin-left:var(--tbw-spacing-md);width:var(--_spinner-size);height:var(--_spinner-size);border:2px solid var(--tbw-spinner-track-color, var(--tbw-color-border));border-top-color:var(--tbw-spinner-color, var(--tbw-color-accent));border-radius:50%;animation:tbw-spin .8s linear infinite}.cell.tbw-cell-loading{position:relative;pointer-events:none}.cell.tbw-cell-loading:before{content:"";position:absolute;inset:0;background:light-dark(rgba(255,255,255,.7),rgba(0,0,0,.5));z-index:26;animation:tbw-fade-in .15s ease-out}.cell.tbw-cell-loading:after{--_spinner-size: calc(var(--tbw-row-height, 28px) * .5);content:"";position:absolute;left:var(--tbw-spacing-sm);top:0;bottom:0;margin:auto 0;width:var(--_spinner-size);height:var(--_spinner-size);border:2px solid var(--tbw-spinner-track-color, var(--tbw-color-border));border-top-color:var(--tbw-spinner-color, var(--tbw-color-accent));border-radius:50%;animation:tbw-spin .8s linear infinite;z-index:27}}
|
|
88
88
|
@layer tbw-base{tbw-grid .tbw-expanding{animation:tbw-expand var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}tbw-grid .tbw-collapsing{animation:tbw-collapse var(--tbw-animation-duration) var(--tbw-animation-easing) forwards;overflow:hidden}tbw-grid[data-animation-mode=off]{--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}tbw-grid[data-animation-mode=off] .data-grid-row[data-animating]{animation:none}tbw-grid .data-grid-row[data-animating=change]{animation:tbw-row-change var(--tbw-row-change-duration) ease-out}tbw-grid .data-grid-row[data-animating=insert]{animation:tbw-row-insert var(--tbw-row-insert-duration) ease-out;will-change:max-height,opacity}tbw-grid .data-grid-row[data-animating=remove]{animation:tbw-row-remove var(--tbw-row-remove-duration) ease-out forwards;will-change:max-height,opacity,transform;pointer-events:none}}@keyframes tbw-expand{0%{opacity:0;max-height:0;transform:translateY(-8px)}to{opacity:1;max-height:500px;transform:translateY(0)}}@keyframes tbw-collapse{0%{opacity:1;max-height:500px;transform:translateY(0)}to{opacity:0;max-height:0;transform:translateY(-8px)}}@keyframes tbw-row-change{0%{background-color:transparent}20%{background-color:var(--tbw-row-change-color)}to{background-color:transparent}}@keyframes tbw-row-insert{0%{opacity:0;max-height:0;overflow:hidden}to{opacity:1;max-height:var(--tbw-row-height, 28px);overflow:hidden}}@keyframes tbw-row-remove{0%{opacity:1;transform:translateY(0);max-height:var(--tbw-row-height, 28px)}to{opacity:0;max-height:0;transform:translateY(-8px)}}@keyframes tbw-spin{to{transform:rotate(360deg)}}@keyframes tbw-fade-in{0%{opacity:0}to{opacity:1}}
|
|
89
89
|
@layer tbw-base{@media(forced-colors:active){tbw-grid{--tbw-color-border: CanvasText;--tbw-color-border-strong: CanvasText;--tbw-color-border-cell: CanvasText;--tbw-color-border-header: CanvasText;--tbw-color-fg: CanvasText;--tbw-color-bg: Canvas;--tbw-color-panel-bg: Canvas;--tbw-color-header-bg: Canvas;--tbw-color-header-fg: CanvasText;--tbw-color-accent: Highlight;--tbw-color-accent-fg: HighlightText;--tbw-color-selection: Highlight;--tbw-color-row-hover: Highlight;--tbw-focus-outline: 2px solid Highlight;--tbw-range-border-color: Highlight}tbw-grid .cell:focus,tbw-grid .cell.active-cell{outline:2px solid Highlight!important;outline-offset:-2px}tbw-grid .data-grid-row[aria-selected=true]{background:Highlight!important;color:HighlightText!important}}@media(prefers-reduced-motion:reduce){tbw-grid[data-animation-mode=reduced-motion]{--tbw-animation-enabled: 0;--tbw-animation-duration: 0ms}tbw-grid[data-animation-mode=reduced-motion] .data-grid-row[data-animating]{animation:none}}}
|
|
90
|
-
`;class V extends HTMLElement{static tagName="tbw-grid";static version=typeof __GRID_VERSION__<"u"?__GRID_VERSION__:"dev";static#t=0;static adapters=[];static registerAdapter(e){this.adapters.push(e)}static getAdapters(){return this.adapters}static clearAdapters(){this.adapters=[]}static get observedAttributes(){return["rows","columns","grid-config","fit-mode","loading"]}get#e(){return this}#u=!1;#c;#n;#l=[];get#i(){return this.#o?.effective??{}}#f=!1;#w=!1;#g={rows:!1,columns:!1,gridConfig:!1,fitMode:!1};#a;#b=0;#d=null;#h=!1;#E=!1;#m=0;#x;#S=dr();#C;#p;#v;#R;#P={scrollTop:0,scrollLeft:0,scrollHeight:0,scrollWidth:0,clientHeight:0,clientWidth:0};#r;#_;#N=!1;#M;#K;#z;#o;#s=Qn();#y;#q;#F=!1;#A=new Set;#H=new Map;#G;#k=new Map;_rows=[];#V=[];get _columns(){return this.#i.columns??[]}set _columns(e){this.#i.columns=e}get _visibleColumns(){return this._columns.filter(e=>!e.hidden)}_headerRowEl;_bodyEl;_rowPool=[];_resizeController;_virtualization={enabled:!0,rowHeight:28,bypassThreshold:24,start:0,end:0,container:null,viewportEl:null,totalHeightEl:null,positionCache:null,heightCache:{byKey:new Map,byRef:new WeakMap},averageHeight:28,measuredCount:0,variableHeights:!1,cachedViewportHeight:0,cachedFauxHeight:0,cachedScrollAreaHeight:0,scrollAreaEl:null};_focusRow=0;_focusCol=0;_restoreFocusAfterRender=!1;_sortState=null;_gridTemplate="";__rowRenderEpoch=0;__didInitialAutoSize=!1;get __lightDomColumnsCache(){return this.#o?.lightDomColumnsCache}set __lightDomColumnsCache(e){this.#o&&(this.#o.lightDomColumnsCache=e)}get __originalColumnNodes(){return this.#o?.originalColumnNodes}set __originalColumnNodes(e){this.#o&&(this.#o.originalColumnNodes=e)}__originalOrder=[];__frameworkAdapter;__rowsBodyEl=null;get rows(){return this._rows}set rows(e){const t=this.#l;this.#l=e,t!==e&&this.#W("rows")}get sourceRows(){return this.#l}get columns(){return[...this._columns]}set columns(e){const t=this.#o?.getColumns();this.#o?.setColumns(e),t!==e&&this.#W("columns")}get gridConfig(){return this.#i}set gridConfig(e){const t=this.#o?.getGridConfig();this.#o?.setGridConfig(e),t!==e&&(this.#o.clearLightDomCache(),this.#W("gridConfig"))}get fitMode(){return this.#i.fitMode??"stretch"}set fitMode(e){const t=this.#o?.getFitMode();this.#o?.setFitMode(e),t!==e&&this.#W("fitMode")}get loading(){return this.#F}set loading(e){const t=this.#F;this.#F=e,e?this.setAttribute("loading",""):this.removeAttribute("loading"),t!==e&&this.#ue()}setRowLoading(e,t){const i=this.#A.has(e);t?this.#A.add(e):this.#A.delete(e),i!==t&&this.#X(e,t)}setCellLoading(e,t,i){let n=this.#H.get(e);const o=n?.has(t)??!1;i?(n||(n=new Set,this.#H.set(e,n)),n.add(t)):(n?.delete(t),n?.size===0&&this.#H.delete(e)),o!==i&&this.#he(e,t,i)}isRowLoading(e){return this.#A.has(e)}isCellLoading(e,t){return this.#H.get(e)?.has(t)??!1}clearAllLoading(){this.loading=!1;for(const e of this.#A)this.#X(e,!1);this.#A.clear();for(const[e,t]of this.#H)for(const i of t)this.#he(e,i,!1);this.#H.clear()}get effectiveConfig(){return this.#i}get disconnectSignal(){return this.#C||(this.#C=new AbortController),this.#C.signal}constructor(){super(),this.#me(),this.#c=new Promise(e=>this.#n=e),this.#a=new Gn({mergeConfig:()=>{this.#o.parseLightDomColumns(this),this.#o.merge(),this.#te(),yr(this.#i,this.#r?.getPlugins()??[]),Cr(this.#r?.getPlugins()??[]),Er(this.#r?.getPlugins()??[]),this.#He(),this.#V=[...this._columns]},processColumns:()=>this.#ke(),processRows:()=>this.#Le(),renderHeader:()=>Le(this),updateTemplate:()=>ue(this),renderVirtualWindow:()=>this.refreshVirtualWindow(!0,!0),afterRender:()=>{this.#r?.afterRender(),this._virtualization.enabled&&this._virtualization.totalHeightEl&&queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const t=this.#L(this._rows.length);this._virtualization.totalHeightEl.style.height=`${t}px`}),this.#i.fitMode==="fixed"&&!this.__didInitialAutoSize&&(this.__didInitialAutoSize=!0,Et(this)),this._restoreFocusAfterRender&&(this._restoreFocusAfterRender=!1,F(this)),this._virtualization.enabled&&!this.#$&&this.#ye(),this.#E&&(this.#E=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.#ve()})})),this.#F&&this.#ue()},isConnected:()=>this.isConnected&&this.#f}),this.#a.setInitialReadyResolver(()=>this.#n?.()),this.#y=nr(this.#s,{getShadow:()=>this.#e,getShellConfig:()=>this.#i?.shell,getAccordionIcons:()=>({expand:this.#i?.icons?.expand??W.expand,collapse:this.#i?.icons?.collapse??W.collapse}),emit:(e,t)=>this.#I(e,t),refreshShellHeader:()=>this.refreshShellHeader()}),this.#o=new bn({getRows:()=>this.#l,getSortState:()=>this._sortState,setSortState:e=>{this._sortState=e},onConfigChange:()=>{this.#a.requestPhase(z.FULL,"configChange")},emit:(e,t)=>this.#I(e,t),clearRowPool:()=>{this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++},setup:()=>this.#D(),renderHeader:()=>Le(this),updateTemplate:()=>ue(this),refreshVirtualWindow:()=>this.#a.requestPhase(z.VIRTUALIZATION,"configManager"),getVirtualization:()=>this._virtualization,setRowHeight:e=>{this._virtualization.rowHeight=e},applyAnimationConfig:e=>this.#Pe(e),getShellLightDomTitle:()=>this.#s.lightDomTitle,getShellToolPanels:()=>this.#s.toolPanels,getShellHeaderContents:()=>this.#s.headerContents,getShellToolbarContents:()=>this.#s.toolbarContents,getShellLightDomHeaderContent:()=>this.#s.lightDomHeaderContent,getShellHasToolButtonsContainer:()=>this.#s.hasToolButtonsContainer})}async#me(){await cr(Dr)}getPlugin(e){return this.#r?.getPlugin(e)}getPluginByName(e){return this.#r?.getPluginByName(e)}requestRender(){this.#a.requestPhase(z.ROWS,"plugin:requestRender")}requestColumnsRender(){this.#a.requestPhase(z.COLUMNS,"plugin:requestColumnsRender")}requestRenderWithFocus(){this._restoreFocusAfterRender=!0,this.#a.requestPhase(z.ROWS,"plugin:requestRenderWithFocus")}updateTemplate(){ue(this)}requestAfterRender(){this.#a.requestPhase(z.STYLE,"plugin:requestAfterRender")}#ee(){this.#r=new we(this);const e=this.#i?.plugins,t=Array.isArray(e)?e:[];this.#r.attachAll(t)}#B(){const e=this.#r?.getPluginStyles()??[];lr(e)}#te(){const e=this.#i?.plugins,t=Array.isArray(e)?e:[];if(this.#_===t)return;if(this.#_&&this.#_.length===t.length&&this.#_.every((n,o)=>n===t[o])){this.#_=t;return}this.#r&&this.#r.detachAll();for(const n of this.#s.toolPanels.keys()){const o=this.#s.lightDomToolPanelIds.has(n),s=this.#s.apiToolPanelIds.has(n);if(!o&&!s){const l=this.#s.panelCleanups.get(n);l&&(l(),this.#s.panelCleanups.delete(n)),this.#s.toolPanels.delete(n)}}for(const n of this.#s.headerContents.keys()){const o=this.#s.headerContentCleanups.get(n);o&&(o(),this.#s.headerContentCleanups.delete(n)),this.#s.headerContents.delete(n)}this.#ee(),this.#B(),this.#_=t,this.#oe(),this.#ie();const i=this.#h;if(this.#h=this.#r?.getAll().some(n=>n.onScroll)??!1,!i&&this.#h){const o=this.#e.querySelector(".tbw-grid-content")??this.#e.querySelector(".tbw-grid-root");this.#U(o)}}#be(){this.#r?.detachAll()}#ie(){if(!this.#r)return;const e=this.#r.getToolPanels();for(const{panel:i}of e)this.#s.toolPanels.has(i.id)||this.#s.toolPanels.set(i.id,i);const t=this.#r.getHeaderContents();for(const{content:i}of t)this.#s.headerContents.has(i.id)||this.#s.headerContents.set(i.id,i)}#ne(){const e=V.getAdapters();if(e.length===0&&!this.__frameworkAdapter)return;const t=this.__frameworkAdapter;return i=>{if(t?.createToolPanelRenderer){const n=t.createToolPanelRenderer(i);if(n)return n}for(const n of e)if(n.createToolPanelRenderer){const o=n.createToolPanelRenderer(i);if(o)return o}}}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=0),this.hasAttribute("version")||this.setAttribute("version",V.version),this.id||(this.id=`tbw-grid-${++V.#t}`),this._rows=Array.isArray(this.#l)?[...this.#l]:[],this.#C&&(this.#C.abort(),this.#N=!1),this.#C=new AbortController,this.#R&&(Gt(this.#R),this.#R=void 0),this.#O(),this.#o.parseLightDomColumns(this),this.#o.merge(),this.#ee();const e=this.#i?.plugins;this.#_=Array.isArray(e)?e:[],this.#ie(),this.#u||(this.#J(),this.#B(),this.#u=!0),this.#re(),this.#R=In(()=>{this.#ze()},{timeout:100})}disconnectedCallback(){this.#R&&(Gt(this.#R),this.#R=void 0),this.#m&&(clearTimeout(this.#m),this.#m=0),this.#be(),ir(this.#s),this.#y.setInitialized(!1),this.#q?.(),this.#q=void 0,ei(this.#S),this.#C&&(this.#C.abort(),this.#C=void 0),this.#M?.abort(),this.#M=void 0,this.#N=!1,this._resizeController&&this._resizeController.dispose(),this.#p&&(this.#p.disconnect(),this.#p=void 0),this.#v&&(this.#v.disconnect(),this.#v=void 0,this.#$=!1),Re(this),this.#T.clear(),this.#_=void 0;for(const e of this._rowPool)e.remove();this._rowPool.length=0,this.__rowsBodyEl=null,this.#f=!1}attributeChangedCallback(e,t,i){if(e==="loading"){const n=i!==null&&i!=="false";this.loading!==n&&(this.loading=n);return}if(!(t===i||!i||i==="null"||i==="undefined"))if(e==="rows"||e==="columns"||e==="grid-config")try{const n=JSON.parse(i);e==="rows"?this.rows=n:e==="columns"?this.columns=n:e==="grid-config"&&(this.gridConfig=n)}catch{console.warn(`[tbw-grid] Invalid JSON for '${e}' attribute:`,i)}else e==="fit-mode"&&(this.fitMode=i)}#re(){const t=this.#e.querySelector(".tbw-grid-content")??this.#e.querySelector(".tbw-grid-root");if(this._headerRowEl=t?.querySelector(".header-row"),this._virtualization.totalHeightEl=t?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=t?.querySelector(".rows-viewport"),this._bodyEl=t?.querySelector(".rows"),this.__rowsBodyEl=t?.querySelector(".rows-body"),this.#y.isInitialized){Ve(this.#e,this.#s),Ke(this.#e,this.#i?.shell,this.#s);const n=this.#i?.shell?.toolPanel?.defaultOpen;n&&this.#s.toolPanels.has(n)&&(this.openToolPanel(),this.#s.expandedSections.add(n))}if(this.setAttribute("data-upgraded",""),this.#f=!0,this._resizeController=Bt(this),this.#D(),this.#U(t),this.#N)return;this.#N=!0;const i=this.disconnectSignal;Ln(this,this,this.#e,i),this.#oe(),queueMicrotask(()=>this.#Ce()),this.#a.requestPhase(z.FULL,"afterConnect")}#oe(){const e=this.#i.rowHeight,t=this.#r.hasRowHeightPlugin();typeof e=="function"||t?this._virtualization.variableHeights||(this._virtualization.variableHeights=!0,this._virtualization.rowHeight=typeof e=="number"&&e>0?e:this._virtualization.rowHeight||28,this.#Z(),typeof e!="function"&&(this.#E=!0)):!t&&typeof e!="function"&&this._virtualization.variableHeights?(this._virtualization.variableHeights=!1,this._virtualization.positionCache=null):typeof e=="number"&&e>0?(this._virtualization.rowHeight=e,this._virtualization.variableHeights=!1):requestAnimationFrame(()=>this.#se())}#se(){if(this.#r.hasExtraHeight())return;const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;const t=e.querySelectorAll(".cell");let i=0;t.forEach(s=>{const l=s.offsetHeight;l>i&&(i=l)});const n=e.getBoundingClientRect(),o=Math.max(n.height,i);o>0&&Math.abs(o-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=o,this.#a.requestPhase(z.VIRTUALIZATION,"measureRowHeight"))}#ve(){const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;const t=e.querySelectorAll(".cell");let i=0;t.forEach(s=>{const l=s.offsetHeight;l>i&&(i=l)});const n=e.getBoundingClientRect(),o=Math.max(n.height,i);if(o>0&&(Math.abs(o-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=o),this.#Z(),this._virtualization.totalHeightEl)){const l=this.#L(this._rows.length);this._virtualization.totalHeightEl.style.height=`${l}px`}}#U(e){this.#M?.abort(),this.#M=new AbortController;const t=this.#M.signal,i=e?.querySelector(".faux-vscroll"),n=e?.querySelector(".rows");if(this._virtualization.container=i??this,this.#h=this.#r?.getAll().some(o=>o.onScroll)??!1,i&&n){i.addEventListener("scroll",()=>{if(!this._virtualization.enabled&&!this.#h)return;const a=i.scrollTop,c=this._virtualization.rowHeight;if(this._rows.length<=this._virtualization.bypassThreshold)n.style.transform=`translateY(${-a}px)`;else{const d=this._virtualization.positionCache;let u,h;if(this._virtualization.variableHeights&&d&&d.length>0){u=ni(d,a),u===-1&&(u=0);const f=u-u%2;h=d[f]?.offset??f*c}else u=Math.floor(a/c),h=(u-u%2)*c;const p=-(a-h);n.style.transform=`translateY(${p}px)`}this.#d=a,this.#b||(this.#b=requestAnimationFrame(()=>{this.#b=0,this.#d!==null&&(this.#Ie(this.#d),this.#d=null)}))},{passive:!0,signal:t});const o=this.#e.querySelector(".tbw-scroll-area");this.#K=o,this._virtualization.scrollAreaEl=o,o&&this.#h&&o.addEventListener("scroll",()=>{const a=this.#P;a.scrollTop=i.scrollTop,a.scrollLeft=o.scrollLeft,a.scrollHeight=i.scrollHeight,a.scrollWidth=o.scrollWidth,a.clientHeight=i.clientHeight,a.clientWidth=o.clientWidth,this.#r?.onScroll(a)},{passive:!0,signal:t});const s=this.#e.querySelector(".tbw-grid-content"),l=this.#K;s&&(s.addEventListener("wheel",a=>{const c=a.shiftKey||Math.abs(a.deltaX)>Math.abs(a.deltaY);if(c&&l){const d=a.shiftKey?a.deltaY:a.deltaX,{scrollLeft:u,scrollWidth:h,clientWidth:p}=l;(d>0&&u<h-p||d<0&&u>0)&&(a.preventDefault(),l.scrollLeft+=d)}else if(!c){const{scrollTop:d,scrollHeight:u,clientHeight:h}=i;(a.deltaY>0&&d<u-h||a.deltaY<0&&d>0)&&(a.preventDefault(),i.scrollTop+=a.deltaY)}},{passive:!1,signal:t}),wr(s,this.#S,{fauxScrollbar:i,scrollArea:l},t))}this._bodyEl&&Tn(this,this._bodyEl,t),this.#p?.disconnect(),this._virtualization.viewportEl&&(this.#p=new ResizeObserver(()=>{this.#Fe(),this.#a.requestPhase(z.VIRTUALIZATION,"resize-observer")}),this.#p.observe(this._virtualization.viewportEl)),this.#e.addEventListener("focusin",()=>{this.dataset.hasFocus=""},{signal:t}),this.#e.addEventListener("focusout",o=>{const s=o.relatedTarget;(!s||!this.#e.contains(s))&&delete this.dataset.hasFocus},{signal:t})}#$=!1;#ye(){if(this.#$)return;const e=this._bodyEl?.querySelector(".data-grid-row");e&&(this.#$=!0,this.#v?.disconnect(),this.#v=new ResizeObserver(()=>{this.#se()}),this.#v.observe(e))}addEventListener(e,t,i){super.addEventListener(e,t,i)}removeEventListener(e,t,i){super.removeEventListener(e,t,i)}#I(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}#Ce(){this._bodyEl?.querySelectorAll(".data-grid-row")?.forEach((t,i)=>{const n=i===this._focusRow;t.setAttribute("aria-selected",String(n)),t.querySelectorAll(".cell").forEach((o,s)=>{o.setAttribute("aria-selected",String(n&&s===this._focusCol))})})}#W(e){this.#g[e]=!0,!this.#w&&(this.#w=!0,queueMicrotask(()=>this.#xe()))}#xe(){if(!this.#w||!this.#f){this.#w=!1;return}const e=this.#g;if(this.#w=!1,this.#g={rows:!1,columns:!1,gridConfig:!1,fitMode:!1},e.gridConfig){this.#_e(),e.rows&&this.#le();return}e.columns&&this.#Re(),e.rows&&this.#le(),e.fitMode&&this.#Se()}#le(){this._rows=Array.isArray(this.#l)?[...this.#l]:[],this.#j(),this.#a.requestPhase(z.ROWS,"applyRowsUpdate")}#j(){this.#k.clear();const e=this.#i.getRowId;this._rows.forEach((t,i)=>{const n=this.#ae(t,e);n!==void 0&&this.#k.set(n,{row:t,index:i})})}#ae(e,t){if(t)return t(e);const i=e;if("id"in i&&i.id!=null)return String(i.id);if("_id"in i&&i._id!=null)return String(i._id)}#Ee(e,t){const i=this.#ae(e,t);if(i===void 0)throw new Error('[tbw-grid] Cannot determine row ID. Configure getRowId in gridConfig or ensure rows have an "id" property.');return i}#Re(){Re(this),this.#o.merge(),this.#D()}#Se(){this.#o.merge(),this.#i.fitMode==="fixed"?(this.__didInitialAutoSize=!1,Et(this)):(this._columns.forEach(t=>{!t.__userResized&&t.__autoSized&&delete t.width}),ue(this))}#_e(){jt(this,this.#s),Yt(this,this.#s);const e=!!this.#e.querySelector(".has-shell"),t=!!this.#e.querySelector(".tbw-tool-panel"),i=this.#e.querySelectorAll(".tbw-accordion-section").length;this.#o.parseLightDomColumns(this),this.#o.merge(),this.#te(),Xt(this,this.#s,this.#ne()),this.#o.markSourcesChanged(),this.#o.merge();const n=Ut(this.#i?.shell),o=(this.#i?.shell?.toolPanels?.length??0)>0,s=this.#i?.shell?.toolPanels?.length??0;if(e!==n||!t&&o||t&&s!==i){Ue(this.#s),this.#J(),this.#B(),this.#re(),this.#j();return}e&&this.#Ae(),this.#j(),this.#a.requestPhase(z.COLUMNS,"applyGridConfigUpdate")}#Ae(){const e=this.#e.querySelector(".tbw-shell-header");if(!e)return;const t=this.#i.shell?.header?.title??this.#s.lightDomTitle;let i=e.querySelector(".tbw-shell-title");t?(i||(i=document.createElement("h2"),i.className="tbw-shell-title",i.setAttribute("part","shell-title"),e.insertBefore(i,e.firstChild)),i.textContent=t):i&&i.remove()}#ke(){if(this.#r){const e=this.#V.length>0?this.#V:this._columns,t=e.filter(o=>!o.hidden),i=e.filter(o=>o.hidden),n=this.#r.processColumns([...t]);if(n!==t){const o=new Set(n.map(l=>l.field));!t.some(l=>o.has(l.field))&&n.length>0?this._columns=[...n,...i]:this._columns=this.#Te(e,n,i)}else this._columns=[...e]}}#Te(e,t,i){if(i.length===0)return t;const n=new Map;for(const a of t)n.set(a.field,a);const o=new Set(e.map(a=>a.field)),s=[];for(const a of t)o.has(a.field)||s.push(a);const l=[];for(const a of e){const c=n.get(a.field);c?l.push(c):a.hidden&&l.push(a)}return l.push(...s),l}#Le(){Re(this);const e=Array.isArray(this.#l)?[...this.#l]:[],t=this.#r?.processRows(e)??e;this._rows=t,this._virtualization.variableHeights&&this.#Z()}#Pe(e){const t={...vt,...e.animation},i=t.mode??"reduced-motion";let n=1;i===!1||i==="off"?n=0:(i===!0||i==="on")&&(n=1),this.style.setProperty("--tbw-animation-duration",`${t.duration}ms`),this.style.setProperty("--tbw-animation-easing",t.easing??"ease-out"),this.style.setProperty("--tbw-animation-enabled",String(n)),this.dataset.animationMode=typeof i=="boolean"?i?"on":"off":i}#Y(e,t,i=this.__rowRenderEpoch){if(this.#x||(this.#x=(n,o,s)=>this.#r?.renderRow(n,o,s)??!1),En(this,e,t,i,this.#x),this.#A.size>0)for(const n of this.#A)this.#X(n,!0)}#ce=de();#de(e,t){Zi(this.#ce,this.__rowsBodyEl,this._bodyEl,e,t)}#He(){en(this.#ce,this.__rowsBodyEl,this.#i,this.#s)}#ue(){const e=this.querySelector(".tbw-grid-root");e&&(this.#F?(this.#G||(this.#G=zn(this.#i?.loadingRenderer)),Fn(e,this.#G)):On(this.#G))}#X(e,t){const i=this.#k.get(e);if(!i)return;const n=this.findRenderedRowElement?.(i.index);n&&Nn(n,t)}#he(e,t,i){const n=this.#k.get(e);if(!n)return;const o=this.findRenderedRowElement?.(n.index);if(!o)return;const s=this._visibleColumns.findIndex(a=>a.field===t);if(s<0)return;const l=o.children[s];l&&qn(l,i)}#D(){if(this.isConnected&&!(!this._headerRowEl||!this._bodyEl)){if(this.#o.parseLightDomColumns(this),this.#z){const e=this.#z;this.#z=void 0,this.#o.merge();const t=this.#r?.getAll()??[];this.#o.applyState(e,t)}this._bodyEl&&(this._bodyEl.style.display="",this._bodyEl.style.gridTemplateColumns=""),this.#a.requestPhase(z.FULL,"setup")}}#Ie(e){let t=0,i=0,n=0,o=0,s=0;if(this.#h){const a=this._virtualization.container,c=this.#K;t=c?.scrollLeft??0,i=a?.scrollHeight??0,n=c?.scrollWidth??0,o=a?.clientHeight??0,s=c?.clientWidth??0}if(this.refreshVirtualWindow(!1)&&this.#r?.onScrollRender(),this._virtualization.variableHeights&&(this.#m&&clearTimeout(this.#m),this.#m=window.setTimeout(()=>{this.#m=0,this.#pe(this._virtualization.start,this._virtualization.end)},100)),this.#h){const a=this.#P;a.scrollTop=e,a.scrollLeft=t,a.scrollHeight=i,a.scrollWidth=n,a.clientHeight=o,a.clientWidth=s,this.#r?.onScroll(a)}}findHeaderRow(){return this.#e.querySelector(".header-row")}findRenderedRowElement(e){return Array.from(this._bodyEl.querySelectorAll(".data-grid-row")).find(t=>{const i=t.querySelector(".cell[data-row]");return i&&Number(i.getAttribute("data-row"))===e})||null}_dispatchCellClick(e,t,i,n){const o=this._rows[t],s=this._columns[i];if(!o||!s)return!1;const l=s.field,a=o[l],c=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,composed:!0,detail:{rowIndex:t,colIndex:i,field:l,value:a,row:o,cellEl:n,trigger:"pointer",originalEvent:e}});if(this.dispatchEvent(c),c.defaultPrevented)return!0;const d={row:o,rowIndex:t,colIndex:i,field:l,value:a,cellEl:n,originalEvent:e},u=this.#r?.onCellClick(d)??!1;return this.#I("cell-click",d),u}_dispatchRowClick(e,t,i,n){if(!i)return!1;const o={rowIndex:t,row:i,rowEl:n,originalEvent:e},s=this.#r?.onRowClick(o)??!1;return this.#I("row-click",o),s}_dispatchHeaderClick(e,t,i){const n=this._columns[t];if(!n)return!1;const o={colIndex:t,field:n.field,column:n,headerEl:i,originalEvent:e};return this.#r?.onHeaderClick(o)??!1}_dispatchKeyDown(e){return this.#r?.onKeyDown(e)??!1}_getHorizontalScrollOffsets(e,t){return this.#r?.getHorizontalScrollOffsets(e,t)??{left:0,right:0}}queryPlugins(e){return this.#r?.queryPlugins(e)??[]}query(e,t){return this.#r?.queryPlugins({type:e,context:t})??[]}_dispatchCellMouseDown(e){return this.#r?.onCellMouseDown(e)??!1}_dispatchCellMouseMove(e){this.#r?.onCellMouseMove(e)}_dispatchCellMouseUp(e){this.#r?.onCellMouseUp(e)}_afterCellRender(e){this.#r?.afterCellRender(e)}_hasAfterCellRenderHook(){return this.#r?.hasAfterCellRenderHook()??!1}_afterRowRender(e){this.#r?.afterRowRender(e)}_hasAfterRowRenderHook(){return this.#r?.hasAfterRowRenderHook()??!1}async ready(){return this.#c}async forceLayout(){return this.#a.requestPhase(z.FULL,"forceLayout"),this.#a.whenReady()}async getConfig(){return Object.freeze({...this.#i||{}})}getRowId(e){return this.#Ee(e,this.#i.getRowId)}getRow(e){return this.#k.get(e)?.row}updateRow(e,t,i="api"){const n=this.#k.get(e);if(!n)throw new Error(`[tbw-grid] Row with ID "${e}" not found. Ensure the row exists and getRowId is correctly configured.`);const{row:o,index:s}=n,l=[];for(const[a,c]of Object.entries(t)){const d=o[a];d!==c&&(l.push({field:a,oldValue:d,newValue:c}),o[a]=c)}for(const{field:a,oldValue:c,newValue:d}of l)this.#I("cell-change",{row:o,rowId:e,rowIndex:s,field:a,oldValue:c,newValue:d,changes:t,source:i});l.length>0&&this.#a.requestPhase(z.ROWS,"updateRow")}updateRows(e,t="api"){let i=!1;for(const{id:n,changes:o}of e){const s=this.#k.get(n);if(!s)throw new Error(`[tbw-grid] Row with ID "${n}" not found. Ensure the row exists and getRowId is correctly configured.`);const{row:l,index:a}=s;for(const[c,d]of Object.entries(o)){const u=l[c];u!==d&&(i=!0,l[c]=d,this.#I("cell-change",{row:l,rowId:n,rowIndex:a,field:c,oldValue:u,newValue:d,changes:o,source:t}))}}i&&this.#a.requestPhase(z.ROWS,"updateRows")}animateRow(e,t){We(this,e,t)}animateRows(e,t){Un(this,e,t)}animateRowById(e,t){return jn(this,e,t)}setColumnVisible(e,t){const i=this.#o.setColumnVisible(e,t);return i&&this.requestStateChange(),i}toggleColumnVisibility(e){const t=this.#o.toggleColumnVisibility(e);return t&&this.requestStateChange(),t}isColumnVisible(e){return this.#o.isColumnVisible(e)}showAllColumns(){this.#o.showAllColumns(),this.requestStateChange()}getAllColumns(){return this.#o.getAllColumns()}setColumnOrder(e){this.#o.setColumnOrder(e),this.requestStateChange()}getColumnOrder(){return this.#o.getColumnOrder()}getColumnState(){const e=this.#r?.getAll()??[];return this.#o.collectState(e)}set columnState(e){e&&(this.#z=e,this.#o.initialColumnState=e,this.#u&&this.#De(e))}get columnState(){return this.getColumnState()}#De(e){const t=this.#r?.getAll()??[];this.#o.applyState(e,t),this.#D()}requestStateChange(){const e=this.#r?.getAll()??[];this.#o.requestStateChange(e)}resetColumnState(){this.#z=void 0,this.__originalOrder=[];const e=this.#r?.getAll()??[];this.#o.resetState(e),this.#o.merge(),this.#D()}get isToolPanelOpen(){return this.#y.isPanelOpen}get defaultRowHeight(){return this._virtualization.rowHeight}get expandedToolPanelSections(){return this.#y.expandedSections}openToolPanel(){this.#y.openToolPanel()}closeToolPanel(){this.#y.closeToolPanel()}toggleToolPanel(){this.#y.toggleToolPanel()}toggleToolPanelSection(e){this.#y.toggleToolPanelSection(e)}getToolPanels(){return this.#y.getToolPanels()}registerToolPanel(e){this.#s.apiToolPanelIds.add(e.id),this.#y.registerToolPanel(e)}unregisterToolPanel(e){this.#s.apiToolPanelIds.delete(e),this.#y.unregisterToolPanel(e)}getHeaderContents(){return this.#y.getHeaderContents()}registerHeaderContent(e){this.#y.registerHeaderContent(e)}unregisterHeaderContent(e){this.#y.unregisterHeaderContent(e)}getToolbarContents(){return this.#y.getToolbarContents()}registerToolbarContent(e){this.#y.registerToolbarContent(e)}unregisterToolbarContent(e){this.#y.unregisterToolbarContent(e)}#Q=!1;refreshShellHeader(){this.#Q||(this.#Q=!0,queueMicrotask(()=>{this.#Q=!1,this.isConnected&&(this.#O(),this.#o.markSourcesChanged(),this.#o.merge(),Ue(this.#s),this.#J(),this.#B(),this.#Me())}))}#Me(){const t=this.#e.querySelector(".tbw-grid-content")??this.#e.querySelector(".tbw-grid-root");if(this._headerRowEl=t?.querySelector(".header-row"),this._virtualization.totalHeightEl=t?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=t?.querySelector(".rows-viewport"),this._bodyEl=t?.querySelector(".rows"),this.__rowsBodyEl=t?.querySelector(".rows-body"),this.#y.isInitialized){Ve(this.#e,this.#s),Ke(this.#e,this.#i?.shell,this.#s);const i=this.#i?.shell?.toolPanel?.defaultOpen;i&&this.#s.toolPanels.has(i)&&(this.openToolPanel(),this.#s.expandedSections.add(i))}this._resizeController=Bt(this),this.#U(t),this.#a.requestPhase(z.COLUMNS,"shellRefresh")}#T=new Map;registerStyles(e,t){let i=this.#T.get(e);i||(i=new CSSStyleSheet,this.#T.set(e,i)),i.replaceSync(t),this.#fe()}unregisterStyles(e){this.#T.delete(e)&&this.#fe()}getRegisteredStyles(){return Array.from(this.#T.keys())}#fe(){const e=Array.from(this.#T.values()),t=document.adoptedStyleSheets.filter(i=>!Array.from(this.#T.values()).includes(i));document.adoptedStyleSheets=[...t,...e]}#O(){jt(this,this.#s),Yt(this,this.#s),Xt(this,this.#s,this.#ne())}#ge(){const e=this.#e.querySelector(".tbw-shell-header");if(!e)return;Ue(this.#s);const t=Zn(this.#i.shell,this.#s,this.#i.icons?.toolPanel),i=document.createElement("div");i.innerHTML=t;const n=i.firstElementChild;n&&(e.replaceWith(n),this.#we(),Ke(this.#e,this.#i?.shell,this.#s))}#ze(){const e=()=>{const i=this.#s.lightDomTitle,n=this.#s.hasToolButtonsContainer;this.#O();const o=this.#s.lightDomTitle,s=this.#s.hasToolButtonsContainer;(o&&!i||s&&!n)&&(this.#o.markSourcesChanged(),this.#o.merge(),this.#ge())},t=()=>{this.__lightDomColumnsCache=void 0,this.#D()};this.#o.registerLightDomHandler("tbw-grid-header",e),this.#o.registerLightDomHandler("tbw-grid-tool-buttons",e),this.#o.registerLightDomHandler("tbw-grid-tool-panel",e),this.#o.registerLightDomHandler("tbw-grid-column",t),this.#o.registerLightDomHandler("tbw-grid-detail",t),this.#o.observeLightDOM(this)}refreshColumns(){this.__lightDomColumnsCache=void 0,Re(this),this.#o.parseLightDomColumns(this);const e=this.#s.lightDomTitle,t=this.#s.hasToolButtonsContainer;this.#O();const i=this.#s.lightDomTitle,n=this.#s.hasToolButtonsContainer;(i&&!e||n&&!t)&&(this.#o.markSourcesChanged(),this.#o.merge(),this.#ge()),this.#a.requestPhase(z.COLUMNS,"refreshColumns")}#Fe(){const e=this._virtualization.container,t=this._virtualization.viewportEl??e;t&&(this._virtualization.cachedViewportHeight=t.clientHeight),e&&(this._virtualization.cachedFauxHeight=e.clientHeight);const i=this._virtualization.scrollAreaEl;i&&(this._virtualization.cachedScrollAreaHeight=i.clientHeight)}#L(e,t=!1){const i=this._virtualization;let n,o,s;if(t){const h=i.container??this,p=i.viewportEl??h,f=i.scrollAreaEl;n=h.clientHeight,o=p.clientHeight,s=f?f.clientHeight:n,i.cachedFauxHeight=n,i.cachedViewportHeight=o,i.cachedScrollAreaHeight=s}else n=i.cachedFauxHeight,o=i.cachedViewportHeight,s=i.cachedScrollAreaHeight||n;const l=s-o,a=Math.max(0,n-s);let c,d=0;return i.variableHeights&&i.positionCache?c=Ar(i.positionCache):(c=e*i.rowHeight,d=this.#r?.getExtraHeight()??0),c+l+d+a}#Z(){if(!this._virtualization.variableHeights)return;const e=this._rows,t=this._virtualization.rowHeight||28,i=this.#i.rowHeight,n=this.#i.getRowId,o=n?l=>n(l):void 0;this._virtualization.positionCache=_r(e,this._virtualization.heightCache,t,{rowId:o},(l,a)=>{const c=this.#r?.getRowHeight?.(l,a);if(c!==void 0)return c;if(i){const d=i(l,a);if(d!==void 0&&d>0)return d}});const s=Pr(this._virtualization.positionCache,e,t,(l,a)=>this.#r?.getRowHeight?.(l,a));this._virtualization.measuredCount=s.measuredCount,s.measuredCount>0&&(this._virtualization.averageHeight=s.averageHeight)}invalidateRowHeight(e,t){if(!this._virtualization.variableHeights||!this._virtualization.positionCache||e<0||e>=this._rows.length)return;const i=this._virtualization.positionCache,n=this._rows[e];let o=t;o===void 0&&(o=this.#r?.getRowHeight?.(n,e)),o===void 0&&(o=this._virtualization.rowHeight);const s=i[e];if(!(!s||Math.abs(s.height-o)<1)&&(Ze(i,e,o),this._virtualization.totalHeightEl)){const l=this.#L(this._rows.length);this._virtualization.totalHeightEl.style.height=`${l}px`}}#pe(e,t){if(!this._virtualization.variableHeights||!this._virtualization.positionCache||!this._bodyEl)return;const i=this._bodyEl.querySelectorAll(".data-grid-row"),n=this.#i.getRowId,o=Lr({positionCache:this._virtualization.positionCache,heightCache:this._virtualization.heightCache,rows:this._rows,defaultHeight:this._virtualization.rowHeight,start:e,end:t,getPluginHeight:(s,l)=>this.#r?.getRowHeight?.(s,l),getRowId:n?s=>n(s):void 0},i);if(o.hasChanges&&(this._virtualization.measuredCount=o.measuredCount,this._virtualization.averageHeight=o.averageHeight,this._virtualization.totalHeightEl)){const s=this.#L(this._rows.length);this._virtualization.totalHeightEl.style.height=`${s}px`}}refreshVirtualWindow(e=!1,t=!1){if(!this._bodyEl)return!1;const i=this._rows.length;if(!this._virtualization.enabled)return this.#Y(0,i),t||this.#r?.afterRender(),!0;if(this._rows.length<=this._virtualization.bypassThreshold)return this._virtualization.start=0,this._virtualization.end=i,e&&(this._bodyEl.style.transform="translateY(0px)"),this.#Y(0,i,e?++this.__rowRenderEpoch:this.__rowRenderEpoch),e&&this._virtualization.totalHeightEl&&(this._virtualization.totalHeightEl.style.height=`${this.#L(i,!0)}px`),this.#de(i,this._visibleColumns.length),t||this.#r?.afterRender(),!0;const n=this._virtualization.container??this,o=this._virtualization.viewportEl??n,s=e?this._virtualization.cachedViewportHeight=o.clientHeight:this._virtualization.cachedViewportHeight||(this._virtualization.cachedViewportHeight=o.clientHeight),l=this._virtualization.rowHeight,a=n.scrollTop;let c;const d=this._virtualization.positionCache;if(this._virtualization.variableHeights&&d&&d.length>0)c=ni(d,a),c===-1&&(c=0);else{c=Math.floor(a/l);let v=0;const A=10;for(;v<A;){const L=this.#r?.getExtraHeightBefore?.(c)??0,_=Math.floor((a-L)/l);if(_>=c||_<0)break;c=_,v++}}c=c-c%2,c<0&&(c=0);const u=this.#r?.adjustVirtualStart(c,a,l);u!==void 0&&u<c&&(c=u,c=c-c%2,c<0&&(c=0));let h;if(this._virtualization.variableHeights&&d&&d.length>0){const v=s+l*3;let A=0;for(h=c;h<i&&A<v;)A+=d[h].height,h++;const L=Math.ceil(s/l)+3;h-c<L&&(h=Math.min(c+L,i))}else{const v=Math.ceil(s/l)+3;h=c+v}h>i&&(h=i);const p=this._virtualization.start,f=this._virtualization.end;if(!e&&c===p&&h===f)return!1;this._virtualization.start=c,this._virtualization.end=h;const g=e?this._virtualization.cachedFauxHeight=n.clientHeight:this._virtualization.cachedFauxHeight||(this._virtualization.cachedFauxHeight=n.clientHeight);if(e){const v=this._virtualization.scrollAreaEl;v&&(this._virtualization.cachedScrollAreaHeight=v.clientHeight)}if(g===0&&s>0)return this.#a.requestPhase(z.VIRTUALIZATION,"stale-refs-retry"),!1;if(e&&this._virtualization.totalHeightEl){const v=this.#L(i);this._virtualization.totalHeightEl.style.height=`${v}px`}let w;if(this._virtualization.variableHeights&&d&&d[c])w=d[c].offset;else{const v=this.#r?.getExtraHeightBefore?.(c)??0;w=c*l+v}const b=-(a-w);return this._bodyEl.style.transform=`translateY(${b}px)`,this.#Y(c,h,e?++this.__rowRenderEpoch:this.__rowRenderEpoch),e&&this._virtualization.variableHeights&&this.#pe(c,h),this.#de(i,this._visibleColumns.length),e&&!t&&(this.#r?.afterRender(),queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const v=this.#L(i);this._virtualization.cachedFauxHeight===0&&this._virtualization.cachedViewportHeight>0||(this._virtualization.totalHeightEl.style.height=`${v}px`)})),!0}#J(){this.#O(),this.#o.markSourcesChanged(),this.#o.merge();const e=this.#i?.shell;or(this.#e,e,{isPanelOpen:this.#s.isPanelOpen,expandedSections:this.#s.expandedSections},this.#i?.icons)&&(this.#we(),this.#y.setInitialized(!0))}#we(){Jn(this.#e,this.#i?.shell,this.#s,{onPanelToggle:()=>this.toggleToolPanel(),onSectionToggle:e=>this.toggleToolPanelSection(e)}),this.#q?.(),this.#q=er(this.#e,this.#i?.shell,e=>{this.style.setProperty("--tbw-tool-panel-width",`${e}px`)})}}customElements.get(V.tagName)||customElements.define(V.tagName,V),globalThis.DataGridElement=V;const Mr={CAN_MOVE_COLUMN:"canMoveColumn",GET_CONTEXT_MENU_ITEMS:"getContextMenuItems"};class M{static dependencies;static manifest;version=typeof __GRID_VERSION__<"u"?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#t;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}attach(e){this.#t?.abort(),this.#t=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#t?.abort(),this.#t=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const i=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(i),i.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid}get disconnectSignal(){return this.#t?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...W,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(e===!1||e==="off")return!1;if(e===!0||e==="on")return!0;const t=this.gridElement;return t?getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()!=="0":!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),i=parseInt(t,10);if(!isNaN(i))return i}return 200}resolveIcon(e,t){return t!==void 0?t:this.gridIcons[e]}setIcon(e,t){typeof t=="string"?e.innerHTML=t:t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}warn(e){console.warn(`[tbw-grid:${this.name}] ${e}`)}}const O={ROOT:"tbw-grid-root",HEADER:"header",HEADER_ROW:"header-row",HEADER_CELL:"header-cell",ROWS_VIEWPORT:"rows-viewport",ROWS_SPACER:"rows-spacer",ROWS_CONTAINER:"rows",DATA_ROW:"data-row",GROUP_ROW:"group-row",DATA_CELL:"data-cell",SELECTED:"selected",FOCUSED:"focused",EDITING:"editing",EXPANDED:"expanded",COLLAPSED:"collapsed",DRAGGING:"dragging",RESIZING:"resizing",SORTABLE:"sortable",SORTED_ASC:"sorted-asc",SORTED_DESC:"sorted-desc",HIDDEN:"hidden",STICKY_LEFT:"sticky-left",STICKY_RIGHT:"sticky-right",PINNED_TOP:"pinned-top",PINNED_BOTTOM:"pinned-bottom",TREE_TOGGLE:"tree-toggle",TREE_INDENT:"tree-indent",GROUP_TOGGLE:"group-toggle",GROUP_LABEL:"group-label",GROUP_COUNT:"group-count",RANGE_SELECTION:"range-selection",SELECTION_OVERLAY:"selection-overlay"},me={ROW_INDEX:"data-row-index",COL_INDEX:"data-col-index",FIELD:"data-field",GROUP_KEY:"data-group-key",TREE_LEVEL:"data-tree-level",STICKY:"data-sticky"},zr={ROOT:`.${O.ROOT}`,HEADER:`.${O.HEADER}`,HEADER_ROW:`.${O.HEADER_ROW}`,HEADER_CELL:`.${O.HEADER_CELL}`,ROWS_VIEWPORT:`.${O.ROWS_VIEWPORT}`,ROWS_CONTAINER:`.${O.ROWS_CONTAINER}`,DATA_ROW:`.${O.DATA_ROW}`,DATA_CELL:`.${O.DATA_CELL}`,GROUP_ROW:`.${O.GROUP_ROW}`,ROW_BY_INDEX:r=>`.${O.DATA_ROW}[${me.ROW_INDEX}="${r}"]`,CELL_BY_FIELD:r=>`.${O.DATA_CELL}[${me.FIELD}="${r}"]`,CELL_AT:(r,e)=>`.${O.DATA_ROW}[${me.ROW_INDEX}="${r}"] .${O.DATA_CELL}[${me.COL_INDEX}="${e}"]`,SELECTED_ROWS:`.${O.DATA_ROW}.${O.SELECTED}`,EDITING_CELL:`.${O.DATA_CELL}.${O.EDITING}`},Fr={COLOR_BG:"--tbw-color-bg",COLOR_FG:"--tbw-color-fg",COLOR_FG_MUTED:"--tbw-color-fg-muted",COLOR_BORDER:"--tbw-color-border",COLOR_ACCENT:"--tbw-color-accent",COLOR_HEADER_BG:"--tbw-color-header-bg",COLOR_HEADER_FG:"--tbw-color-header-fg",COLOR_SELECTION:"--tbw-color-selection",COLOR_ROW_HOVER:"--tbw-color-row-hover",COLOR_ROW_ALT:"--tbw-color-row-alt",ROW_HEIGHT:"--tbw-row-height",HEADER_HEIGHT:"--tbw-header-height",CELL_PADDING:"--tbw-cell-padding",FONT_FAMILY:"--tbw-font-family",FONT_SIZE:"--tbw-font-size",BORDER_RADIUS:"--tbw-border-radius",FOCUS_OUTLINE:"--tbw-focus-outline"};function Or(r){const e=document.createElement("tbw-grid");return r&&(e.gridConfig=r),e}function Nr(r,e=document){return e.querySelector(r)}const qr={CELL_CHANGE:"cell-change",CELL_COMMIT:"cell-commit",ROW_COMMIT:"row-commit",EDIT_OPEN:"edit-open",EDIT_CLOSE:"edit-close",CHANGED_ROWS_RESET:"changed-rows-reset",MOUNT_EXTERNAL_VIEW:"mount-external-view",MOUNT_EXTERNAL_EDITOR:"mount-external-editor",SORT_CHANGE:"sort-change",COLUMN_RESIZE:"column-resize",ACTIVATE_CELL:"activate-cell",CELL_ACTIVATE:"cell-activate",GROUP_TOGGLE:"group-toggle",COLUMN_STATE_CHANGE:"column-state-change"},Gr={SELECTION_CHANGE:"selection-change",TREE_EXPAND:"tree-expand",FILTER_CHANGE:"filter-change",SORT_MODEL_CHANGE:"sort-model-change",EXPORT_START:"export-start",EXPORT_COMPLETE:"export-complete",CLIPBOARD_COPY:"clipboard-copy",CLIPBOARD_PASTE:"clipboard-paste",CONTEXT_MENU_OPEN:"context-menu-open",CONTEXT_MENU_CLOSE:"context-menu-close",HISTORY_CHANGE:"history-change",SERVER_LOADING:"server-loading",SERVER_ERROR:"server-error",COLUMN_VISIBILITY_CHANGE:"column-visibility-change",COLUMN_REORDER:"column-reorder",DETAIL_EXPAND:"detail-expand",GROUP_EXPAND:"group-expand"};function Ie(r,e,t=!0){let i=r;if(t&&(i=i.filter(n=>!n.hidden&&!n.field.startsWith("__")&&n.meta?.utility!==!0)),e?.length){const n=new Set(e);i=i.filter(o=>n.has(o.field))}return i}function Je(r,e){return e?.length?[...e].sort((t,i)=>t-i).map(t=>r[t]).filter(t=>t!=null):r}function Br(r){return r==null?"":r instanceof Date?r.toISOString():typeof r=="object"?JSON.stringify(r):String(r)}async function $r(r){try{return await navigator.clipboard.writeText(r),!0}catch{const e=document.createElement("textarea");e.value=r,e.style.position="fixed",e.style.opacity="0",e.style.pointerEvents="none",document.body.appendChild(e),e.select();const t=document.execCommand("copy");return document.body.removeChild(e),t}}function ri(r,e){const t=e.delimiter??" ",i=e.newline??`
|
|
90
|
+
`;class V extends HTMLElement{static tagName="tbw-grid";static version=typeof __GRID_VERSION__<"u"?__GRID_VERSION__:"dev";static#t=0;static adapters=[];static registerAdapter(e){this.adapters.push(e)}static getAdapters(){return this.adapters}static clearAdapters(){this.adapters=[]}static get observedAttributes(){return["rows","columns","grid-config","fit-mode","loading"]}get#e(){return this}#u=!1;#c;#n;#l=[];get#i(){return this.#o?.effective??{}}#f=!1;#w=!1;#g={rows:!1,columns:!1,gridConfig:!1,fitMode:!1};#a;#b=0;#d=null;#h=!1;#E=!1;#m=0;#x;#S=dr();#C;#p;#v;#R;#P={scrollTop:0,scrollLeft:0,scrollHeight:0,scrollWidth:0,clientHeight:0,clientWidth:0};#r;#_;#N=!1;#M;#K;#z;#o;#s=Qn();#y;#q;#F=!1;#A=new Set;#H=new Map;#G;#k=new Map;_rows=[];#V=[];get _columns(){return this.#i.columns??[]}set _columns(e){this.#i.columns=e}get _visibleColumns(){return this._columns.filter(e=>!e.hidden)}_headerRowEl;_bodyEl;_rowPool=[];_resizeController;_virtualization={enabled:!0,rowHeight:28,bypassThreshold:24,start:0,end:0,container:null,viewportEl:null,totalHeightEl:null,positionCache:null,heightCache:{byKey:new Map,byRef:new WeakMap},averageHeight:28,measuredCount:0,variableHeights:!1,cachedViewportHeight:0,cachedFauxHeight:0,cachedScrollAreaHeight:0,scrollAreaEl:null};_focusRow=0;_focusCol=0;_restoreFocusAfterRender=!1;_sortState=null;_gridTemplate="";__rowRenderEpoch=0;__didInitialAutoSize=!1;get __lightDomColumnsCache(){return this.#o?.lightDomColumnsCache}set __lightDomColumnsCache(e){this.#o&&(this.#o.lightDomColumnsCache=e)}get __originalColumnNodes(){return this.#o?.originalColumnNodes}set __originalColumnNodes(e){this.#o&&(this.#o.originalColumnNodes=e)}__originalOrder=[];__frameworkAdapter;__rowsBodyEl=null;get rows(){return this._rows}set rows(e){const t=this.#l;this.#l=e,t!==e&&this.#W("rows")}get sourceRows(){return this.#l}get columns(){return[...this._columns]}set columns(e){const t=this.#o?.getColumns();this.#o?.setColumns(e),t!==e&&this.#W("columns")}get gridConfig(){return this.#i}set gridConfig(e){const t=this.#o?.getGridConfig();this.#o?.setGridConfig(e),t!==e&&(this.#o.clearLightDomCache(),this.#W("gridConfig"))}get fitMode(){return this.#i.fitMode??"stretch"}set fitMode(e){const t=this.#o?.getFitMode();this.#o?.setFitMode(e),t!==e&&this.#W("fitMode")}get loading(){return this.#F}set loading(e){const t=this.#F;this.#F=e,e?this.setAttribute("loading",""):this.removeAttribute("loading"),t!==e&&this.#ue()}setRowLoading(e,t){const i=this.#A.has(e);t?this.#A.add(e):this.#A.delete(e),i!==t&&this.#X(e,t)}setCellLoading(e,t,i){let n=this.#H.get(e);const o=n?.has(t)??!1;i?(n||(n=new Set,this.#H.set(e,n)),n.add(t)):(n?.delete(t),n?.size===0&&this.#H.delete(e)),o!==i&&this.#he(e,t,i)}isRowLoading(e){return this.#A.has(e)}isCellLoading(e,t){return this.#H.get(e)?.has(t)??!1}clearAllLoading(){this.loading=!1;for(const e of this.#A)this.#X(e,!1);this.#A.clear();for(const[e,t]of this.#H)for(const i of t)this.#he(e,i,!1);this.#H.clear()}get effectiveConfig(){return this.#i}get disconnectSignal(){return this.#C||(this.#C=new AbortController),this.#C.signal}constructor(){super(),this.#me(),this.#c=new Promise(e=>this.#n=e),this.#a=new Gn({mergeConfig:()=>{this.#o.parseLightDomColumns(this),this.#o.merge(),this.#te(),yr(this.#i,this.#r?.getPlugins()??[]),Cr(this.#r?.getPlugins()??[]),Er(this.#r?.getPlugins()??[]),this.#He(),this.#V=[...this._columns]},processColumns:()=>this.#ke(),processRows:()=>this.#Le(),renderHeader:()=>Le(this),updateTemplate:()=>ue(this),renderVirtualWindow:()=>this.refreshVirtualWindow(!0,!0),afterRender:()=>{this.#r?.afterRender(),this._virtualization.enabled&&this._virtualization.totalHeightEl&&queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const t=this.#L(this._rows.length);this._virtualization.totalHeightEl.style.height=`${t}px`}),this.#i.fitMode==="fixed"&&!this.__didInitialAutoSize&&(this.__didInitialAutoSize=!0,Et(this)),this._restoreFocusAfterRender&&(this._restoreFocusAfterRender=!1,F(this)),this._virtualization.enabled&&!this.#$&&this.#ye(),this.#E&&(this.#E=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.#ve()})})),this.#F&&this.#ue()},isConnected:()=>this.isConnected&&this.#f}),this.#a.setInitialReadyResolver(()=>this.#n?.()),this.#y=nr(this.#s,{getShadow:()=>this.#e,getShellConfig:()=>this.#i?.shell,getAccordionIcons:()=>({expand:this.#i?.icons?.expand??W.expand,collapse:this.#i?.icons?.collapse??W.collapse}),emit:(e,t)=>this.#I(e,t),refreshShellHeader:()=>this.refreshShellHeader()}),this.#o=new bn({getRows:()=>this.#l,getSortState:()=>this._sortState,setSortState:e=>{this._sortState=e},onConfigChange:()=>{this.#a.requestPhase(z.FULL,"configChange")},emit:(e,t)=>this.#I(e,t),clearRowPool:()=>{this._rowPool.length=0,this._bodyEl&&(this._bodyEl.innerHTML=""),this.__rowRenderEpoch++},setup:()=>this.#D(),renderHeader:()=>Le(this),updateTemplate:()=>ue(this),refreshVirtualWindow:()=>this.#a.requestPhase(z.VIRTUALIZATION,"configManager"),getVirtualization:()=>this._virtualization,setRowHeight:e=>{this._virtualization.rowHeight=e},applyAnimationConfig:e=>this.#Pe(e),getShellLightDomTitle:()=>this.#s.lightDomTitle,getShellToolPanels:()=>this.#s.toolPanels,getShellHeaderContents:()=>this.#s.headerContents,getShellToolbarContents:()=>this.#s.toolbarContents,getShellLightDomHeaderContent:()=>this.#s.lightDomHeaderContent,getShellHasToolButtonsContainer:()=>this.#s.hasToolButtonsContainer})}async#me(){await cr(Dr)}getPlugin(e){return this.#r?.getPlugin(e)}getPluginByName(e){return this.#r?.getPluginByName(e)}requestRender(){this.#a.requestPhase(z.ROWS,"plugin:requestRender")}requestColumnsRender(){this.#a.requestPhase(z.COLUMNS,"plugin:requestColumnsRender")}requestRenderWithFocus(){this._restoreFocusAfterRender=!0,this.#a.requestPhase(z.ROWS,"plugin:requestRenderWithFocus")}updateTemplate(){ue(this)}requestAfterRender(){this.#a.requestPhase(z.STYLE,"plugin:requestAfterRender")}#ee(){this.#r=new we(this);const e=this.#i?.plugins,t=Array.isArray(e)?e:[];this.#r.attachAll(t)}#B(){const e=this.#r?.getPluginStyles()??[];lr(e)}#te(){const e=this.#i?.plugins,t=Array.isArray(e)?e:[];if(this.#_===t)return;if(this.#_&&this.#_.length===t.length&&this.#_.every((n,o)=>n===t[o])){this.#_=t;return}this.#r&&this.#r.detachAll();for(const n of this.#s.toolPanels.keys()){const o=this.#s.lightDomToolPanelIds.has(n),s=this.#s.apiToolPanelIds.has(n);if(!o&&!s){const l=this.#s.panelCleanups.get(n);l&&(l(),this.#s.panelCleanups.delete(n)),this.#s.toolPanels.delete(n)}}for(const n of this.#s.headerContents.keys()){const o=this.#s.headerContentCleanups.get(n);o&&(o(),this.#s.headerContentCleanups.delete(n)),this.#s.headerContents.delete(n)}this.#ee(),this.#B(),this.#_=t,this.#oe(),this.#ie();const i=this.#h;if(this.#h=this.#r?.getAll().some(n=>n.onScroll)??!1,!i&&this.#h){const o=this.#e.querySelector(".tbw-grid-content")??this.#e.querySelector(".tbw-grid-root");this.#U(o)}}#be(){this.#r?.detachAll()}#ie(){if(!this.#r)return;const e=this.#r.getToolPanels();for(const{panel:i}of e)this.#s.toolPanels.has(i.id)||this.#s.toolPanels.set(i.id,i);const t=this.#r.getHeaderContents();for(const{content:i}of t)this.#s.headerContents.has(i.id)||this.#s.headerContents.set(i.id,i)}#ne(){const e=V.getAdapters();if(e.length===0&&!this.__frameworkAdapter)return;const t=this.__frameworkAdapter;return i=>{if(t?.createToolPanelRenderer){const n=t.createToolPanelRenderer(i);if(n)return n}for(const n of e)if(n.createToolPanelRenderer){const o=n.createToolPanelRenderer(i);if(o)return o}}}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=0),this.hasAttribute("version")||this.setAttribute("version",V.version),this.id||(this.id=`tbw-grid-${++V.#t}`),this._rows=Array.isArray(this.#l)?[...this.#l]:[],this.#C&&(this.#C.abort(),this.#N=!1),this.#C=new AbortController,this.#R&&(Gt(this.#R),this.#R=void 0),this.#O(),this.#o.parseLightDomColumns(this),this.#o.merge(),this.#ee();const e=this.#i?.plugins;this.#_=Array.isArray(e)?e:[],this.#ie(),this.#u||(this.#J(),this.#B(),this.#u=!0),this.#re(),this.#R=In(()=>{this.#ze()},{timeout:100})}disconnectedCallback(){this.#R&&(Gt(this.#R),this.#R=void 0),this.#m&&(clearTimeout(this.#m),this.#m=0),this.#be(),ir(this.#s),this.#y.setInitialized(!1),this.#q?.(),this.#q=void 0,ei(this.#S),this.#C&&(this.#C.abort(),this.#C=void 0),this.#M?.abort(),this.#M=void 0,this.#N=!1,this._resizeController&&this._resizeController.dispose(),this.#p&&(this.#p.disconnect(),this.#p=void 0),this.#v&&(this.#v.disconnect(),this.#v=void 0,this.#$=!1),Re(this),this.#T.clear(),this.#_=void 0;for(const e of this._rowPool)e.remove();this._rowPool.length=0,this.__rowsBodyEl=null,this.#f=!1}attributeChangedCallback(e,t,i){if(e==="loading"){const n=i!==null&&i!=="false";this.loading!==n&&(this.loading=n);return}if(!(t===i||!i||i==="null"||i==="undefined"))if(e==="rows"||e==="columns"||e==="grid-config")try{const n=JSON.parse(i);e==="rows"?this.rows=n:e==="columns"?this.columns=n:e==="grid-config"&&(this.gridConfig=n)}catch{console.warn(`[tbw-grid] Invalid JSON for '${e}' attribute:`,i)}else e==="fit-mode"&&(this.fitMode=i)}#re(){const t=this.#e.querySelector(".tbw-grid-content")??this.#e.querySelector(".tbw-grid-root");if(this._headerRowEl=t?.querySelector(".header-row"),this._virtualization.totalHeightEl=t?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=t?.querySelector(".rows-viewport"),this._bodyEl=t?.querySelector(".rows"),this.__rowsBodyEl=t?.querySelector(".rows-body"),this.#y.isInitialized){Ve(this.#e,this.#s),Ke(this.#e,this.#i?.shell,this.#s);const n=this.#i?.shell?.toolPanel?.defaultOpen;n&&this.#s.toolPanels.has(n)&&(this.openToolPanel(),this.#s.expandedSections.add(n))}if(this.setAttribute("data-upgraded",""),this.#f=!0,this._resizeController=Bt(this),this.#D(),this.#U(t),this.#N)return;this.#N=!0;const i=this.disconnectSignal;Ln(this,this,this.#e,i),this.#oe(),queueMicrotask(()=>this.#Ce()),this.#a.requestPhase(z.FULL,"afterConnect")}#oe(){const e=this.#i.rowHeight,t=this.#r.hasRowHeightPlugin();typeof e=="function"||t?this._virtualization.variableHeights||(this._virtualization.variableHeights=!0,this._virtualization.rowHeight=typeof e=="number"&&e>0?e:this._virtualization.rowHeight||28,this.#Z(),typeof e!="function"&&(this.#E=!0)):!t&&typeof e!="function"&&this._virtualization.variableHeights?(this._virtualization.variableHeights=!1,this._virtualization.positionCache=null):typeof e=="number"&&e>0?(this._virtualization.rowHeight=e,this._virtualization.variableHeights=!1):requestAnimationFrame(()=>this.#se())}#se(){if(this.#r.hasExtraHeight())return;const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;const t=e.querySelectorAll(".cell");let i=0;t.forEach(s=>{const l=s.offsetHeight;l>i&&(i=l)});const n=e.getBoundingClientRect(),o=Math.max(n.height,i);o>0&&Math.abs(o-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=o,this.#a.requestPhase(z.VIRTUALIZATION,"measureRowHeight"))}#ve(){const e=this._bodyEl?.querySelector(".data-grid-row");if(!e)return;const t=e.querySelectorAll(".cell");let i=0;t.forEach(s=>{const l=s.offsetHeight;l>i&&(i=l)});const n=e.getBoundingClientRect(),o=Math.max(n.height,i);if(o>0&&(Math.abs(o-this._virtualization.rowHeight)>1&&(this._virtualization.rowHeight=o),this.#Z(),this._virtualization.totalHeightEl)){const l=this.#L(this._rows.length);this._virtualization.totalHeightEl.style.height=`${l}px`}}#U(e){this.#M?.abort(),this.#M=new AbortController;const t=this.#M.signal,i=e?.querySelector(".faux-vscroll"),n=e?.querySelector(".rows");if(this._virtualization.container=i??this,this.#h=this.#r?.getAll().some(o=>o.onScroll)??!1,i&&n){i.addEventListener("scroll",()=>{if(!this._virtualization.enabled&&!this.#h)return;const a=i.scrollTop,c=this._virtualization.rowHeight;if(this._rows.length<=this._virtualization.bypassThreshold)n.style.transform=`translateY(${-a}px)`;else{const d=this._virtualization.positionCache;let u,h;if(this._virtualization.variableHeights&&d&&d.length>0){u=ni(d,a),u===-1&&(u=0);const f=u-u%2;h=d[f]?.offset??f*c}else u=Math.floor(a/c),h=(u-u%2)*c;const p=-(a-h);n.style.transform=`translateY(${p}px)`}this.#d=a,this.#b||(this.#b=requestAnimationFrame(()=>{this.#b=0,this.#d!==null&&(this.#Ie(this.#d),this.#d=null)}))},{passive:!0,signal:t});const o=this.#e.querySelector(".tbw-scroll-area");this.#K=o,this._virtualization.scrollAreaEl=o,o&&this.#h&&o.addEventListener("scroll",()=>{const a=this.#P;a.scrollTop=i.scrollTop,a.scrollLeft=o.scrollLeft,a.scrollHeight=i.scrollHeight,a.scrollWidth=o.scrollWidth,a.clientHeight=i.clientHeight,a.clientWidth=o.clientWidth,this.#r?.onScroll(a)},{passive:!0,signal:t});const s=this.#e.querySelector(".tbw-grid-content"),l=this.#K;s&&(s.addEventListener("wheel",a=>{const c=a.shiftKey||Math.abs(a.deltaX)>Math.abs(a.deltaY);if(c&&l){const d=a.shiftKey?a.deltaY:a.deltaX,{scrollLeft:u,scrollWidth:h,clientWidth:p}=l;(d>0&&u<h-p||d<0&&u>0)&&(a.preventDefault(),l.scrollLeft+=d)}else if(!c){const{scrollTop:d,scrollHeight:u,clientHeight:h}=i;(a.deltaY>0&&d<u-h||a.deltaY<0&&d>0)&&(a.preventDefault(),i.scrollTop+=a.deltaY)}},{passive:!1,signal:t}),wr(s,this.#S,{fauxScrollbar:i,scrollArea:l},t))}this._bodyEl&&Tn(this,this._bodyEl,t),this.#p?.disconnect(),this._virtualization.viewportEl&&(this.#p=new ResizeObserver(()=>{this.#Fe(),this.#a.requestPhase(z.VIRTUALIZATION,"resize-observer")}),this.#p.observe(this._virtualization.viewportEl)),this.#e.addEventListener("focusin",()=>{this.dataset.hasFocus=""},{signal:t}),this.#e.addEventListener("focusout",o=>{const s=o.relatedTarget;(!s||!this.#e.contains(s))&&delete this.dataset.hasFocus},{signal:t})}#$=!1;#ye(){if(this.#$)return;const e=this._bodyEl?.querySelector(".data-grid-row");e&&(this.#$=!0,this.#v?.disconnect(),this.#v=new ResizeObserver(()=>{this.#se()}),this.#v.observe(e))}addEventListener(e,t,i){super.addEventListener(e,t,i)}removeEventListener(e,t,i){super.removeEventListener(e,t,i)}#I(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}#Ce(){this._bodyEl?.querySelectorAll(".data-grid-row")?.forEach((t,i)=>{const n=i===this._focusRow;t.setAttribute("aria-selected",String(n)),t.querySelectorAll(".cell").forEach((o,s)=>{o.setAttribute("aria-selected",String(n&&s===this._focusCol))})})}#W(e){this.#g[e]=!0,!this.#w&&(this.#w=!0,queueMicrotask(()=>this.#xe()))}#xe(){if(!this.#w||!this.#f){this.#w=!1;return}const e=this.#g;if(this.#w=!1,this.#g={rows:!1,columns:!1,gridConfig:!1,fitMode:!1},e.gridConfig){this.#_e(),e.rows&&this.#le();return}e.columns&&this.#Re(),e.rows&&this.#le(),e.fitMode&&this.#Se()}#le(){this._rows=Array.isArray(this.#l)?[...this.#l]:[],this.#j(),this.#a.requestPhase(z.ROWS,"applyRowsUpdate")}#j(){this.#k.clear();const e=this.#i.getRowId;this._rows.forEach((t,i)=>{const n=this.#ae(t,e);n!==void 0&&this.#k.set(n,{row:t,index:i})})}#ae(e,t){if(t)return t(e);const i=e;if("id"in i&&i.id!=null)return String(i.id);if("_id"in i&&i._id!=null)return String(i._id)}#Ee(e,t){const i=this.#ae(e,t);if(i===void 0)throw new Error('[tbw-grid] Cannot determine row ID. Configure getRowId in gridConfig or ensure rows have an "id" property.');return i}#Re(){Re(this),this.#o.merge(),this.#D()}#Se(){this.#o.merge(),this.#i.fitMode==="fixed"?(this.__didInitialAutoSize=!1,Et(this)):(this._columns.forEach(t=>{!t.__userResized&&t.__autoSized&&delete t.width}),ue(this))}#_e(){jt(this,this.#s),Yt(this,this.#s);const e=!!this.#e.querySelector(".has-shell"),t=!!this.#e.querySelector(".tbw-tool-panel"),i=this.#e.querySelectorAll(".tbw-accordion-section").length;this.#o.parseLightDomColumns(this),this.#o.merge(),this.#te(),Xt(this,this.#s,this.#ne()),this.#o.markSourcesChanged(),this.#o.merge();const n=Ut(this.#i?.shell),o=(this.#i?.shell?.toolPanels?.length??0)>0,s=this.#i?.shell?.toolPanels?.length??0;if(e!==n||!t&&o||t&&s!==i){Ue(this.#s),this.#J(),this.#B(),this.#re(),this.#j();return}e&&this.#Ae(),this.#j(),this.#a.requestPhase(z.COLUMNS,"applyGridConfigUpdate")}#Ae(){const e=this.#e.querySelector(".tbw-shell-header");if(!e)return;const t=this.#i.shell?.header?.title??this.#s.lightDomTitle;let i=e.querySelector(".tbw-shell-title");t?(i||(i=document.createElement("h2"),i.className="tbw-shell-title",i.setAttribute("part","shell-title"),e.insertBefore(i,e.firstChild)),i.textContent=t):i&&i.remove()}#ke(){if(this.#r){const e=this.#V.length>0?this.#V:this._columns,t=e.filter(o=>!o.hidden),i=e.filter(o=>o.hidden),n=this.#r.processColumns([...t]);if(n!==t){const o=new Set(n.map(l=>l.field));!t.some(l=>o.has(l.field))&&n.length>0?this._columns=[...n,...i]:this._columns=this.#Te(e,n,i)}else this._columns=[...e]}}#Te(e,t,i){if(i.length===0)return t;const n=new Map;for(const a of t)n.set(a.field,a);const o=new Set(e.map(a=>a.field)),s=[];for(const a of t)o.has(a.field)||s.push(a);const l=[];for(const a of e){const c=n.get(a.field);c?l.push(c):a.hidden&&l.push(a)}return l.push(...s),l}#Le(){Re(this);const e=Array.isArray(this.#l)?[...this.#l]:[],t=this.#r?.processRows(e)??e;this._rows=t,this._virtualization.variableHeights&&this.#Z()}#Pe(e){const t={...vt,...e.animation},i=t.mode??"reduced-motion";let n=1;i===!1||i==="off"?n=0:(i===!0||i==="on")&&(n=1),this.style.setProperty("--tbw-animation-duration",`${t.duration}ms`),this.style.setProperty("--tbw-animation-easing",t.easing??"ease-out"),this.style.setProperty("--tbw-animation-enabled",String(n)),this.dataset.animationMode=typeof i=="boolean"?i?"on":"off":i}#Y(e,t,i=this.__rowRenderEpoch){if(this.#x||(this.#x=(n,o,s)=>this.#r?.renderRow(n,o,s)??!1),En(this,e,t,i,this.#x),this.#A.size>0)for(const n of this.#A)this.#X(n,!0)}#ce=de();#de(e,t){Zi(this.#ce,this.__rowsBodyEl,this._bodyEl,e,t)}#He(){en(this.#ce,this.__rowsBodyEl,this.#i,this.#s)}#ue(){const e=this.querySelector(".tbw-grid-root");e&&(this.#F?(this.#G||(this.#G=zn(this.#i?.loadingRenderer)),Fn(e,this.#G)):On(this.#G))}#X(e,t){const i=this.#k.get(e);if(!i)return;const n=this.findRenderedRowElement?.(i.index);n&&Nn(n,t)}#he(e,t,i){const n=this.#k.get(e);if(!n)return;const o=this.findRenderedRowElement?.(n.index);if(!o)return;const s=this._visibleColumns.findIndex(a=>a.field===t);if(s<0)return;const l=o.children[s];l&&qn(l,i)}#D(){if(this.isConnected&&!(!this._headerRowEl||!this._bodyEl)){if(this.#o.parseLightDomColumns(this),this.#z){const e=this.#z;this.#z=void 0,this.#o.merge();const t=this.#r?.getAll()??[];this.#o.applyState(e,t)}this._bodyEl&&(this._bodyEl.style.display="",this._bodyEl.style.gridTemplateColumns=""),this.#a.requestPhase(z.FULL,"setup")}}#Ie(e){let t=0,i=0,n=0,o=0,s=0;if(this.#h){const a=this._virtualization.container,c=this.#K;t=c?.scrollLeft??0,i=a?.scrollHeight??0,n=c?.scrollWidth??0,o=a?.clientHeight??0,s=c?.clientWidth??0}if(this.refreshVirtualWindow(!1)&&this.#r?.onScrollRender(),this._virtualization.variableHeights&&(this.#m&&clearTimeout(this.#m),this.#m=window.setTimeout(()=>{this.#m=0,this.#pe(this._virtualization.start,this._virtualization.end)},100)),this.#h){const a=this.#P;a.scrollTop=e,a.scrollLeft=t,a.scrollHeight=i,a.scrollWidth=n,a.clientHeight=o,a.clientWidth=s,this.#r?.onScroll(a)}}findHeaderRow(){return this.#e.querySelector(".header-row")}findRenderedRowElement(e){return Array.from(this._bodyEl.querySelectorAll(".data-grid-row")).find(t=>{const i=t.querySelector(".cell[data-row]");return i&&Number(i.getAttribute("data-row"))===e})||null}_dispatchCellClick(e,t,i,n){const o=this._rows[t],s=this._columns[i];if(!o||!s)return!1;const l=s.field,a=o[l],c=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,composed:!0,detail:{rowIndex:t,colIndex:i,field:l,value:a,row:o,cellEl:n,trigger:"pointer",originalEvent:e}});if(this.dispatchEvent(c),c.defaultPrevented)return!0;const d={row:o,rowIndex:t,colIndex:i,field:l,value:a,cellEl:n,originalEvent:e},u=this.#r?.onCellClick(d)??!1;return this.#I("cell-click",d),u}_dispatchRowClick(e,t,i,n){if(!i)return!1;const o={rowIndex:t,row:i,rowEl:n,originalEvent:e},s=this.#r?.onRowClick(o)??!1;return this.#I("row-click",o),s}_dispatchHeaderClick(e,t,i){const n=this._columns[t];if(!n)return!1;const o={colIndex:t,field:n.field,column:n,headerEl:i,originalEvent:e};return this.#r?.onHeaderClick(o)??!1}_dispatchKeyDown(e){return this.#r?.onKeyDown(e)??!1}_getHorizontalScrollOffsets(e,t){return this.#r?.getHorizontalScrollOffsets(e,t)??{left:0,right:0}}queryPlugins(e){return this.#r?.queryPlugins(e)??[]}query(e,t){return this.#r?.queryPlugins({type:e,context:t})??[]}_dispatchCellMouseDown(e){return this.#r?.onCellMouseDown(e)??!1}_dispatchCellMouseMove(e){this.#r?.onCellMouseMove(e)}_dispatchCellMouseUp(e){this.#r?.onCellMouseUp(e)}_afterCellRender(e){this.#r?.afterCellRender(e)}_hasAfterCellRenderHook(){return this.#r?.hasAfterCellRenderHook()??!1}_afterRowRender(e){this.#r?.afterRowRender(e)}_hasAfterRowRenderHook(){return this.#r?.hasAfterRowRenderHook()??!1}async ready(){return this.#c}async forceLayout(){return this.#a.requestPhase(z.FULL,"forceLayout"),this.#a.whenReady()}async getConfig(){return Object.freeze({...this.#i||{}})}getRowId(e){return this.#Ee(e,this.#i.getRowId)}getRow(e){return this.#k.get(e)?.row}updateRow(e,t,i="api"){const n=this.#k.get(e);if(!n)throw new Error(`[tbw-grid] Row with ID "${e}" not found. Ensure the row exists and getRowId is correctly configured.`);const{row:o,index:s}=n,l=[];for(const[a,c]of Object.entries(t)){const d=o[a];d!==c&&(l.push({field:a,oldValue:d,newValue:c}),o[a]=c)}for(const{field:a,oldValue:c,newValue:d}of l)this.#I("cell-change",{row:o,rowId:e,rowIndex:s,field:a,oldValue:c,newValue:d,changes:t,source:i});l.length>0&&this.#a.requestPhase(z.ROWS,"updateRow")}updateRows(e,t="api"){let i=!1;for(const{id:n,changes:o}of e){const s=this.#k.get(n);if(!s)throw new Error(`[tbw-grid] Row with ID "${n}" not found. Ensure the row exists and getRowId is correctly configured.`);const{row:l,index:a}=s;for(const[c,d]of Object.entries(o)){const u=l[c];u!==d&&(i=!0,l[c]=d,this.#I("cell-change",{row:l,rowId:n,rowIndex:a,field:c,oldValue:u,newValue:d,changes:o,source:t}))}}i&&this.#a.requestPhase(z.ROWS,"updateRows")}animateRow(e,t){We(this,e,t)}animateRows(e,t){Un(this,e,t)}animateRowById(e,t){return jn(this,e,t)}setColumnVisible(e,t){const i=this.#o.setColumnVisible(e,t);return i&&this.requestStateChange(),i}toggleColumnVisibility(e){const t=this.#o.toggleColumnVisibility(e);return t&&this.requestStateChange(),t}isColumnVisible(e){return this.#o.isColumnVisible(e)}showAllColumns(){this.#o.showAllColumns(),this.requestStateChange()}getAllColumns(){return this.#o.getAllColumns()}setColumnOrder(e){this.#o.setColumnOrder(e),this.requestStateChange()}getColumnOrder(){return this.#o.getColumnOrder()}getColumnState(){const e=this.#r?.getAll()??[];return this.#o.collectState(e)}set columnState(e){e&&(this.#z=e,this.#o.initialColumnState=e,this.#u&&this.#De(e))}get columnState(){return this.getColumnState()}#De(e){const t=this.#r?.getAll()??[];this.#o.applyState(e,t),this.#D()}requestStateChange(){const e=this.#r?.getAll()??[];this.#o.requestStateChange(e)}resetColumnState(){this.#z=void 0,this.__originalOrder=[];const e=this.#r?.getAll()??[];this.#o.resetState(e),this.#o.merge(),this.#D()}get isToolPanelOpen(){return this.#y.isPanelOpen}get defaultRowHeight(){return this._virtualization.rowHeight}get expandedToolPanelSections(){return this.#y.expandedSections}openToolPanel(){this.#y.openToolPanel()}closeToolPanel(){this.#y.closeToolPanel()}toggleToolPanel(){this.#y.toggleToolPanel()}toggleToolPanelSection(e){this.#y.toggleToolPanelSection(e)}getToolPanels(){return this.#y.getToolPanels()}registerToolPanel(e){this.#s.apiToolPanelIds.add(e.id),this.#y.registerToolPanel(e)}unregisterToolPanel(e){this.#s.apiToolPanelIds.delete(e),this.#y.unregisterToolPanel(e)}getHeaderContents(){return this.#y.getHeaderContents()}registerHeaderContent(e){this.#y.registerHeaderContent(e)}unregisterHeaderContent(e){this.#y.unregisterHeaderContent(e)}getToolbarContents(){return this.#y.getToolbarContents()}registerToolbarContent(e){this.#y.registerToolbarContent(e)}unregisterToolbarContent(e){this.#y.unregisterToolbarContent(e)}#Q=!1;refreshShellHeader(){this.#Q||(this.#Q=!0,queueMicrotask(()=>{this.#Q=!1,this.isConnected&&(this.#O(),this.#o.markSourcesChanged(),this.#o.merge(),Ue(this.#s),this.#J(),this.#B(),this.#Me())}))}#Me(){const t=this.#e.querySelector(".tbw-grid-content")??this.#e.querySelector(".tbw-grid-root");if(this._headerRowEl=t?.querySelector(".header-row"),this._virtualization.totalHeightEl=t?.querySelector(".faux-vscroll-spacer"),this._virtualization.viewportEl=t?.querySelector(".rows-viewport"),this._bodyEl=t?.querySelector(".rows"),this.__rowsBodyEl=t?.querySelector(".rows-body"),this.#y.isInitialized){Ve(this.#e,this.#s),Ke(this.#e,this.#i?.shell,this.#s);const i=this.#i?.shell?.toolPanel?.defaultOpen;i&&this.#s.toolPanels.has(i)&&(this.openToolPanel(),this.#s.expandedSections.add(i))}this._resizeController=Bt(this),this.#U(t),this.#a.requestPhase(z.COLUMNS,"shellRefresh")}#T=new Map;registerStyles(e,t){let i=this.#T.get(e);i||(i=new CSSStyleSheet,this.#T.set(e,i)),i.replaceSync(t),this.#fe()}unregisterStyles(e){this.#T.delete(e)&&this.#fe()}getRegisteredStyles(){return Array.from(this.#T.keys())}#fe(){const e=Array.from(this.#T.values()),t=document.adoptedStyleSheets.filter(i=>!Array.from(this.#T.values()).includes(i));document.adoptedStyleSheets=[...t,...e]}#O(){jt(this,this.#s),Yt(this,this.#s),Xt(this,this.#s,this.#ne())}#ge(){const e=this.#e.querySelector(".tbw-shell-header");if(!e)return;Ue(this.#s);const t=Zn(this.#i.shell,this.#s,this.#i.icons?.toolPanel),i=document.createElement("div");i.innerHTML=t;const n=i.firstElementChild;n&&(e.replaceWith(n),this.#we(),Ke(this.#e,this.#i?.shell,this.#s))}#ze(){const e=()=>{const i=this.#s.lightDomTitle,n=this.#s.hasToolButtonsContainer;this.#O();const o=this.#s.lightDomTitle,s=this.#s.hasToolButtonsContainer;(o&&!i||s&&!n)&&(this.#o.markSourcesChanged(),this.#o.merge(),this.#ge())},t=()=>{this.__lightDomColumnsCache=void 0,this.#D()};this.#o.registerLightDomHandler("tbw-grid-header",e),this.#o.registerLightDomHandler("tbw-grid-tool-buttons",e),this.#o.registerLightDomHandler("tbw-grid-tool-panel",e),this.#o.registerLightDomHandler("tbw-grid-column",t),this.#o.registerLightDomHandler("tbw-grid-detail",t),this.#o.observeLightDOM(this)}refreshColumns(){this.__lightDomColumnsCache=void 0,Re(this),this.#o.parseLightDomColumns(this);const e=this.#s.lightDomTitle,t=this.#s.hasToolButtonsContainer;this.#O();const i=this.#s.lightDomTitle,n=this.#s.hasToolButtonsContainer;(i&&!e||n&&!t)&&(this.#o.markSourcesChanged(),this.#o.merge(),this.#ge()),this.#a.requestPhase(z.COLUMNS,"refreshColumns")}#Fe(){const e=this._virtualization.container,t=this._virtualization.viewportEl??e;t&&(this._virtualization.cachedViewportHeight=t.clientHeight),e&&(this._virtualization.cachedFauxHeight=e.clientHeight);const i=this._virtualization.scrollAreaEl;i&&(this._virtualization.cachedScrollAreaHeight=i.clientHeight)}#L(e,t=!1){const i=this._virtualization;let n,o,s;if(t){const h=i.container??this,p=i.viewportEl??h,f=i.scrollAreaEl;n=h.clientHeight,o=p.clientHeight,s=f?f.clientHeight:n,i.cachedFauxHeight=n,i.cachedViewportHeight=o,i.cachedScrollAreaHeight=s}else n=i.cachedFauxHeight,o=i.cachedViewportHeight,s=i.cachedScrollAreaHeight||n;const l=s-o,a=Math.max(0,n-s);let c,d=0;return i.variableHeights&&i.positionCache?c=Ar(i.positionCache):(c=e*i.rowHeight,d=this.#r?.getExtraHeight()??0),c+l+d+a}#Z(){if(!this._virtualization.variableHeights)return;const e=this._rows,t=this._virtualization.rowHeight||28,i=this.#i.rowHeight,n=this.#i.getRowId,o=n?l=>n(l):void 0;this._virtualization.positionCache=_r(e,this._virtualization.heightCache,t,{rowId:o},(l,a)=>{const c=this.#r?.getRowHeight?.(l,a);if(c!==void 0)return c;if(i){const d=i(l,a);if(d!==void 0&&d>0)return d}});const s=Pr(this._virtualization.positionCache,e,t,(l,a)=>this.#r?.getRowHeight?.(l,a));this._virtualization.measuredCount=s.measuredCount,s.measuredCount>0&&(this._virtualization.averageHeight=s.averageHeight)}invalidateRowHeight(e,t){if(!this._virtualization.variableHeights||!this._virtualization.positionCache||e<0||e>=this._rows.length)return;const i=this._virtualization.positionCache,n=this._rows[e];let o=t;o===void 0&&(o=this.#r?.getRowHeight?.(n,e)),o===void 0&&(o=this._virtualization.rowHeight);const s=i[e];if(!(!s||Math.abs(s.height-o)<1)&&(Ze(i,e,o),this._virtualization.totalHeightEl)){const l=this.#L(this._rows.length);this._virtualization.totalHeightEl.style.height=`${l}px`}}#pe(e,t){if(!this._virtualization.variableHeights||!this._virtualization.positionCache||!this._bodyEl)return;const i=this._bodyEl.querySelectorAll(".data-grid-row"),n=this.#i.getRowId,o=Lr({positionCache:this._virtualization.positionCache,heightCache:this._virtualization.heightCache,rows:this._rows,defaultHeight:this._virtualization.rowHeight,start:e,end:t,getPluginHeight:(s,l)=>this.#r?.getRowHeight?.(s,l),getRowId:n?s=>n(s):void 0},i);if(o.hasChanges&&(this._virtualization.measuredCount=o.measuredCount,this._virtualization.averageHeight=o.averageHeight,this._virtualization.totalHeightEl)){const s=this.#L(this._rows.length);this._virtualization.totalHeightEl.style.height=`${s}px`}}refreshVirtualWindow(e=!1,t=!1){if(!this._bodyEl)return!1;const i=this._rows.length;if(!this._virtualization.enabled)return this.#Y(0,i),t||this.#r?.afterRender(),!0;if(this._rows.length<=this._virtualization.bypassThreshold)return this._virtualization.start=0,this._virtualization.end=i,e&&(this._bodyEl.style.transform="translateY(0px)"),this.#Y(0,i,e?++this.__rowRenderEpoch:this.__rowRenderEpoch),e&&this._virtualization.totalHeightEl&&(this._virtualization.totalHeightEl.style.height=`${this.#L(i,!0)}px`),this.#de(i,this._visibleColumns.length),t||this.#r?.afterRender(),!0;const n=this._virtualization.container??this,o=this._virtualization.viewportEl??n,s=e?this._virtualization.cachedViewportHeight=o.clientHeight:this._virtualization.cachedViewportHeight||(this._virtualization.cachedViewportHeight=o.clientHeight),l=this._virtualization.rowHeight,a=n.scrollTop;let c;const d=this._virtualization.positionCache;if(this._virtualization.variableHeights&&d&&d.length>0)c=ni(d,a),c===-1&&(c=0);else{c=Math.floor(a/l);let v=0;const A=10;for(;v<A;){const L=this.#r?.getExtraHeightBefore?.(c)??0,_=Math.floor((a-L)/l);if(_>=c||_<0)break;c=_,v++}}c=c-c%2,c<0&&(c=0);const u=this.#r?.adjustVirtualStart(c,a,l);u!==void 0&&u<c&&(c=u,c=c-c%2,c<0&&(c=0));let h;if(this._virtualization.variableHeights&&d&&d.length>0){const v=s+l*3;let A=0;for(h=c;h<i&&A<v;)A+=d[h].height,h++;const L=Math.ceil(s/l)+3;h-c<L&&(h=Math.min(c+L,i))}else{const v=Math.ceil(s/l)+3;h=c+v}h>i&&(h=i);const p=this._virtualization.start,f=this._virtualization.end;if(!e&&c===p&&h===f)return!1;this._virtualization.start=c,this._virtualization.end=h;const g=e?this._virtualization.cachedFauxHeight=n.clientHeight:this._virtualization.cachedFauxHeight||(this._virtualization.cachedFauxHeight=n.clientHeight);if(e){const v=this._virtualization.scrollAreaEl;v&&(this._virtualization.cachedScrollAreaHeight=v.clientHeight)}if(g===0&&s>0)return this.#a.requestPhase(z.VIRTUALIZATION,"stale-refs-retry"),!1;if(e&&this._virtualization.totalHeightEl){const v=this.#L(i);this._virtualization.totalHeightEl.style.height=`${v}px`}let w;if(this._virtualization.variableHeights&&d&&d[c])w=d[c].offset;else{const v=this.#r?.getExtraHeightBefore?.(c)??0;w=c*l+v}const b=-(a-w);return this._bodyEl.style.transform=`translateY(${b}px)`,this.#Y(c,h,e?++this.__rowRenderEpoch:this.__rowRenderEpoch),e&&this._virtualization.variableHeights&&this.#pe(c,h),this.#de(i,this._visibleColumns.length),e&&!t&&(this.#r?.afterRender(),queueMicrotask(()=>{if(!this._virtualization.totalHeightEl)return;const v=this.#L(i);this._virtualization.cachedFauxHeight===0&&this._virtualization.cachedViewportHeight>0||(this._virtualization.totalHeightEl.style.height=`${v}px`)})),!0}#J(){this.#O(),this.#o.markSourcesChanged(),this.#o.merge();const e=this.#i?.shell;or(this.#e,e,{isPanelOpen:this.#s.isPanelOpen,expandedSections:this.#s.expandedSections},this.#i?.icons)&&(this.#we(),this.#y.setInitialized(!0))}#we(){Jn(this.#e,this.#i?.shell,this.#s,{onPanelToggle:()=>this.toggleToolPanel(),onSectionToggle:e=>this.toggleToolPanelSection(e)}),this.#q?.(),this.#q=er(this.#e,this.#i?.shell,e=>{this.style.setProperty("--tbw-tool-panel-width",`${e}px`)})}}customElements.get(V.tagName)||customElements.define(V.tagName,V),globalThis.DataGridElement=V;const Mr={CAN_MOVE_COLUMN:"canMoveColumn",GET_CONTEXT_MENU_ITEMS:"getContextMenuItems"};class M{static dependencies;static manifest;version=typeof __GRID_VERSION__<"u"?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#t;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}attach(e){this.#t?.abort(),this.#t=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#t?.abort(),this.#t=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const i=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(i),i.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid}get disconnectSignal(){return this.#t?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...W,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(e===!1||e==="off")return!1;if(e===!0||e==="on")return!0;const t=this.gridElement;return t?getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()!=="0":!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),i=parseInt(t,10);if(!isNaN(i))return i}return 200}resolveIcon(e,t){return t!==void 0?t:this.gridIcons[e]}setIcon(e,t){typeof t=="string"?e.innerHTML=t:t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}warn(e){console.warn(`[tbw-grid:${this.name}] ${e}`)}}const O={ROOT:"tbw-grid-root",HEADER:"header",HEADER_ROW:"header-row",HEADER_CELL:"header-cell",ROWS_VIEWPORT:"rows-viewport",ROWS_SPACER:"rows-spacer",ROWS_CONTAINER:"rows",DATA_ROW:"data-row",GROUP_ROW:"group-row",DATA_CELL:"data-cell",SELECTED:"selected",FOCUSED:"focused",EDITING:"editing",EXPANDED:"expanded",COLLAPSED:"collapsed",DRAGGING:"dragging",RESIZING:"resizing",SORTABLE:"sortable",SORTED_ASC:"sorted-asc",SORTED_DESC:"sorted-desc",HIDDEN:"hidden",STICKY_LEFT:"sticky-left",STICKY_RIGHT:"sticky-right",PINNED_TOP:"pinned-top",PINNED_BOTTOM:"pinned-bottom",TREE_TOGGLE:"tree-toggle",TREE_INDENT:"tree-indent",GROUP_TOGGLE:"group-toggle",GROUP_LABEL:"group-label",GROUP_COUNT:"group-count",RANGE_SELECTION:"range-selection",SELECTION_OVERLAY:"selection-overlay"},me={ROW_INDEX:"data-row-index",COL_INDEX:"data-col-index",FIELD:"data-field",GROUP_KEY:"data-group-key",TREE_LEVEL:"data-tree-level",STICKY:"data-sticky"},zr={ROOT:`.${O.ROOT}`,HEADER:`.${O.HEADER}`,HEADER_ROW:`.${O.HEADER_ROW}`,HEADER_CELL:`.${O.HEADER_CELL}`,ROWS_VIEWPORT:`.${O.ROWS_VIEWPORT}`,ROWS_CONTAINER:`.${O.ROWS_CONTAINER}`,DATA_ROW:`.${O.DATA_ROW}`,DATA_CELL:`.${O.DATA_CELL}`,GROUP_ROW:`.${O.GROUP_ROW}`,ROW_BY_INDEX:r=>`.${O.DATA_ROW}[${me.ROW_INDEX}="${r}"]`,CELL_BY_FIELD:r=>`.${O.DATA_CELL}[${me.FIELD}="${r}"]`,CELL_AT:(r,e)=>`.${O.DATA_ROW}[${me.ROW_INDEX}="${r}"] .${O.DATA_CELL}[${me.COL_INDEX}="${e}"]`,SELECTED_ROWS:`.${O.DATA_ROW}.${O.SELECTED}`,EDITING_CELL:`.${O.DATA_CELL}.${O.EDITING}`},Fr={COLOR_BG:"--tbw-color-bg",COLOR_FG:"--tbw-color-fg",COLOR_FG_MUTED:"--tbw-color-fg-muted",COLOR_BORDER:"--tbw-color-border",COLOR_ACCENT:"--tbw-color-accent",COLOR_HEADER_BG:"--tbw-color-header-bg",COLOR_HEADER_FG:"--tbw-color-header-fg",COLOR_SELECTION:"--tbw-color-selection",COLOR_ROW_HOVER:"--tbw-color-row-hover",COLOR_ROW_ALT:"--tbw-color-row-alt",ROW_HEIGHT:"--tbw-row-height",HEADER_HEIGHT:"--tbw-header-height",CELL_PADDING:"--tbw-cell-padding",FONT_FAMILY:"--tbw-font-family",FONT_SIZE:"--tbw-font-size",BORDER_RADIUS:"--tbw-border-radius",FOCUS_OUTLINE:"--tbw-focus-outline"};function Or(r){const e=document.createElement("tbw-grid");return r&&(e.gridConfig=r),e}function Nr(r,e=document){return e.querySelector(r)}const qr={CELL_CHANGE:"cell-change",CELL_COMMIT:"cell-commit",ROW_COMMIT:"row-commit",EDIT_OPEN:"edit-open",EDIT_CLOSE:"edit-close",CHANGED_ROWS_RESET:"changed-rows-reset",MOUNT_EXTERNAL_VIEW:"mount-external-view",MOUNT_EXTERNAL_EDITOR:"mount-external-editor",SORT_CHANGE:"sort-change",COLUMN_RESIZE:"column-resize",ACTIVATE_CELL:"activate-cell",CELL_ACTIVATE:"cell-activate",GROUP_TOGGLE:"group-toggle",COLUMN_STATE_CHANGE:"column-state-change"},Gr={SELECTION_CHANGE:"selection-change",TREE_EXPAND:"tree-expand",FILTER_CHANGE:"filter-change",SORT_MODEL_CHANGE:"sort-model-change",EXPORT_START:"export-start",EXPORT_COMPLETE:"export-complete",CLIPBOARD_COPY:"clipboard-copy",CLIPBOARD_PASTE:"clipboard-paste",CONTEXT_MENU_OPEN:"context-menu-open",CONTEXT_MENU_CLOSE:"context-menu-close",HISTORY_CHANGE:"history-change",SERVER_LOADING:"server-loading",SERVER_ERROR:"server-error",COLUMN_VISIBILITY_CHANGE:"column-visibility-change",COLUMN_REORDER:"column-reorder",DETAIL_EXPAND:"detail-expand",GROUP_EXPAND:"group-expand"};function Ie(r,e,t=!0){let i=r;if(t&&(i=i.filter(n=>!n.hidden&&!n.field.startsWith("__")&&n.meta?.utility!==!0)),e?.length){const n=new Set(e);i=i.filter(o=>n.has(o.field))}return i}function Je(r,e){return e?.length?[...e].sort((t,i)=>t-i).map(t=>r[t]).filter(t=>t!=null):r}function Br(r){return r==null?"":r instanceof Date?r.toISOString():typeof r=="object"?JSON.stringify(r):String(r)}async function $r(r){try{return await navigator.clipboard.writeText(r),!0}catch(e){console.warn("[copyToClipboard] Clipboard API failed:",e);const t=document.createElement("textarea");t.value=r,t.style.position="fixed",t.style.opacity="0",t.style.pointerEvents="none",document.body.appendChild(t),t.select();const i=document.execCommand("copy");return document.body.removeChild(t),i}}function ri(r,e){const t=e.delimiter??" ",i=e.newline??`
|
|
91
91
|
`,n=r.replace(/\r\n/g,`
|
|
92
92
|
`).replace(/\r/g,`
|
|
93
93
|
`),o=[];let s=[],l="",a=!1;for(let c=0;c<n.length;c++){const d=n[c];d==='"'&&!a?a=!0:d==='"'&&a?n[c+1]==='"'?(l+='"',c++):a=!1:d===t&&!a?(s.push(l),l=""):d===i&&!a?(s.push(l),l="",(s.length>1||s.some(u=>u.trim()!==""))&&o.push(s),s=[]):l+=d}return s.push(l),(s.length>1||s.some(c=>c.trim()!==""))&&o.push(s),o}async function Wr(){try{return await navigator.clipboard.readText()}catch{return""}}function oi(r,e){const{rows:t,target:i,fields:n}=r;if(!i)return;const o=e.rows,s=e.effectiveConfig.columns??[],l=s.map(u=>u.field),a=new Map;s.forEach(u=>{a.set(u.field,u.editable===!0)});const c=[...o],d=i.bounds?i.bounds.endRow:1/0;t.forEach((u,h)=>{const p=i.row+h;if(!(p>d)){if(i.bounds){if(p>=c.length)return}else for(;p>=c.length;){const f={};l.forEach(g=>f[g]=""),c.push(f)}c[p]={...c[p]},u.forEach((f,g)=>{const w=n[g];w&&a.get(w)&&(c[p][w]=f)})}}),e.rows=c}class Kr extends M{static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:" ",newline:`
|
|
94
|
-
`,quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e),e.addEventListener("paste",
|
|
94
|
+
`,quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e),e.addEventListener("paste",i=>this.#e(i),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(e){return(e.ctrlKey||e.metaKey)&&e.key==="c"?(e.preventDefault(),this.#t(e.target),!0):!1}#t(e){const t=this.#c();if(t&&t.ranges.length===0){const i=this.#i(e);if(!i)return;const n=this.columns[i.col];if(!n)return;this.copy({rowIndices:[i.row],columns:[n.field]});return}this.copy()}#e(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const i=ri(t,this.config),n=this.#c(),o=n?.ranges?.[0],s=o?.from.row??0,l=o?.from.col??0,c=o&&(n?.mode==="range"||n?.mode==="row")&&(o.from.row!==o.to.row||o.from.col!==o.to.col)?{endRow:o.to.row,endCol:o.to.col}:null,d=c?.endCol??this.columns.length-1,u=this.columns[l],h=u?{row:s,col:l,field:u.field,bounds:c}:null,p=[],f=i[0]?.length??0;for(let w=0;w<f&&l+w<=d;w++){const b=this.columns[l+w];b&&!b.hidden&&p.push(b.field)}const g={rows:i,text:t,target:h,fields:p};this.emit("paste",g),this.#u(g)}#u(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(t===null)return;(t??oi)(e,this.grid)}#c(){return this.grid?.query("getSelection")?.[0]}#n(e){const t=this.#c();let i;if(e?.columns)i=Ie(this.columns,e.columns);else if(t?.ranges.length&&t.mode!=="row"){const o=t.ranges[t.ranges.length-1],s=Math.min(o.from.col,o.to.col),l=Math.max(o.from.col,o.to.col);i=Ie(this.columns.slice(s,l+1))}else i=Ie(this.columns);let n;if(e?.rowIndices)n=Je(this.rows,e.rowIndices);else if(t?.ranges.length){const o=t.ranges[t.ranges.length-1],s=Math.min(o.from.row,o.to.row),l=Math.max(o.from.row,o.to.row);n=[];for(let a=s;a<=l;a++){const c=this.rows[a];c&&n.push(c)}}else n=this.rows;return{columns:i,rows:n}}#l(e,t,i){const n=i?.delimiter??this.config.delimiter??" ",o=i?.newline??this.config.newline??`
|
|
95
95
|
`,s=i?.includeHeaders??this.config.includeHeaders??!1,l=i?.processCell??this.config.processCell,a=[];s&&a.push(e.map(c=>c.header||c.field).join(n));for(const c of t){const d=e.map(u=>{const h=c[u.field];return l?l(h,u.field,c):Br(h)});a.push(d.join(n))}return a.join(o)}#i(e){const t=e.closest("[data-field-cache]");if(!t)return null;const i=t.dataset.fieldCache,n=t.dataset.row;if(!i||!n)return null;const o=parseInt(n,10);if(isNaN(o))return null;const s=this.columns.findIndex(l=>l.field===i);return s===-1?null:{row:o,col:s}}getSelectionAsText(e){const{columns:t,rows:i}=this.#n(e);return t.length===0||i.length===0?"":this.#l(t,i,e)}async copy(e){const{columns:t,rows:i}=this.#n(e);if(t.length===0||i.length===0)return"";const n=this.#l(t,i,e);return await $r(n),this.lastCopied={text:n,timestamp:Date.now()},this.emit("copy",{text:n,rowCount:i.length,columnCount:t.length}),n}async copyRows(e,t){return e.length===0?"":this.copy({...t,rowIndices:e})}async paste(){const e=await Wr();return e?ri(e,this.config):null}getLastCopied(){return this.lastCopied}}const si=100;function et(r){if(r==null)return si;if(typeof r=="number")return r;const e=parseFloat(r);return isNaN(e)?si:e}function li(r){return r.map(e=>et(e.width))}function ai(r){const e=[];let t=0;for(const i of r)e.push(t),t+=et(i.width);return e}function ci(r){return r.reduce((e,t)=>e+et(t.width),0)}function Vr(r,e,t,i,n){const o=t.length;if(o===0)return{startCol:0,endCol:0,visibleColumns:[]};let s=Ur(r,t,i);s=Math.max(0,s-n);const l=r+e;let a=s;for(let d=s;d<o;d++){if(t[d]>=l){a=d-1;break}a=d}a=Math.min(o-1,a+n);const c=[];for(let d=s;d<=a;d++)c.push(d);return{startCol:s,endCol:a,visibleColumns:c}}function Ur(r,e,t){let i=0,n=e.length-1;for(;i<n;){const o=Math.floor((i+n)/2);e[o]+t[o]<=r?i=o+1:n=o}return i}function jr(r,e,t){return t?r>e:!1}class Yr extends M{name="columnVirtualization";get defaultConfig(){return{autoEnable:!0,threshold:30,overscan:3}}isVirtualized=!1;startCol=0;endCol=0;scrollLeft=0;totalWidth=0;columnWidths=[];columnOffsets=[];originalColumns=[];attach(e){super.attach(e);const t=this.columns;this.columnWidths=li(t),this.columnOffsets=ai(t),this.totalWidth=ci(t),this.endCol=t.length-1}detach(){this.#t(),this.columnWidths=[],this.columnOffsets=[],this.originalColumns=[],this.isVirtualized=!1,this.startCol=0,this.endCol=0,this.scrollLeft=0,this.totalWidth=0}#t(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".header-row");t&&(t.style.paddingLeft="",t.style.minWidth=""),e.querySelectorAll(".data-grid-row").forEach(s=>{s.style.paddingLeft=""});const n=e.querySelector(".rows-viewport .rows");n&&(n.style.width="");const o=e.querySelector(".rows-body");o&&(o.style.minWidth="")}processColumns(e){(this.originalColumns.length===0||e.length>=this.originalColumns.length)&&(this.originalColumns=e,this.columnWidths=li(e),this.columnOffsets=ai(e),this.totalWidth=ci(e));const i=this.originalColumns,n=jr(i.length,this.config.threshold??30,this.config.autoEnable??!0);if(this.isVirtualized=n??!1,!n)return this.startCol=0,this.endCol=i.length-1,[...i];const o=this.grid.clientWidth||800,s=Vr(this.scrollLeft,o,this.columnOffsets,this.columnWidths,this.config.overscan??3);return this.startCol=s.startCol,this.endCol=s.endCol,s.visibleColumns.map(l=>i[l])}afterRender(){if(!this.isVirtualized)return;const e=this.gridElement;if(!e)return;const t=this.columnOffsets[this.startCol]??0,i=e.querySelector(".header-row"),n=e.querySelectorAll(".data-grid-row");i&&(i.style.paddingLeft=`${t}px`,i.style.minWidth=`${this.totalWidth}px`),n.forEach(l=>{l.style.paddingLeft=`${t}px`});const o=e.querySelector(".rows-viewport .rows");o&&(o.style.width=`${this.totalWidth}px`);const s=e.querySelector(".rows-body");s&&(s.style.minWidth=`${this.totalWidth}px`)}onScroll(e){!this.isVirtualized||Math.abs(e.scrollLeft-this.scrollLeft)<1||(this.scrollLeft=e.scrollLeft,this.requestColumnsRender())}getIsVirtualized(){return this.isVirtualized}getVisibleColumnRange(){return{start:this.startCol,end:this.endCol}}scrollToColumn(e){const t=this.columnOffsets[e]??0,i=this.grid;i.scrollLeft=t}getColumnOffset(e){return this.columnOffsets[e]??0}getTotalWidth(){return this.totalWidth}}const tt="@layer tbw-plugins{.tbw-context-menu{position:fixed;background:var(--tbw-context-menu-bg, var(--tbw-color-panel-bg));color:var(--tbw-context-menu-fg, var(--tbw-color-fg));border:1px solid var(--tbw-context-menu-border, var(--tbw-color-border));border-radius:var(--tbw-context-menu-radius, var(--tbw-border-radius));box-shadow:var(--tbw-context-menu-shadow, 0 2px 10px var(--tbw-color-shadow));min-width:var(--tbw-context-menu-min-width, var(--tbw-menu-min-width));padding:var(--tbw-spacing-xs) 0;z-index:10000;font-size:var(--tbw-context-menu-font-size, var(--tbw-font-size-sm));font-family:var(--tbw-context-menu-font-family, var(--tbw-font-family))}.tbw-context-menu-item{display:flex;align-items:center;padding:var(--tbw-context-menu-item-padding, var(--tbw-menu-item-padding));cursor:pointer;gap:var(--tbw-context-menu-item-gap, var(--tbw-menu-item-gap))}.tbw-context-menu-item:hover:not(.disabled){background:var(--tbw-context-menu-hover, var(--tbw-color-row-hover))}.tbw-context-menu-item.disabled{opacity:.5;cursor:default}.tbw-context-menu-item.danger{color:var(--tbw-context-menu-danger, var(--tbw-color-danger))}.tbw-context-menu-icon{width:var(--tbw-context-menu-icon-size, var(--tbw-icon-size));text-align:center}.tbw-context-menu-label{flex:1}.tbw-context-menu-shortcut kbd{color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted));font-size:var(--tbw-context-menu-shortcut-size, var(--tbw-font-size-xs))}.tbw-context-menu-arrow{font-size:var(--tbw-context-menu-arrow-size, var(--tbw-font-size-2xs));color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted))}.tbw-context-menu-separator{height:1px;background:var(--tbw-context-menu-border, var(--tbw-color-border));margin:var(--tbw-spacing-xs) 0}}";function it(r,e){return(typeof r=="function"?r(e):r).filter(i=>!(i.hidden===!0||typeof i.hidden=="function"&&i.hidden(e)))}function di(r){const e=[];for(const t of r)t.separator&&(e.length===0||e[e.length-1].separator)||e.push(t);return e.length>0&&e[e.length-1].separator&&e.pop(),e}function Xr(r,e){return r.disabled===!0?!0:typeof r.disabled=="function"?r.disabled(e):!1}function nt(r,e,t,i=W.submenuArrow){const n=document.createElement("div");n.className="tbw-context-menu",n.setAttribute("role","menu");const o=r.some(s=>!s.separator&&s.icon);for(const s of r){if(s.separator){const d=document.createElement("div");d.className="tbw-context-menu-separator",d.setAttribute("role","separator"),n.appendChild(d);continue}const l=document.createElement("div");l.className="tbw-context-menu-item",s.cssClass&&l.classList.add(s.cssClass),l.setAttribute("role","menuitem"),l.setAttribute("data-id",s.id);const a=Xr(s,e);if(a&&(l.classList.add("disabled"),l.setAttribute("aria-disabled","true")),s.icon){const d=document.createElement("span");d.className="tbw-context-menu-icon",d.innerHTML=s.icon,l.appendChild(d)}else if(o){const d=document.createElement("span");d.className="tbw-context-menu-icon",d.innerHTML=" ",l.appendChild(d)}const c=document.createElement("span");if(c.className="tbw-context-menu-label",c.textContent=s.name,l.appendChild(c),s.shortcut){const d=document.createElement("span");if(d.className="tbw-context-menu-shortcut",Array.isArray(s.shortcut))s.shortcut.forEach((u,h)=>{h>0&&d.appendChild(document.createTextNode("+"));const p=document.createElement("kbd");p.textContent=u,d.appendChild(p)});else{const u=document.createElement("kbd");u.textContent=s.shortcut,d.appendChild(u)}l.appendChild(d)}if(s.subMenu?.length){const d=document.createElement("span");d.className="tbw-context-menu-arrow",typeof i=="string"?d.innerHTML=i:i instanceof HTMLElement&&d.appendChild(i.cloneNode(!0)),l.appendChild(d),l.addEventListener("mouseenter",()=>{if(l.querySelector(".tbw-context-menu")||!s.subMenu)return;const h=it(s.subMenu,e),p=nt(h,e,t,i);p.classList.add("tbw-context-submenu"),p.style.position="absolute",p.style.left="100%",p.style.top="0",l.style.position="relative",l.appendChild(p)}),l.addEventListener("mouseleave",()=>{const u=l.querySelector(".tbw-context-menu");u&&u.remove()})}!a&&s.action&&!s.subMenu&&l.addEventListener("click",d=>{d.stopPropagation(),t(s)}),n.appendChild(l)}return n}function ui(r,e,t){r.style.position="fixed",r.style.left=`${e}px`,r.style.top=`${t}px`,r.style.visibility="hidden",r.style.zIndex="10000";const i=r.getBoundingClientRect(),n=window.innerWidth,o=window.innerHeight;let s=e,l=t;e+i.width>n&&(s=e-i.width),t+i.height>o&&(l=t-i.height),s=Math.max(0,s),l=Math.max(0,l),r.style.left=`${s}px`,r.style.top=`${l}px`,r.style.visibility="visible"}const hi="getContextMenuItems";let re=null,oe=null,Q=null,rt=0;const ot=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:r=>{r.grid?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:r=>{r.grid?.plugins?.export?.exportCsv?.()}}];class st extends M{static manifest={queries:[{type:hi,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:ot}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),rt++}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,this.uninstallGlobalHandlers()}syncSelectionOnContextMenu(e){if(e<0)return[];const i=this.grid?.query("getSelectedRowIndices")?.[0];return i?i.includes(e)?i:(this.grid?.query("selectRows",[e]),[e]):[e]}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size"];copyGridStyles(e){const t=this.gridElement;if(!t)return;const i=getComputedStyle(t),n=[],o=i.getPropertyValue("color-scheme").trim();o&&n.push(`color-scheme: ${o}`);for(const s of st.CSS_VARS_TO_COPY){const l=i.getPropertyValue(s).trim();l&&n.push(`${s}: ${l}`)}if(n.length>0){const s=e.getAttribute("style")||"";e.setAttribute("style",s+n.join("; ")+";")}}installGlobalHandlers(){!Q&&typeof document<"u"&&typeof tt=="string"&&tt&&(Q=document.createElement("style"),Q.id="tbw-context-menu-styles",Q.textContent=tt,document.head.appendChild(Q)),re||(re=()=>{document.querySelectorAll(".tbw-context-menu").forEach(t=>t.remove())},document.addEventListener("click",re)),oe||(oe=e=>{e.key==="Escape"&&document.querySelectorAll(".tbw-context-menu").forEach(i=>i.remove())},document.addEventListener("keydown",oe))}uninstallGlobalHandlers(){rt--,!(rt>0)&&(re&&(document.removeEventListener("click",re),re=null),oe&&(document.removeEventListener("keydown",oe),oe=null),Q&&(Q.remove(),Q=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(hi,e),i=[];for(const n of t)Array.isArray(n)&&i.push(...n);return i.sort((n,o)=>(n.order??100)-(o.order??100)),this.insertGroupSeparators(i)}insertGroupSeparators(e){if(e.length<=1)return e;const t=[];let i=-1;for(const n of e){if(n.separator){t.push(n);continue}const o=Math.floor((n.order??100)/10);i>=0&&o!==i&&t.push({id:`__sep-${i}-${o}`,label:"",separator:!0,action:()=>{}}),i=o,t.push(n)}return t}convertPluginItems(e){return e.map(t=>({id:t.id,name:t.label,icon:t.icon,shortcut:t.shortcut,disabled:t.disabled??!1,action:()=>t.action(),separator:t.separator,cssClass:t.cssClass}))}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root");t&&t.getAttribute("data-context-menu-bound")!=="true"&&(t.setAttribute("data-context-menu-bound","true"),t.addEventListener("contextmenu",i=>{const n=i;n.preventDefault();const o=n.target,s=o.closest("[data-row][data-col]"),l=o.closest('[part~="header-cell"]');let a;if(s){const u=parseInt(s.getAttribute("data-row")??"-1",10),h=parseInt(s.getAttribute("data-col")??"-1",10),p=this.visibleColumns[h],f=this.rows[u],g=this.syncSelectionOnContextMenu(u);a={row:f,rowIndex:u,column:p,columnIndex:h,field:p?.field??"",value:f?.[p?.field]??null,isHeader:!1,event:n,selectedRows:g}}else if(l){const u=parseInt(l.getAttribute("data-col")??"-1",10),h=this.visibleColumns[u];a={row:null,rowIndex:-1,column:h,columnIndex:u,field:h?.field??"",value:null,isHeader:!0,event:n,selectedRows:[]}}else return;this.params=a,this.position={x:n.clientX,y:n.clientY};const c=this.collectPluginItems(a);let d=it(this.config.items??ot,a);if(c.length>0){const u=this.convertPluginItems(c);d.length>0&&u.length>0?d=[...d,{id:"__plugin-sep",name:"",separator:!0},...u]:d=[...d,...u]}d=di(d),d.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=nt(d,a,u=>{u.action&&u.action(a),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),ui(this.menuElement,n.clientX,n.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:a,items:d}))}))}showMenu(e,t,i){const n={row:i.row??null,rowIndex:i.rowIndex??-1,column:i.column??null,columnIndex:i.columnIndex??-1,field:i.field??"",value:i.value??null,isHeader:i.isHeader??!1,event:i.event??new MouseEvent("contextmenu"),selectedRows:i.selectedRows??[]},o=this.collectPluginItems(n);let s=it(this.config.items??ot,n);if(o.length>0){const l=this.convertPluginItems(o);s.length>0&&l.length>0?s=[...s,{id:"__plugin-sep",name:"",separator:!0},...l]:s=[...s,...l]}s=di(s),this.menuElement&&this.menuElement.remove(),this.menuElement=nt(s,n,l=>{l.action&&l.action(n),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),ui(this.menuElement,e,t),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}const Qr="@layer tbw-plugins{tbw-grid{--tbw-editing-bg: var(--tbw-color-selection);--tbw-editing-row-bg: var(--tbw-editing-bg);--tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));--tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);--tbw-font-size-editor: inherit;--tbw-editing-row-outline-color: var(--tbw-color-accent);--tbw-editing-row-outline-width: 1px;--tbw-invalid-bg: light-dark(#fef2f2, #450a0a);--tbw-invalid-border-color: light-dark(#ef4444, #f87171)}tbw-grid:not(.tbw-grid-mode) .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:calc(var(--tbw-row-height) + 2px);align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}tbw-grid .data-grid-row>.cell[data-invalid=true]{background:var(--tbw-invalid-bg);outline:1px solid var(--tbw-invalid-border-color);outline-offset:-1px}}";function Zr(r){const e=r.options;return e?typeof e=="function"?e():e:[]}function Jr(r){return e=>{const t=r.editorParams,i=document.createElement("input");i.type="number",i.value=e.value!=null?String(e.value):"",t?.min!==void 0&&(i.min=String(t.min)),t?.max!==void 0&&(i.max=String(t.max)),t?.step!==void 0&&(i.step=String(t.step)),t?.placeholder&&(i.placeholder=t.placeholder);const n=()=>e.commit(i.value===""?null:Number(i.value));return i.addEventListener("blur",n),i.addEventListener("keydown",o=>{o.key==="Enter"&&n(),o.key==="Escape"&&e.cancel()}),i}}function eo(){return r=>{const e=document.createElement("input");return e.type="checkbox",e.checked=!!r.value,e.addEventListener("change",()=>r.commit(e.checked)),e}}function to(r){return e=>{const t=r.editorParams,i=document.createElement("input");i.type="date",e.value instanceof Date?i.valueAsDate=e.value:typeof e.value=="string"&&e.value&&(i.value=e.value.split("T")[0]),t?.min&&(i.min=t.min),t?.max&&(i.max=t.max),t?.placeholder&&(i.placeholder=t.placeholder);const n=()=>{typeof e.value=="string"?e.commit(i.value):e.commit(i.valueAsDate)};return i.addEventListener("change",n),i.addEventListener("keydown",o=>{o.key==="Escape"&&e.cancel()}),i}}function io(r){return e=>{const t=r.editorParams,i=document.createElement("select");if(r.multi&&(i.multiple=!0),t?.includeEmpty){const s=document.createElement("option");s.value="",s.textContent=t.emptyLabel??"",i.appendChild(s)}Zr(r).forEach(s=>{const l=document.createElement("option");l.value=String(s.value),l.textContent=s.label,(r.multi&&Array.isArray(e.value)&&e.value.includes(s.value)||!r.multi&&e.value===s.value)&&(l.selected=!0),i.appendChild(l)});const o=()=>{if(r.multi){const s=Array.from(i.selectedOptions).map(l=>l.value);e.commit(s)}else e.commit(i.value)};return i.addEventListener("change",o),i.addEventListener("blur",o),i.addEventListener("keydown",s=>{s.key==="Escape"&&e.cancel()}),i}}function no(r){return e=>{const t=r.editorParams,i=document.createElement("input");i.type="text",i.value=e.value!=null?String(e.value):"",t?.maxLength!==void 0&&(i.maxLength=t.maxLength),t?.pattern&&(i.pattern=t.pattern),t?.placeholder&&(i.placeholder=t.placeholder);const n=()=>{const o=i.value;(e.value===null||e.value===void 0)&&o===""||typeof e.value=="string"&&o===e.value.replace(/[\n\r]/g,"")||(typeof e.value=="number"&&o!==""?e.commit(Number(o)):e.commit(o))};return i.addEventListener("blur",n),i.addEventListener("keydown",o=>{o.key==="Enter"&&n(),o.key==="Escape"&&e.cancel()}),i}}function fi(r){switch(r.type){case"number":return Jr(r);case"boolean":return eo();case"date":return to(r);case"select":return io(r);default:return no(r)}}function ro(r,e){if(e.editor)return e.editor;if(e.__editorTemplate)return"template";if(!e.type)return;const i=r.effectiveConfig?.typeDefaults;if(i?.[e.type]?.editor)return i[e.type].editor;const n=r.__frameworkAdapter;if(n?.getTypeDefault){const o=n.getTypeDefault(e.type);if(o?.editor)return o.editor}}function be(r){return!(typeof r!="string"||r==="__proto__"||r==="constructor"||r==="prototype")}function oo(r){const e=(r.__editingCellCount??0)+1;r.__editingCellCount=e,r.setAttribute("data-has-editing","")}function so(r){r.__editingCellCount=0,r.removeAttribute("data-has-editing")}function se(r,e,t){return r instanceof HTMLInputElement?r.type==="checkbox"?r.checked:r.type==="number"?r.value===""?null:Number(r.value):r.type==="date"?typeof t=="string"?r.value:r.valueAsDate:typeof t=="number"?r.value===""?null:Number(r.value):t==null&&r.value===""||typeof t=="string"&&r.value===t.replace(/[\n\r]/g,"")?t:r.value:e?.type==="number"&&r.value!==""||typeof t=="number"&&r.value!==""?Number(r.value):t==null&&r.value===""?t:r.value}function gi(r){}function lo(r,e,t,i){const n=r.querySelector("input,textarea,select");n&&(n.addEventListener("blur",()=>{t(se(n,e,i))}),n instanceof HTMLInputElement&&n.type==="checkbox"?n.addEventListener("change",()=>t(n.checked)):n instanceof HTMLSelectElement&&n.addEventListener("change",()=>t(se(n,e,i))))}class ao extends M{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>e===!0},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'}],events:[{type:"cell-edit-committed",description:"Emitted when a cell edit is committed (for plugin-to-plugin coordination)"}],queries:[{type:"isEditing",description:"Returns whether any cell is currently being edited"}]};name="editing";styles=Qr;get defaultConfig(){return{mode:"row",editOn:"click"}}get#t(){return this.config.mode==="grid"}#e=-1;#u=-1;#c=new Map;#n=new Set;#l=new Set;#i=new Map;#f=!1;#w=-1;#g=new Map;#a=!1;#b=!1;#d=!1;attach(e){super.attach(e);const t=this.disconnectSignal,i=e;i._activeEditRows=-1,i._rowEditSnapshots=new Map,Object.defineProperty(e,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(e,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),e.resetChangedRows=n=>this.resetChangedRows(n),e.beginBulkEdit=(n,o)=>{o&&this.beginCellEdit(n,o)},document.addEventListener("keydown",n=>{if(!this.#t&&n.key==="Escape"&&this.#e!==-1){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(n)===!1)return;this.#p(this.#e,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",n=>{if(this.#t||this.#e===-1)return;const o=i.findRenderedRowElement?.(this.#e);!o||(n.composedPath&&n.composedPath()||[]).includes(o)||this.config.onBeforeEditClose&&this.config.onBeforeEditClose(n)===!1||queueMicrotask(()=>{this.#e!==-1&&this.#p(this.#e,!1)})},{signal:t}),this.gridElement.addEventListener("cell-change",n=>{const o=n.detail;if(o.source==="user")return;const s=`${o.rowIndex}:${o.field}`,l=this.#i.get(s);l&&l(o.newValue)},{signal:t}),this.#t&&(i._isGridEditMode=!0,this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",n=>{const o=n.target;if(o.matches(K)){if(this.#b){o.blur(),this.gridElement.focus();return}this.#a=!0}},{signal:t}),this.gridElement.addEventListener("focusout",n=>{const o=n.relatedTarget;(!o||!this.gridElement.contains(o)||!o.matches(K))&&(this.#a=!1)},{signal:t}),this.gridElement.addEventListener("keydown",n=>{if(n.key==="Escape"&&this.#a){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(n)===!1)return;const o=document.activeElement;o&&this.gridElement.contains(o)&&(o.blur(),this.gridElement.focus()),this.#a=!1,this.#b=!0,n.preventDefault(),n.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",n=>{n.target.matches(K)&&(this.#b=!1)},{signal:t}))}detach(){const e=this.gridElement;e._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#e=-1,this.#u=-1,this.#c.clear(),this.#n.clear(),this.#l.clear(),this.#i.clear(),this.#a=!1,this.#b=!1,this.#d=!1,super.detach()}handleQuery(e){if(e.type==="isEditing")return this.#t||this.#e!==-1}onCellClick(e){if(this.#t)return!1;const t=this.grid,i=this.config.editOn??t.effectiveConfig?.editOn;if(i===!1||i==="manual"||i!=="click"&&i!=="dblclick")return!1;const n=e.originalEvent.type==="dblclick";if(i==="click"&&n||i==="dblclick"&&!n)return!1;const{rowIndex:o}=e;return t._columns?.some(l=>l.editable)?(e.originalEvent.stopPropagation(),this.beginBulkEdit(o),!0):!1}onKeyDown(e){const t=this.grid;if(e.key==="Escape"){if(this.#t&&this.#a){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1)return!0;const i=document.activeElement;return i&&this.gridElement.contains(i)&&i.blur(),this.#a=!1,this.requestAfterRender(),!0}if(this.#e!==-1&&!this.#t)return this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1||this.#p(this.#e,!0),!0}if(this.#t&&!this.#a&&(e.key==="ArrowUp"||e.key==="ArrowDown"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return!1;if(this.#t&&this.#a&&(e.key==="ArrowUp"||e.key==="ArrowDown"))return!0;if((e.key==="ArrowUp"||e.key==="ArrowDown")&&this.#e!==-1&&!this.#t){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1)return!0;const i=t._rows.length-1,n=this.#e;return this.#p(n,!1),e.key==="ArrowDown"?t._focusRow=Math.min(i,t._focusRow+1):t._focusRow=Math.max(0,t._focusRow-1),e.preventDefault(),F(t),this.requestAfterRender(),!0}if(e.key==="Tab"&&(this.#e!==-1||this.#t)){if(e.preventDefault(),this.#d)return this.#p(this.#e,!1),!0;const i=!e.shiftKey;return this.#x(i),!0}if(e.key===" "||e.key==="Spacebar"){if(this.#e!==-1)return!1;const i=t._focusRow,n=t._focusCol;if(i>=0&&n>=0){const o=t._visibleColumns[n],s=t._rows[i];if(o?.editable&&o.type==="boolean"&&s){const l=o.field;if(be(l)){const c=!s[l];return this.#v(i,o,c,s),e.preventDefault(),this.requestRender(),!0}}}return!1}if(e.key==="Enter"&&!e.shiftKey&&!e.ctrlKey&&!e.altKey&&!e.metaKey){if(this.#t&&!this.#a)return this.#m(),!0;if(this.#e!==-1)return!!(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1);const i=this.config.editOn??t.effectiveConfig?.editOn;if(i===!1||i==="manual")return!1;const n=t._focusRow,o=t._focusCol;if(n>=0&&t._columns?.some(l=>l.editable)){const l=t._visibleColumns[o],a=t._rows[n],c=l?.field??"",d=c&&a?a[c]:void 0,u=this.gridElement.querySelector(`[data-row="${n}"][data-col="${o}"]`),h=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:n,colIndex:o,field:c,value:d,row:a,cellEl:u,trigger:"keyboard",originalEvent:e}});this.gridElement.dispatchEvent(h);const p=new CustomEvent("activate-cell",{cancelable:!0,bubbles:!0,detail:{row:n,col:o}});return this.gridElement.dispatchEvent(p),h.defaultPrevented||p.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(n),!0)}return!1}if(e.key==="F2"){if(this.#e!==-1||this.#t||(this.config.editOn??t.effectiveConfig?.editOn)===!1)return!1;const n=t._focusRow,o=t._focusCol;if(n>=0&&o>=0){const s=t._visibleColumns[o];if(s?.editable&&s.field)return e.preventDefault(),this.beginCellEdit(n,s.field),!0}return!1}return!1}processColumns(e){const t=this.grid,i=t.effectiveConfig?.typeDefaults,n=t.__frameworkAdapter;return!i&&!n?.getTypeDefault?e:e.map(o=>{if(!o.type)return o;let s;if(i?.[o.type]?.editorParams&&(s=i[o.type].editorParams),!s&&n?.getTypeDefault){const l=n.getTypeDefault(o.type);l?.editorParams&&(s=l.editorParams)}return s?{...o,editorParams:{...s,...o.editorParams}}:o})}afterRender(){const e=this.grid;if(this.#f&&(this.#f=!1,this.#_(e)),this.#w!==-1){const t=this.#w;this.#w=-1,e.animateRow?.(t,"change")}if(!this.#t&&this.#l.size!==0)for(const t of this.#l){const[i,n]=t.split(":"),o=parseInt(i,10),s=parseInt(n,10),l=e.findRenderedRowElement?.(o);if(!l)continue;const a=l.querySelector(`.cell[data-col="${s}"]`);if(!a||a.classList.contains("editing"))continue;const c=e._rows[o],d=e._visibleColumns[s];c&&d&&this.#R(c,o,d,s,a,!0)}}afterCellRender(e){if(!this.#t)return;const{row:t,rowIndex:i,column:n,colIndex:o,cellElement:s}=e;n.editable&&(s.classList.contains("editing")||this.#R(t,i,n,o,s,!0))}onScrollRender(){this.afterRender()}get changedRows(){const e=[];for(const t of this.#n){const i=this.grid.getRow(t);i&&e.push(i)}return e}get changedRowIds(){return Array.from(this.#n)}get activeEditRow(){return this.#e}get activeEditCol(){return this.#u}isRowEditing(e){return this.#e===e}isCellEditing(e,t){return this.#l.has(`${e}:${t}`)}isRowChanged(e){const t=this.grid,i=t._rows[e];if(!i)return!1;try{const n=t.getRowId?.(i);return n?this.#n.has(n):!1}catch{return!1}}isRowChangedById(e){return this.#n.has(e)}setInvalid(e,t,i=""){let n=this.#g.get(e);n||(n=new Map,this.#g.set(e,n)),n.set(t,i),this.#h(e,t,!0)}clearInvalid(e,t){const i=this.#g.get(e);i&&(i.delete(t),i.size===0&&this.#g.delete(e)),this.#h(e,t,!1)}clearRowInvalid(e){const t=this.#g.get(e);if(t){const i=Array.from(t.keys());this.#g.delete(e),i.forEach(n=>this.#h(e,n,!1))}}clearAllInvalid(){const e=Array.from(this.#g.entries());this.#g.clear(),e.forEach(([t,i])=>{i.forEach((n,o)=>this.#h(t,o,!1))})}isCellInvalid(e,t){return this.#g.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#g.get(e)?.get(t)}hasInvalidCells(e){const t=this.#g.get(e);return t?t.size>0:!1}getInvalidFields(e){return new Map(this.#g.get(e)??[])}#h(e,t,i){const n=this.grid,o=n._visibleColumns?.findIndex(d=>d.field===t);if(o===-1||o===void 0)return;const l=n._rows?.findIndex(d=>{try{return n.getRowId?.(d)===e}catch{return!1}});if(l===-1||l===void 0)return;const c=n.findRenderedRowElement?.(l)?.querySelector(`.cell[data-col="${o}"]`);if(c)if(i){c.setAttribute("data-invalid","true");const d=this.#g.get(e)?.get(t);d&&c.setAttribute("title",d)}else c.removeAttribute("data-invalid"),c.removeAttribute("title")}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#n.clear(),this.#S(),e||this.emit("changed-rows-reset",{rows:t,ids:i}),this.grid._rowPool?.forEach(o=>o.classList.remove("changed"))}beginCellEdit(e,t){const i=this.grid,n=i._visibleColumns.findIndex(a=>a.field===t);if(n===-1||!i._visibleColumns[n]?.editable)return;const l=i.findRenderedRowElement?.(e)?.querySelector(`.cell[data-col="${n}"]`);l&&(this.#d=!0,this.#E(e,n,l))}beginBulkEdit(e){const t=this.grid;if((this.config.editOn??t.effectiveConfig?.editOn)===!1||!t._columns?.some(l=>l.editable))return;const o=t.findRenderedRowElement?.(e);if(!o)return;this.#d=!1;const s=t._rows[e];this.#C(e,s),Array.from(o.children).forEach((l,a)=>{const c=t._visibleColumns[a];if(c?.editable){const d=l;d.classList.contains("editing")||this.#R(s,e,c,a,d,!0)}}),setTimeout(()=>{let l=o.querySelector(`.cell[data-col="${t._focusCol}"]`);if(l?.classList.contains("editing")||(l=o.querySelector(".cell.editing")),l?.classList.contains("editing")){const a=l.querySelector(K);try{a?.focus({preventScroll:!0})}catch{}}},0)}commitActiveRowEdit(){this.#e!==-1&&this.#p(this.#e,!1)}cancelActiveRowEdit(){this.#e!==-1&&this.#p(this.#e,!0)}#E(e,t,i){const n=this.grid,o=n._rows[e],s=n._visibleColumns[t];!o||!s?.editable||i.classList.contains("editing")||(this.#e!==e&&this.#C(e,o),this.#u=t,this.#R(o,e,s,t,i,!1))}#m(){const e=this.grid,t=e._focusRow,i=e._focusCol;if(t<0||i<0)return;const o=e.findRenderedRowElement?.(t)?.querySelector(`.cell[data-col="${i}"]`);if(o?.classList.contains("editing")){const s=o.querySelector(K);s&&(this.#b=!1,s.focus(),this.#a=!0,s instanceof HTMLInputElement&&(s.type==="text"||s.type==="number")&&s.select())}}#x(e){const t=this.grid,i=t._rows,n=this.#t?t._focusRow:this.#e,o=t._visibleColumns.map((c,d)=>c.editable?d:-1).filter(c=>c>=0);if(o.length===0)return;const l=o.indexOf(t._focusCol)+(e?1:-1);if(l>=0&&l<o.length){t._focusCol=o[l];const d=t.findRenderedRowElement?.(n)?.querySelector(`.cell[data-col="${o[l]}"]`);d?.classList.contains("editing")&&d.querySelector(K)?.focus({preventScroll:!0}),F(t,{forceHorizontalScroll:!0});return}const a=n+(e?1:-1);a>=0&&a<i.length&&(this.#t?(t._focusRow=a,t._focusCol=e?o[0]:o[o.length-1],F(t,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const d=t.findRenderedRowElement?.(a)?.querySelector(`.cell[data-col="${t._focusCol}"]`);d?.classList.contains("editing")&&d.querySelector(K)?.focus({preventScroll:!0})},0)):(this.#p(n,!1),t._focusRow=a,t._focusCol=e?o[0]:o[o.length-1],this.beginBulkEdit(a),F(t,{forceHorizontalScroll:!0})))}#S(){const e=this.grid;e._activeEditRows=this.#e,e._rowEditSnapshots=this.#c}#C(e,t){if(this.#e!==e&&(this.#c.set(e,{...t}),this.#e=e,this.#S(),!this.#t)){const i=this.grid;let n="";try{n=i.getRowId?.(t)??""}catch{}this.emit("edit-open",{rowIndex:e,rowId:n,row:t})}}#p(e,t){if(this.#e!==e)return;const i=this.grid,n=this.#c.get(e),o=i._rows[e],s=i.findRenderedRowElement?.(e);let l;if(o)try{l=i.getRowId?.(o)}catch{}if(!t&&s&&o&&s.querySelectorAll(".cell.editing").forEach(c=>{const d=Number(c.getAttribute("data-col"));if(isNaN(d))return;const u=i._visibleColumns[d];if(!u||c.hasAttribute("data-editor-managed"))return;const h=c.querySelector("input,textarea,select");if(h){const p=u.field,f=o[p],g=se(h,u,f);f!==g&&this.#v(e,u,g,o)}}),t&&n&&o)Object.keys(n).forEach(a=>{o[a]=n[a]}),l&&(this.#n.delete(l),this.clearRowInvalid(l));else if(!t&&o){const a=this.#r(n,o),c=l?this.#n.has(l):a,d=this.emitCancelable("row-commit",{rowIndex:e,rowId:l??"",row:o,oldValue:n,newValue:o,changed:c,changedRows:this.changedRows,changedRowIds:this.changedRowIds});d&&n?(Object.keys(n).forEach(u=>{o[u]=n[u]}),l&&(this.#n.delete(l),this.clearRowInvalid(l))):!d&&a&&this.isAnimationEnabled&&(this.#w=e)}this.#c.delete(e),this.#e=-1,this.#u=-1,this.#d=!1,this.#S();for(const a of this.#l)a.startsWith(`${e}:`)&&this.#l.delete(a);for(const a of this.#i.keys())a.startsWith(`${e}:`)&&this.#i.delete(a);s&&(s.querySelectorAll(".cell.editing").forEach(a=>{a.classList.remove("editing"),so(a.parentElement)}),this.requestRender()),this.#f=!0,s||(this.#_(i),this.#f=!1),!this.#t&&o&&this.emit("edit-close",{rowIndex:e,rowId:l??"",row:o,reverted:t})}#v(e,t,i,n){const o=t.field;if(!be(o))return;const s=n[o];if(s===i)return;const l=this.grid;let a;try{a=this.grid.getRowId(n)}catch{}const c=a?!this.#n.has(a):!0,d=a?g=>this.grid.updateRow(a,g,"cascade"):gi;let u=!1;const h=a?g=>{u=!0,this.setInvalid(a,o,g??"")}:()=>{};if(this.emitCancelable("cell-commit",{row:n,rowId:a??"",field:o,oldValue:s,value:i,rowIndex:e,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:c,updateRow:d,setInvalid:h}))return;a&&!u&&this.isCellInvalid(a,o)&&this.clearInvalid(a,o),n[o]=i,a&&this.#n.add(a),this.#S(),this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:o,oldValue:s,newValue:i});const f=l.findRenderedRowElement?.(e);f&&f.classList.add("changed")}#R(e,t,i,n,o,s){if(!i.editable||o.classList.contains("editing"))return;let l;try{l=this.grid.getRowId(e)}catch{}const a=l?C=>this.grid.updateRow(l,C,"cascade"):gi,c=be(i.field)?e[i.field]:void 0;o.classList.add("editing"),this.#l.add(`${t}:${n}`);const d=o.parentElement;d&&oo(d);let u=!1;const h=C=>{if(u||!this.#t&&this.#e===-1)return;const m=this.grid._rows[t]??e;this.#v(t,i,C,m)},p=()=>{if(u=!0,be(i.field)){const C=this.grid._rows[t]??e;C[i.field]=c}},f=document.createElement("div");f.className="tbw-editor-host",o.innerHTML="",o.appendChild(f),f.addEventListener("keydown",C=>{if(C.key==="Enter"){if(this.#t){C.stopPropagation(),C.preventDefault();const m=f.querySelector("input,textarea,select");m&&h(se(m,i,c));return}if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(C)===!1)return;C.stopPropagation(),C.preventDefault(),u=!0,this.#p(t,!1)}if(C.key==="Escape"){if(this.#t){C.stopPropagation(),C.preventDefault();return}if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(C)===!1)return;C.stopPropagation(),C.preventDefault(),p(),this.#p(t,!0)}});const g=i,w=g.__editorTemplate,b=ro(this.grid,g)??fi(i),v=c,A=`${t}:${i.field}`,L=[];this.#i.set(A,C=>{for(const m of L)m(C)});const _=C=>{L.push(C)};if(b==="template"&&w)this.#P(f,g,e,c,h,p,s,t),_(C=>{const m=f.querySelector("input,textarea,select");m&&(m instanceof HTMLInputElement&&m.type==="checkbox"?m.checked=!!C:m.value=String(C??""))});else if(typeof b=="string"){const C=document.createElement(b);C.value=v,C.addEventListener("change",()=>h(C.value)),_(m=>{C.value=m}),f.appendChild(C),s||queueMicrotask(()=>{f.querySelector(K)?.focus({preventScroll:!0})})}else if(typeof b=="function"){const C={row:e,rowId:l??"",value:v,field:i.field,column:i,commit:h,cancel:p,updateRow:a,onValueChange:_},m=b(C);typeof m=="string"?(f.innerHTML=m,lo(f,i,h,c),_(R=>{const y=f.querySelector("input,textarea,select");y&&(y instanceof HTMLInputElement&&y.type==="checkbox"?y.checked=!!R:y.value=String(R??""))})):m instanceof Node&&(f.appendChild(m),m instanceof HTMLInputElement||m instanceof HTMLSelectElement||m instanceof HTMLTextAreaElement?_(y=>{m instanceof HTMLInputElement&&m.type==="checkbox"?m.checked=!!y:m.value=String(y??"")}):o.setAttribute("data-editor-managed","")),s||queueMicrotask(()=>{f.querySelector(K)?.focus({preventScroll:!0})})}else if(b&&typeof b=="object"){const C=document.createElement("div");C.setAttribute("data-external-editor",""),C.setAttribute("data-field",i.field),f.appendChild(C),o.setAttribute("data-editor-managed","");const m={row:e,rowId:l??"",value:v,field:i.field,column:i,commit:h,cancel:p,updateRow:a,onValueChange:_};if(b.mount)try{b.mount({placeholder:C,context:m,spec:b})}catch(R){console.warn(`[tbw-grid] External editor mount error for column '${i.field}':`,R)}else this.grid.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:C,spec:b,context:m}}))}}#P(e,t,i,n,o,s,l,a){const c=t.__editorTemplate;if(!c)return;const d=c.cloneNode(!0),u=t.__compiledEditor;u?d.innerHTML=u({row:i,value:n,field:t.field,column:t,commit:o,cancel:s}):d.querySelectorAll("*").forEach(p=>{p.childNodes.length===1&&p.firstChild?.nodeType===Node.TEXT_NODE&&(p.textContent=p.textContent?.replace(/{{\s*value\s*}}/g,n==null?"":String(n)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(f,g)=>{if(!be(g))return"";const w=i[g];return w==null?"":String(w)})||"")});const h=d.querySelector("input,textarea,select");if(h){h instanceof HTMLInputElement&&h.type==="checkbox"?h.checked=!!n:h.value=String(n??"");let p=!1;h.addEventListener("blur",()=>{p||o(se(h,t,n))}),h.addEventListener("keydown",f=>{const g=f;if(g.key==="Enter"){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(g)===!1)return;g.stopPropagation(),g.preventDefault(),p=!0,o(se(h,t,n)),this.#p(a,!1)}if(g.key==="Escape"){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(g)===!1)return;g.stopPropagation(),g.preventDefault(),s(),this.#p(a,!0)}}),h instanceof HTMLInputElement&&h.type==="checkbox"&&h.addEventListener("change",()=>o(h.checked)),l||setTimeout(()=>h.focus({preventScroll:!0}),0)}e.appendChild(d)}#r(e,t){if(!e)return!1;const i=e,n=t,o=new Set([...Object.keys(i),...Object.keys(n)]);for(const s of o)if(i[s]!==n[s])return!0;return!1}#_(e){queueMicrotask(()=>{try{const t=e._focusRow,i=e._focusCol,n=e.findRenderedRowElement?.(t);if(n){Array.from(e._bodyEl.querySelectorAll(".cell-focus")).forEach(s=>s.classList.remove("cell-focus"));const o=n.querySelector(`.cell[data-row="${t}"][data-col="${i}"]`);o&&(o.classList.add("cell-focus"),o.setAttribute("aria-selected","true"),o.hasAttribute("tabindex")||o.setAttribute("tabindex","-1"),o.focus({preventScroll:!0}))}}catch{}})}}function pi(r,e=!0){if(r==null)return"";if(r instanceof Date)return r.toISOString();if(typeof r=="object")return JSON.stringify(r);const t=String(r);return e&&(t.includes(",")||t.includes('"')||t.includes(`
|
|
96
96
|
`)||t.includes("\r"))?`"${t.replace(/"/g,'""')}"`:t}function co(r,e,t,i={}){const n=i.delimiter??",",o=i.newline??`
|
|
97
97
|
`,s=[],l=i.bom?"\uFEFF":"";if(t.includeHeaders!==!1){const a=e.map(c=>{const d=c.header||c.field,u=t.processHeader?t.processHeader(d,c.field):d;return pi(u)});s.push(a.join(n))}for(const a of r){const c=e.map(d=>{let u=a[d.field];return t.processCell&&(u=t.processCell(u,d.field,a)),pi(u)});s.push(c.join(n))}return l+s.join(o)}function lt(r,e){const t=URL.createObjectURL(r),i=document.createElement("a");i.href=t,i.download=e,i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(t)}function uo(r,e){const t=new Blob([r],{type:"text/csv;charset=utf-8;"});lt(t,e)}function wi(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ho(r,e,t){let i=`<?xml version="1.0" encoding="UTF-8"?>
|