@toolbox-web/grid 2.17.1 → 2.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/all.js +1 -1
  2. package/all.js.map +1 -1
  3. package/index.js +1 -1
  4. package/lib/features/registry.js +1 -1
  5. package/lib/plugins/clipboard/index.js +1 -1
  6. package/lib/plugins/column-virtualization/index.js +1 -1
  7. package/lib/plugins/context-menu/index.js +1 -1
  8. package/lib/plugins/editing/index.js +1 -1
  9. package/lib/plugins/export/index.js +1 -1
  10. package/lib/plugins/filtering/index.js +1 -1
  11. package/lib/plugins/grouping-columns/index.js +1 -1
  12. package/lib/plugins/grouping-rows/index.js +1 -1
  13. package/lib/plugins/master-detail/index.js +1 -1
  14. package/lib/plugins/multi-sort/index.js +1 -1
  15. package/lib/plugins/pinned-columns/index.js +1 -1
  16. package/lib/plugins/pinned-rows/index.js +1 -1
  17. package/lib/plugins/pivot/index.js +1 -1
  18. package/lib/plugins/print/index.js +1 -1
  19. package/lib/plugins/reorder-columns/index.js +1 -1
  20. package/lib/plugins/reorder-rows/index.js +1 -1
  21. package/lib/plugins/responsive/index.js +1 -1
  22. package/lib/plugins/row-drag-drop/index.js +1 -1
  23. package/lib/plugins/selection/index.js +1 -1
  24. package/lib/plugins/server-side/index.js +1 -1
  25. package/lib/plugins/shell/index.js +1 -1
  26. package/lib/plugins/sticky-rows/StickyRowsPlugin.d.ts +23 -0
  27. package/lib/plugins/sticky-rows/index.js +1 -1
  28. package/lib/plugins/sticky-rows/index.js.map +1 -1
  29. package/lib/plugins/tooltip/index.js +1 -1
  30. package/lib/plugins/tree/index.js +1 -1
  31. package/lib/plugins/undo-redo/index.js +1 -1
  32. package/lib/plugins/visibility/index.js +1 -1
  33. package/package.json +1 -1
  34. package/umd/grid.all.umd.js +1 -1
  35. package/umd/grid.all.umd.js.map +1 -1
  36. package/umd/grid.umd.js +1 -1
  37. package/umd/plugins/sticky-rows.umd.js +1 -1
  38. package/umd/plugins/sticky-rows.umd.js.map +1 -1
@@ -1,2 +1,2 @@
1
- import{setFeatureResolver as o}from"@toolbox-web/grid";function e(o,e,t,n){console.warn(function(o,e){return`[tbw-grid] ${o}: ${e}\n\n → More info: ${function(o){return`https://toolboxjs.com/grid/errors#${o.toLowerCase()}`}(o)}`}(o,e))}const t="2.17.1",n=/* @__PURE__ */Symbol.for(`@toolbox-web/grid:feature-registry@${t}/v1`),r=/* @__PURE__ */Symbol.for(`@toolbox-web/grid:feature-registry-warned@${t}/v1`);function i(o,e){let t=Reflect.get(globalThis,o);return void 0===t&&(t=e(),Reflect.set(globalThis,o,t)),t}const s=i(n,()=>/* @__PURE__ */new Map),c=i(r,()=>/* @__PURE__ */new Set),f=()=>"undefined"!=typeof window&&("localhost"===window.location?.hostname||"127.0.0.1"===window.location?.hostname);function a(o,t,n){f()&&s.has(o)&&!n?.override&&e("TBW030",`Feature "${o}" was re-registered. Previous registration overwritten.`),s.set(o,{factory:t,name:o})}function u(o){return s.has(o)}function d(o){return s.get(o)?.factory}function l(){return Array.from(s.keys())}const g={undoRedo:["editing"],clipboard:["selection"]};function w(o,t){const n=s.get(o);if(n)return n.factory(t);if(f()&&!c.has(o)){c.add(o);const t=o.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();e("TBW031",`Feature "${o}" is configured but not registered.\nAdd this import to enable it:\n\n import '@toolbox-web/grid/features/${t}';\n`)}}function b(o){const t=[],n=[];for(const[e,s]of Object.entries(o))void 0!==s&&!1!==s&&n.push(e);!function(o){const t=new Set(o);for(const n of o){const o=g[n];if(o)for(const r of o)t.has(r)||f()&&e("TBW032",`Feature "${n}" requires "${r}" to be enabled. Add "${r}" to your features configuration.`)}}(n);const r=["selection","editing",...n.filter(o=>"selection"!==o&&"editing"!==o)],i=[...new Set(r)].filter(o=>n.includes(o));for(const e of i){const n=o[e];if(void 0===n||!1===n)continue;const r=w(e,n);r&&t.push(r)}return t}function $(){s.clear(),c.clear()}o(b);export{$ as clearFeatureRegistry,w as createPluginFromFeature,b as createPluginsFromFeatures,d as getFeatureFactory,l as getRegisteredFeatures,u as isFeatureRegistered,a as registerFeature};
1
+ import{setFeatureResolver as o}from"@toolbox-web/grid";function e(o,e,t,n){console.warn(function(o,e){return`[tbw-grid] ${o}: ${e}\n\n → More info: ${function(o){return`https://toolboxjs.com/grid/errors#${o.toLowerCase()}`}(o)}`}(o,e))}const t="2.17.2",n=/* @__PURE__ */Symbol.for(`@toolbox-web/grid:feature-registry@${t}/v1`),r=/* @__PURE__ */Symbol.for(`@toolbox-web/grid:feature-registry-warned@${t}/v1`);function i(o,e){let t=Reflect.get(globalThis,o);return void 0===t&&(t=e(),Reflect.set(globalThis,o,t)),t}const s=i(n,()=>/* @__PURE__ */new Map),c=i(r,()=>/* @__PURE__ */new Set),f=()=>"undefined"!=typeof window&&("localhost"===window.location?.hostname||"127.0.0.1"===window.location?.hostname);function a(o,t,n){f()&&s.has(o)&&!n?.override&&e("TBW030",`Feature "${o}" was re-registered. Previous registration overwritten.`),s.set(o,{factory:t,name:o})}function u(o){return s.has(o)}function d(o){return s.get(o)?.factory}function l(){return Array.from(s.keys())}const g={undoRedo:["editing"],clipboard:["selection"]};function w(o,t){const n=s.get(o);if(n)return n.factory(t);if(f()&&!c.has(o)){c.add(o);const t=o.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();e("TBW031",`Feature "${o}" is configured but not registered.\nAdd this import to enable it:\n\n import '@toolbox-web/grid/features/${t}';\n`)}}function b(o){const t=[],n=[];for(const[e,s]of Object.entries(o))void 0!==s&&!1!==s&&n.push(e);!function(o){const t=new Set(o);for(const n of o){const o=g[n];if(o)for(const r of o)t.has(r)||f()&&e("TBW032",`Feature "${n}" requires "${r}" to be enabled. Add "${r}" to your features configuration.`)}}(n);const r=["selection","editing",...n.filter(o=>"selection"!==o&&"editing"!==o)],i=[...new Set(r)].filter(o=>n.includes(o));for(const e of i){const n=o[e];if(void 0===n||!1===n)continue;const r=w(e,n);r&&t.push(r)}return t}function $(){s.clear(),c.clear()}o(b);export{$ as clearFeatureRegistry,w as createPluginFromFeature,b as createPluginsFromFeatures,d as getFeatureFactory,l as getRegisteredFeatures,u as isFeatureRegistered,a as registerFeature};
2
2
  //# sourceMappingURL=registry.js.map
@@ -1,2 +1,2 @@
1
- const e=/* @__PURE__ */new WeakMap;function t(t,n,r=-1){if(!n.valueAccessor)return t?.[n.field];if("object"!=typeof t||null===t)return n.valueAccessor({row:t,column:n,rowIndex:r});const o=t,i=n.field;let s=e.get(o);if(s){const e=s.get(i);if(void 0!==e)return e.v}else s=/* @__PURE__ */new Map,e.set(o,s);const l=n.valueAccessor({row:t,column:n,rowIndex:r});return s.set(i,{v:l}),l}function n(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function r(e,t,r,o){return`${n(r,o)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}const o="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join(""));new RegExp(`__(proto|defineGetter|defineSetter)|${o.slice(3).join("|")}|this\\b`);const i=new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing".split("|")),s=/^on\w+$/i,l=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),a=/^\s*(javascript|vbscript|data|blob):/i;function c(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],n=e.querySelectorAll("*");for(const r of n){const e=r.tagName.toLowerCase();if(i.has(e)){t.push(r);continue}if("svg"===e||"http://www.w3.org/2000/svg"===r.namespaceURI){if(Array.from(r.attributes).some(e=>s.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(r);continue}}const n=[];for(const t of r.attributes){const e=t.name.toLowerCase();s.test(e)?n.push(t.name):(l.has(e)&&a.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&n.push(t.name)}n.forEach(e=>r.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}const u={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class d{static dependencies;static manifest;aliases;version="2.17.1";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},n={};for(const r of Object.keys(t))n[r]=this;for(const o of e){const e=o.userConfig;for(const[i,s]of Object.entries(e)){if(void 0===s)continue;if(!(i in t)){t[i]=s,n[i]=o;continue}if(t[i]===s)continue;const e=n[i]?.constructor.name??this.constructor.name,l=o.constructor.name,a=r("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${i}" supplied by both ${e} and ${l}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(a)}}Object.assign(this.userConfig,t)}refreshUserConfigFrom(e){const t=this.userConfig;for(const n of Object.keys(t))delete t[n];Object.assign(t,e.userConfig)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const n=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(n),n.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...u,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),n=parseInt(t,10);if(!isNaN(n))return n}return 200}setIcon(e,t,n){e.dataset.icon=t.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const r=this.#t(t,n);void 0!==r?"string"==typeof r?e.innerHTML=c(r):r instanceof HTMLElement&&(e.innerHTML="",e.appendChild(r.cloneNode(!0))):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const n=document.createElement("span");n.setAttribute("part","sort-indicator"),n.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(n,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(n,"sortNone"));const r=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return r?e.insertBefore(n,r):e.appendChild(n),n}warn(e,t){void 0!==t?console.warn(r(e,t,this.gridElement.id,this.name)):console.warn(`${n(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(r(e,t,this.gridElement.id,this.name))}}function f(e,t,n=!0){let r=e;if(n&&(r=r.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.utility)),t?.length){const e=new Set(t);r=r.filter(t=>e.has(t.field))}return r}async function h(e){try{return await navigator.clipboard.writeText(e),!0}catch(s){t="TBW100",n=`Clipboard API failed: ${s}`,console.warn(r(t,n,o,i));const l=document.createElement("textarea");l.value=e,l.style.position="fixed",l.style.opacity="0",l.style.pointerEvents="none",document.body.appendChild(l),l.select();const a=document.execCommand("copy");return document.body.removeChild(l),a}var t,n,o,i}function g(e,t){const n=t.delimiter??"\t",r=t.newline??"\n",o=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),i=o.length,s=[];let l=[],a=0,c=!1,u=!1;const d=e=>{const t=o.slice(a,e);return u?function(e){let t="",n=!1;for(let r=0;r<e.length;r++){const o=e[r];'"'===o?n?'"'===e[r+1]?(t+='"',r++):n=!1:n=!0:t+=o}return t}(t):t},f=()=>{(l.length>1||l.some(e=>""!==e.trim()))&&s.push(l),l=[]};for(let h=0;h<i;h++){const e=o[h];'"'===e?(u=!0,c?'"'===o[h+1]?h++:c=!1:c=!0):e!==n||c?e!==r||c||(l.push(d(h)),a=h+1,u=!1,f()):(l.push(d(h)),a=h+1,u=!1)}return l.push(d(i)),f(),s}function m(e,t){const{rows:n,target:r,fields:o}=e;if(!r)return;const i=t.rows,s=t.effectiveConfig.columns??[],l=s.map(e=>e.field),a=new Set(t.query("getEditableFields",{columns:s}).flat()),c=[...i],u=r.bounds?r.bounds.endRow:1/0;n.forEach((e,t)=>{const n=r.row+t;if(!(n>u)){if(r.bounds){if(n>=c.length)return}else for(;n>=c.length;){const e={};l.forEach(t=>e[t]=""),c.push(e)}c[n]={...c[n]},e.forEach((e,t)=>{const r=o[t];r&&a.has(r)&&(c[n][r]=e)})}}),t.rows=c}class p extends d{static manifest={queries:[{type:"clipboard:copy",description:"Triggers a copy operation and returns the copied text"}]};static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:"\t",newline:"\n",quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e),e.addEventListener("paste",e=>this.#n(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}handleQuery(e){if("clipboard:copy"===e.type)return this.copy(),!0}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#r(e.target),!0)}#r(e){const t=this.#o();if(t&&0===t.ranges.length){const t=this.#i(e);if(!t)return;const n=this.columns[t.col];if(!n)return;return void this.copy({rowIndices:[t.row],columns:[n.field]})}this.copy()}#n(e){if(this.#s(e.target))return;const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const n=g(t,this.config),r=this.#o(),o=r?.ranges?.[0],i=o?.from.row??0,s=o?.from.col??0,l=o&&("range"===r?.mode||"row"===r?.mode)&&(o.from.row!==o.to.row||o.from.col!==o.to.col)?{endRow:o.to.row,endCol:o.to.col}:null,a=l?.endCol??this.visibleColumns.length-1,c=this.visibleColumns[s],u=c?{row:i,col:s,field:c.field,bounds:l}:null,d=[],f=n[0]?.length??0;for(let g=0;g<f&&s+g<=a;g++){const e=this.visibleColumns[s+g];e&&d.push(e.field)}const h={rows:n,text:t,target:u,fields:d};this.emit("paste",h),this.#l(h)}#l(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??m)(e,this.grid)}#s(e){return e instanceof Element&&!!e.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]')}#o(){const e=this.grid?.query("getSelection");return e?.[0]}#a(e){const t=this.#o();let n,r;if(e?.columns)n=f(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],r=Math.min(e.from.col,e.to.col),o=Math.max(e.from.col,e.to.col);n=f(this.visibleColumns.slice(r,o+1))}else n=f(this.columns);if(e?.rowIndices)r=function(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}(this.rows,e.rowIndices);else if(t?.ranges.length){const e=t.ranges[t.ranges.length-1],n=Math.min(e.from.row,e.to.row),o=Math.max(e.from.row,e.to.row);r=[];for(let t=n;t<=o;t++){const e=this.rows[t];e&&r.push(e)}}else r=this.rows;return{columns:n,rows:r}}#c(e,n,r){const o=r?.delimiter??this.config.delimiter??"\t",i=r?.newline??this.config.newline??"\n",s=r?.includeHeaders??this.config.includeHeaders??!1,l=r?.processCell??this.config.processCell,a=[];s&&a.push(e.map(e=>e.header||e.field).join(o));for(const c of n){const n=e.map(e=>{const n=t(c,e);return l?l(n,e.field,c):this.#u(e,n,c)});a.push(n.join(o))}return a.join(i)}#u(e,t,n){if(e.format)try{const r=e.format(t,n);return null==r?"":String(r)}catch{}if(e.renderer||e.viewRenderer){const t=this.#d(e.field,n);if(null!=t)return t}return function(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}(t)}#d(e,t){const n=this.gridElement;if(!n)return null;const r=this.rows.indexOf(t);if(-1===r)return null;const o=n.querySelector(`.cell[data-row="${r}"][data-field="${e}"]`);return o?o.textContent?.trim()??null:null}#i(e){const t=e.closest("[data-field-cache]");if(!t)return null;const n=t.dataset.fieldCache,r=t.dataset.row;if(!n||!r)return null;const o=parseInt(r,10);if(isNaN(o))return null;const i=this.columns.findIndex(e=>e.field===n);return-1===i?null:{row:o,col:i}}getSelectionAsText(e){const{columns:t,rows:n}=this.#a(e);return 0===t.length||0===n.length?"":this.#c(t,n,e)}async copy(e){const{columns:t,rows:n}=this.#a(e);if(0===t.length||0===n.length)return"";const r=this.#c(t,n,e);return await h(r),this.lastCopied={text:r,timestamp:Date.now()},this.emit("copy",{text:r,rowCount:n.length,columnCount:t.length}),r}async copyRows(e,t){return 0===e.length?"":this.copy({...t,rowIndices:e})}async paste(){const e=await async function(){try{return await navigator.clipboard.readText()}catch{return""}}();return e?g(e,this.config):null}getLastCopied(){return this.lastCopied}}export{p as ClipboardPlugin,m as defaultPasteHandler};
1
+ const e=/* @__PURE__ */new WeakMap;function t(t,n,r=-1){if(!n.valueAccessor)return t?.[n.field];if("object"!=typeof t||null===t)return n.valueAccessor({row:t,column:n,rowIndex:r});const o=t,i=n.field;let s=e.get(o);if(s){const e=s.get(i);if(void 0!==e)return e.v}else s=/* @__PURE__ */new Map,e.set(o,s);const l=n.valueAccessor({row:t,column:n,rowIndex:r});return s.set(i,{v:l}),l}function n(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function r(e,t,r,o){return`${n(r,o)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}const o="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join(""));new RegExp(`__(proto|defineGetter|defineSetter)|${o.slice(3).join("|")}|this\\b`);const i=new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing".split("|")),s=/^on\w+$/i,l=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),a=/^\s*(javascript|vbscript|data|blob):/i;function c(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],n=e.querySelectorAll("*");for(const r of n){const e=r.tagName.toLowerCase();if(i.has(e)){t.push(r);continue}if("svg"===e||"http://www.w3.org/2000/svg"===r.namespaceURI){if(Array.from(r.attributes).some(e=>s.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(r);continue}}const n=[];for(const t of r.attributes){const e=t.name.toLowerCase();s.test(e)?n.push(t.name):(l.has(e)&&a.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&n.push(t.name)}n.forEach(e=>r.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}const u={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class d{static dependencies;static manifest;aliases;version="2.17.2";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},n={};for(const r of Object.keys(t))n[r]=this;for(const o of e){const e=o.userConfig;for(const[i,s]of Object.entries(e)){if(void 0===s)continue;if(!(i in t)){t[i]=s,n[i]=o;continue}if(t[i]===s)continue;const e=n[i]?.constructor.name??this.constructor.name,l=o.constructor.name,a=r("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${i}" supplied by both ${e} and ${l}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(a)}}Object.assign(this.userConfig,t)}refreshUserConfigFrom(e){const t=this.userConfig;for(const n of Object.keys(t))delete t[n];Object.assign(t,e.userConfig)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const n=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(n),n.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...u,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),n=parseInt(t,10);if(!isNaN(n))return n}return 200}setIcon(e,t,n){e.dataset.icon=t.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const r=this.#t(t,n);void 0!==r?"string"==typeof r?e.innerHTML=c(r):r instanceof HTMLElement&&(e.innerHTML="",e.appendChild(r.cloneNode(!0))):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const n=document.createElement("span");n.setAttribute("part","sort-indicator"),n.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(n,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(n,"sortNone"));const r=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return r?e.insertBefore(n,r):e.appendChild(n),n}warn(e,t){void 0!==t?console.warn(r(e,t,this.gridElement.id,this.name)):console.warn(`${n(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(r(e,t,this.gridElement.id,this.name))}}function f(e,t,n=!0){let r=e;if(n&&(r=r.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.utility)),t?.length){const e=new Set(t);r=r.filter(t=>e.has(t.field))}return r}async function h(e){try{return await navigator.clipboard.writeText(e),!0}catch(s){t="TBW100",n=`Clipboard API failed: ${s}`,console.warn(r(t,n,o,i));const l=document.createElement("textarea");l.value=e,l.style.position="fixed",l.style.opacity="0",l.style.pointerEvents="none",document.body.appendChild(l),l.select();const a=document.execCommand("copy");return document.body.removeChild(l),a}var t,n,o,i}function g(e,t){const n=t.delimiter??"\t",r=t.newline??"\n",o=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),i=o.length,s=[];let l=[],a=0,c=!1,u=!1;const d=e=>{const t=o.slice(a,e);return u?function(e){let t="",n=!1;for(let r=0;r<e.length;r++){const o=e[r];'"'===o?n?'"'===e[r+1]?(t+='"',r++):n=!1:n=!0:t+=o}return t}(t):t},f=()=>{(l.length>1||l.some(e=>""!==e.trim()))&&s.push(l),l=[]};for(let h=0;h<i;h++){const e=o[h];'"'===e?(u=!0,c?'"'===o[h+1]?h++:c=!1:c=!0):e!==n||c?e!==r||c||(l.push(d(h)),a=h+1,u=!1,f()):(l.push(d(h)),a=h+1,u=!1)}return l.push(d(i)),f(),s}function m(e,t){const{rows:n,target:r,fields:o}=e;if(!r)return;const i=t.rows,s=t.effectiveConfig.columns??[],l=s.map(e=>e.field),a=new Set(t.query("getEditableFields",{columns:s}).flat()),c=[...i],u=r.bounds?r.bounds.endRow:1/0;n.forEach((e,t)=>{const n=r.row+t;if(!(n>u)){if(r.bounds){if(n>=c.length)return}else for(;n>=c.length;){const e={};l.forEach(t=>e[t]=""),c.push(e)}c[n]={...c[n]},e.forEach((e,t)=>{const r=o[t];r&&a.has(r)&&(c[n][r]=e)})}}),t.rows=c}class p extends d{static manifest={queries:[{type:"clipboard:copy",description:"Triggers a copy operation and returns the copied text"}]};static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:"\t",newline:"\n",quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e),e.addEventListener("paste",e=>this.#n(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}handleQuery(e){if("clipboard:copy"===e.type)return this.copy(),!0}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#r(e.target),!0)}#r(e){const t=this.#o();if(t&&0===t.ranges.length){const t=this.#i(e);if(!t)return;const n=this.columns[t.col];if(!n)return;return void this.copy({rowIndices:[t.row],columns:[n.field]})}this.copy()}#n(e){if(this.#s(e.target))return;const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const n=g(t,this.config),r=this.#o(),o=r?.ranges?.[0],i=o?.from.row??0,s=o?.from.col??0,l=o&&("range"===r?.mode||"row"===r?.mode)&&(o.from.row!==o.to.row||o.from.col!==o.to.col)?{endRow:o.to.row,endCol:o.to.col}:null,a=l?.endCol??this.visibleColumns.length-1,c=this.visibleColumns[s],u=c?{row:i,col:s,field:c.field,bounds:l}:null,d=[],f=n[0]?.length??0;for(let g=0;g<f&&s+g<=a;g++){const e=this.visibleColumns[s+g];e&&d.push(e.field)}const h={rows:n,text:t,target:u,fields:d};this.emit("paste",h),this.#l(h)}#l(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??m)(e,this.grid)}#s(e){return e instanceof Element&&!!e.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]')}#o(){const e=this.grid?.query("getSelection");return e?.[0]}#a(e){const t=this.#o();let n,r;if(e?.columns)n=f(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],r=Math.min(e.from.col,e.to.col),o=Math.max(e.from.col,e.to.col);n=f(this.visibleColumns.slice(r,o+1))}else n=f(this.columns);if(e?.rowIndices)r=function(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}(this.rows,e.rowIndices);else if(t?.ranges.length){const e=t.ranges[t.ranges.length-1],n=Math.min(e.from.row,e.to.row),o=Math.max(e.from.row,e.to.row);r=[];for(let t=n;t<=o;t++){const e=this.rows[t];e&&r.push(e)}}else r=this.rows;return{columns:n,rows:r}}#c(e,n,r){const o=r?.delimiter??this.config.delimiter??"\t",i=r?.newline??this.config.newline??"\n",s=r?.includeHeaders??this.config.includeHeaders??!1,l=r?.processCell??this.config.processCell,a=[];s&&a.push(e.map(e=>e.header||e.field).join(o));for(const c of n){const n=e.map(e=>{const n=t(c,e);return l?l(n,e.field,c):this.#u(e,n,c)});a.push(n.join(o))}return a.join(i)}#u(e,t,n){if(e.format)try{const r=e.format(t,n);return null==r?"":String(r)}catch{}if(e.renderer||e.viewRenderer){const t=this.#d(e.field,n);if(null!=t)return t}return function(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}(t)}#d(e,t){const n=this.gridElement;if(!n)return null;const r=this.rows.indexOf(t);if(-1===r)return null;const o=n.querySelector(`.cell[data-row="${r}"][data-field="${e}"]`);return o?o.textContent?.trim()??null:null}#i(e){const t=e.closest("[data-field-cache]");if(!t)return null;const n=t.dataset.fieldCache,r=t.dataset.row;if(!n||!r)return null;const o=parseInt(r,10);if(isNaN(o))return null;const i=this.columns.findIndex(e=>e.field===n);return-1===i?null:{row:o,col:i}}getSelectionAsText(e){const{columns:t,rows:n}=this.#a(e);return 0===t.length||0===n.length?"":this.#c(t,n,e)}async copy(e){const{columns:t,rows:n}=this.#a(e);if(0===t.length||0===n.length)return"";const r=this.#c(t,n,e);return await h(r),this.lastCopied={text:r,timestamp:Date.now()},this.emit("copy",{text:r,rowCount:n.length,columnCount:t.length}),r}async copyRows(e,t){return 0===e.length?"":this.copy({...t,rowIndices:e})}async paste(){const e=await async function(){try{return await navigator.clipboard.readText()}catch{return""}}();return e?g(e,this.config):null}getLastCopied(){return this.lastCopied}}export{p as ClipboardPlugin,m as defaultPasteHandler};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- function t(t,e){return`[tbw-grid${t?`#${t}`:""}${e?`:${e}`:""}]`}function e(e,r,s,i){return`${t(s,i)} ${e}: ${r}\n\n → More info: ${function(t){return`https://toolboxjs.com/grid/errors#${t.toLowerCase()}`}(e)}`}const r="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(t=>t.split("").reverse().join(""));new RegExp(`__(proto|defineGetter|defineSetter)|${r.slice(3).join("|")}|this\\b`);const s=new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing".split("|")),i=/^on\w+$/i,n=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),o=/^\s*(javascript|vbscript|data|blob):/i;function l(t){if(!t||"string"!=typeof t)return"";if(-1===t.indexOf("<"))return t;const e=document.createElement("template");return e.innerHTML=t,function(t){const e=[],r=t.querySelectorAll("*");for(const l of r){const t=l.tagName.toLowerCase();if(s.has(t)){e.push(l);continue}if("svg"===t||"http://www.w3.org/2000/svg"===l.namespaceURI){if(Array.from(l.attributes).some(t=>i.test(t.name)||"href"===t.name||"xlink:href"===t.name)){e.push(l);continue}}const r=[];for(const e of l.attributes){const t=e.name.toLowerCase();i.test(t)?r.push(e.name):(n.has(t)&&o.test(e.value)||"style"===t&&/expression\s*\(|javascript:|behavior\s*:/i.test(e.value))&&r.push(e.name)}r.forEach(t=>l.removeAttribute(t))}e.forEach(t=>t.remove())}(e.content),e.innerHTML}const a={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class c{static dependencies;static manifest;aliases;version="2.17.1";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#t;get defaultConfig(){return{}}constructor(t={}){this.userConfig=t}get resolvedConfig(){return this.#t?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(t){if(0===t.length)return;const r={...this.userConfig},s={};for(const e of Object.keys(r))s[e]=this;for(const i of t){const t=i.userConfig;for(const[n,o]of Object.entries(t)){if(void 0===o)continue;if(!(n in r)){r[n]=o,s[n]=i;continue}if(r[n]===o)continue;const t=s[n]?.constructor.name??this.constructor.name,l=i.constructor.name,a=e("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${n}" supplied by both ${t} and ${l}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(a)}}Object.assign(this.userConfig,r)}refreshUserConfigFrom(t){const e=this.userConfig;for(const r of Object.keys(e))delete e[r];Object.assign(e,t.userConfig)}attach(t){this.#t?.abort(),this.#t=new AbortController,this.grid=t,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#t?.abort(),this.#t=void 0}getPlugin(t){return this.grid?.getPlugin(t)}emit(t,e){this.grid?.dispatchEvent?.(new CustomEvent(t,{detail:e,bubbles:!0}))}emitCancelable(t,e){const r=new CustomEvent(t,{detail:e,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(r),r.defaultPrevented}on(t,e){this.grid?._pluginManager?.subscribe(this,t,e)}off(t){this.grid?._pluginManager?.unsubscribe(this,t)}emitPluginEvent(t,e){this.grid?._pluginManager?.emitPluginEvent(t,e)}broadcast(t,e){this.emitPluginEvent(t,e),this.emit(t,e)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#t?.signal??this.grid?.disconnectSignal}get gridIcons(){const t=this.grid?.gridConfig?.icons??{};return{...a,...t}}get isAnimationEnabled(){const t=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===t||"off"===t)return!1;if(!0===t||"on"===t)return!0;const e=this.gridElement;if(e){return"0"!==getComputedStyle(e).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const t=this.gridElement;if(t){const e=getComputedStyle(t).getPropertyValue("--tbw-animation-duration").trim(),r=parseInt(e,10);if(!isNaN(r))return r}return 200}setIcon(t,e,r){t.dataset.icon=e.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===e?t.dataset.expanded="":"expand"===e&&delete t.dataset.expanded;const s=this.#e(e,r);void 0!==s?"string"==typeof s?t.innerHTML=l(s):s instanceof HTMLElement&&(t.innerHTML="",t.appendChild(s.cloneNode(!0))):t.innerHTML=""}#e(t,e){return void 0!==e?e:this.grid?.gridConfig?.icons?.[t]}updateSortIndicator(t,e){t.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const r=document.createElement("span");r.setAttribute("part","sort-indicator"),r.className="sort-indicator",e?(t.setAttribute("aria-sort","asc"===e?"ascending":"descending"),t.setAttribute("data-sort",e),this.setIcon(r,"asc"===e?"sortAsc":"sortDesc")):(t.setAttribute("aria-sort","none"),t.removeAttribute("data-sort"),this.setIcon(r,"sortNone"));const s=t.querySelector(".tbw-filter-btn")??t.querySelector(".resize-handle");return s?t.insertBefore(r,s):t.appendChild(r),r}warn(r,s){void 0!==s?console.warn(e(r,s,this.gridElement.id,this.name)):console.warn(`${t(this.gridElement.id,this.name)} ${r}`)}throwDiagnostic(t,r){throw new Error(e(t,r,this.gridElement.id,this.name))}}function u(t){if(null==t)return 100;if("number"==typeof t)return t;const e=parseFloat(t);return isNaN(e)?100:e}function d(t){return t.map(t=>u(t.width))}function h(t){const e=[];let r=0;for(const s of t)e.push(r),r+=u(s.width);return e}function f(t){return t.reduce((t,e)=>t+u(e.width),0)}function g(t,e,r,s,i){const n=r.length;if(0===n)return{startCol:0,endCol:0,visibleColumns:[]};let o=function(t,e,r){let s=0,i=e.length-1;for(;s<i;){const n=Math.floor((s+i)/2);e[n]+r[n]<=t?s=n+1:i=n}return s}(t,r,s);o=Math.max(0,o-i);const l=t+e;let a=o;for(let u=o;u<n;u++){if(r[u]>=l){a=u-1;break}a=u}a=Math.min(n-1,a+i);const c=[];for(let u=o;u<=a;u++)c.push(u);return{startCol:o,endCol:a,visibleColumns:c}}class m extends c{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(t){super.attach(t);const e=this.columns;this.columnWidths=d(e),this.columnOffsets=h(e),this.totalWidth=f(e),this.endCol=e.length-1}detach(){this.#r(),this.columnWidths=[],this.columnOffsets=[],this.originalColumns=[],this.isVirtualized=!1,this.startCol=0,this.endCol=0,this.scrollLeft=0,this.totalWidth=0}#r(){const t=this.gridElement;if(!t)return;const e=t.querySelector(".header-row");e&&(e.style.paddingLeft="",e.style.minWidth="");t.querySelectorAll(".data-grid-row").forEach(t=>{t.style.paddingLeft=""});const r=t.querySelector(".rows-viewport .rows");r&&(r.style.width="");const s=t.querySelector(".rows-body");s&&(s.style.minWidth="")}processColumns(t){(0===this.originalColumns.length||t.length>=this.originalColumns.length)&&(this.originalColumns=t,this.columnWidths=d(t),this.columnOffsets=h(t),this.totalWidth=f(t));const e=this.originalColumns,r=(s=e.length,i=this.config.threshold??30,!!(this.config.autoEnable??!0)&&s>i);var s,i;if(this.isVirtualized=r??!1,!r)return this.startCol=0,this.endCol=e.length-1,[...e];const n=this.grid?.clientWidth||800,o=g(this.scrollLeft,n,this.columnOffsets,this.columnWidths,this.config.overscan??3);return this.startCol=o.startCol,this.endCol=o.endCol,o.visibleColumns.map(t=>e[t])}afterRender(){if(!this.isVirtualized)return;const t=this.gridElement;if(!t)return;const e=this.columnOffsets[this.startCol]??0,r=t.querySelector(".header-row"),s=t.querySelectorAll(".data-grid-row");r&&(r.style.paddingLeft=`${e}px`,r.style.minWidth=`${this.totalWidth}px`),s.forEach(t=>{t.style.paddingLeft=`${e}px`});const i=t.querySelector(".rows-viewport .rows");i&&(i.style.width=`${this.totalWidth}px`);const n=t.querySelector(".rows-body");n&&(n.style.minWidth=`${this.totalWidth}px`)}onScroll(t){if(!this.isVirtualized)return;Math.abs(t.scrollLeft-this.scrollLeft)<1||(this.scrollLeft=t.scrollLeft,this.requestColumnsRender())}getIsVirtualized(){return this.isVirtualized}getVisibleColumnRange(){return{start:this.startCol,end:this.endCol}}scrollToColumn(t){const e=this.columnOffsets[t]??0,r=this.gridElement;r&&(r.scrollLeft=e)}getColumnOffset(t){return this.columnOffsets[t]??0}getTotalWidth(){return this.totalWidth}}export{m as ColumnVirtualizationPlugin};
1
+ function t(t,e){return`[tbw-grid${t?`#${t}`:""}${e?`:${e}`:""}]`}function e(e,r,s,i){return`${t(s,i)} ${e}: ${r}\n\n → More info: ${function(t){return`https://toolboxjs.com/grid/errors#${t.toLowerCase()}`}(e)}`}const r="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(t=>t.split("").reverse().join(""));new RegExp(`__(proto|defineGetter|defineSetter)|${r.slice(3).join("|")}|this\\b`);const s=new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing".split("|")),i=/^on\w+$/i,n=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),o=/^\s*(javascript|vbscript|data|blob):/i;function l(t){if(!t||"string"!=typeof t)return"";if(-1===t.indexOf("<"))return t;const e=document.createElement("template");return e.innerHTML=t,function(t){const e=[],r=t.querySelectorAll("*");for(const l of r){const t=l.tagName.toLowerCase();if(s.has(t)){e.push(l);continue}if("svg"===t||"http://www.w3.org/2000/svg"===l.namespaceURI){if(Array.from(l.attributes).some(t=>i.test(t.name)||"href"===t.name||"xlink:href"===t.name)){e.push(l);continue}}const r=[];for(const e of l.attributes){const t=e.name.toLowerCase();i.test(t)?r.push(e.name):(n.has(t)&&o.test(e.value)||"style"===t&&/expression\s*\(|javascript:|behavior\s*:/i.test(e.value))&&r.push(e.name)}r.forEach(t=>l.removeAttribute(t))}e.forEach(t=>t.remove())}(e.content),e.innerHTML}const a={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class c{static dependencies;static manifest;aliases;version="2.17.2";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#t;get defaultConfig(){return{}}constructor(t={}){this.userConfig=t}get resolvedConfig(){return this.#t?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(t){if(0===t.length)return;const r={...this.userConfig},s={};for(const e of Object.keys(r))s[e]=this;for(const i of t){const t=i.userConfig;for(const[n,o]of Object.entries(t)){if(void 0===o)continue;if(!(n in r)){r[n]=o,s[n]=i;continue}if(r[n]===o)continue;const t=s[n]?.constructor.name??this.constructor.name,l=i.constructor.name,a=e("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${n}" supplied by both ${t} and ${l}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(a)}}Object.assign(this.userConfig,r)}refreshUserConfigFrom(t){const e=this.userConfig;for(const r of Object.keys(e))delete e[r];Object.assign(e,t.userConfig)}attach(t){this.#t?.abort(),this.#t=new AbortController,this.grid=t,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#t?.abort(),this.#t=void 0}getPlugin(t){return this.grid?.getPlugin(t)}emit(t,e){this.grid?.dispatchEvent?.(new CustomEvent(t,{detail:e,bubbles:!0}))}emitCancelable(t,e){const r=new CustomEvent(t,{detail:e,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(r),r.defaultPrevented}on(t,e){this.grid?._pluginManager?.subscribe(this,t,e)}off(t){this.grid?._pluginManager?.unsubscribe(this,t)}emitPluginEvent(t,e){this.grid?._pluginManager?.emitPluginEvent(t,e)}broadcast(t,e){this.emitPluginEvent(t,e),this.emit(t,e)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#t?.signal??this.grid?.disconnectSignal}get gridIcons(){const t=this.grid?.gridConfig?.icons??{};return{...a,...t}}get isAnimationEnabled(){const t=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===t||"off"===t)return!1;if(!0===t||"on"===t)return!0;const e=this.gridElement;if(e){return"0"!==getComputedStyle(e).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const t=this.gridElement;if(t){const e=getComputedStyle(t).getPropertyValue("--tbw-animation-duration").trim(),r=parseInt(e,10);if(!isNaN(r))return r}return 200}setIcon(t,e,r){t.dataset.icon=e.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===e?t.dataset.expanded="":"expand"===e&&delete t.dataset.expanded;const s=this.#e(e,r);void 0!==s?"string"==typeof s?t.innerHTML=l(s):s instanceof HTMLElement&&(t.innerHTML="",t.appendChild(s.cloneNode(!0))):t.innerHTML=""}#e(t,e){return void 0!==e?e:this.grid?.gridConfig?.icons?.[t]}updateSortIndicator(t,e){t.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const r=document.createElement("span");r.setAttribute("part","sort-indicator"),r.className="sort-indicator",e?(t.setAttribute("aria-sort","asc"===e?"ascending":"descending"),t.setAttribute("data-sort",e),this.setIcon(r,"asc"===e?"sortAsc":"sortDesc")):(t.setAttribute("aria-sort","none"),t.removeAttribute("data-sort"),this.setIcon(r,"sortNone"));const s=t.querySelector(".tbw-filter-btn")??t.querySelector(".resize-handle");return s?t.insertBefore(r,s):t.appendChild(r),r}warn(r,s){void 0!==s?console.warn(e(r,s,this.gridElement.id,this.name)):console.warn(`${t(this.gridElement.id,this.name)} ${r}`)}throwDiagnostic(t,r){throw new Error(e(t,r,this.gridElement.id,this.name))}}function u(t){if(null==t)return 100;if("number"==typeof t)return t;const e=parseFloat(t);return isNaN(e)?100:e}function d(t){return t.map(t=>u(t.width))}function h(t){const e=[];let r=0;for(const s of t)e.push(r),r+=u(s.width);return e}function f(t){return t.reduce((t,e)=>t+u(e.width),0)}function g(t,e,r,s,i){const n=r.length;if(0===n)return{startCol:0,endCol:0,visibleColumns:[]};let o=function(t,e,r){let s=0,i=e.length-1;for(;s<i;){const n=Math.floor((s+i)/2);e[n]+r[n]<=t?s=n+1:i=n}return s}(t,r,s);o=Math.max(0,o-i);const l=t+e;let a=o;for(let u=o;u<n;u++){if(r[u]>=l){a=u-1;break}a=u}a=Math.min(n-1,a+i);const c=[];for(let u=o;u<=a;u++)c.push(u);return{startCol:o,endCol:a,visibleColumns:c}}class m extends c{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(t){super.attach(t);const e=this.columns;this.columnWidths=d(e),this.columnOffsets=h(e),this.totalWidth=f(e),this.endCol=e.length-1}detach(){this.#r(),this.columnWidths=[],this.columnOffsets=[],this.originalColumns=[],this.isVirtualized=!1,this.startCol=0,this.endCol=0,this.scrollLeft=0,this.totalWidth=0}#r(){const t=this.gridElement;if(!t)return;const e=t.querySelector(".header-row");e&&(e.style.paddingLeft="",e.style.minWidth="");t.querySelectorAll(".data-grid-row").forEach(t=>{t.style.paddingLeft=""});const r=t.querySelector(".rows-viewport .rows");r&&(r.style.width="");const s=t.querySelector(".rows-body");s&&(s.style.minWidth="")}processColumns(t){(0===this.originalColumns.length||t.length>=this.originalColumns.length)&&(this.originalColumns=t,this.columnWidths=d(t),this.columnOffsets=h(t),this.totalWidth=f(t));const e=this.originalColumns,r=(s=e.length,i=this.config.threshold??30,!!(this.config.autoEnable??!0)&&s>i);var s,i;if(this.isVirtualized=r??!1,!r)return this.startCol=0,this.endCol=e.length-1,[...e];const n=this.grid?.clientWidth||800,o=g(this.scrollLeft,n,this.columnOffsets,this.columnWidths,this.config.overscan??3);return this.startCol=o.startCol,this.endCol=o.endCol,o.visibleColumns.map(t=>e[t])}afterRender(){if(!this.isVirtualized)return;const t=this.gridElement;if(!t)return;const e=this.columnOffsets[this.startCol]??0,r=t.querySelector(".header-row"),s=t.querySelectorAll(".data-grid-row");r&&(r.style.paddingLeft=`${e}px`,r.style.minWidth=`${this.totalWidth}px`),s.forEach(t=>{t.style.paddingLeft=`${e}px`});const i=t.querySelector(".rows-viewport .rows");i&&(i.style.width=`${this.totalWidth}px`);const n=t.querySelector(".rows-body");n&&(n.style.minWidth=`${this.totalWidth}px`)}onScroll(t){if(!this.isVirtualized)return;Math.abs(t.scrollLeft-this.scrollLeft)<1||(this.scrollLeft=t.scrollLeft,this.requestColumnsRender())}getIsVirtualized(){return this.isVirtualized}getVisibleColumnRange(){return{start:this.startCol,end:this.endCol}}scrollToColumn(t){const e=this.columnOffsets[t]??0,r=this.gridElement;r&&(r.scrollLeft=e)}getColumnOffset(t){return this.columnOffsets[t]??0}getTotalWidth(){return this.totalWidth}}export{m as ColumnVirtualizationPlugin};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- function e(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function t(t,n,o,r){return`${e(o,r)} ${t}: ${n}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(t)}`}const n="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join(""));new RegExp(`__(proto|defineGetter|defineSetter)|${n.slice(3).join("|")}|this\\b`);const o=new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing".split("|")),r=/^on\w+$/i,s=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),i=/^\s*(javascript|vbscript|data|blob):/i;function a(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],n=e.querySelectorAll("*");for(const a of n){const e=a.tagName.toLowerCase();if(o.has(e)){t.push(a);continue}if("svg"===e||"http://www.w3.org/2000/svg"===a.namespaceURI){if(Array.from(a.attributes).some(e=>r.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(a);continue}}const n=[];for(const t of a.attributes){const e=t.name.toLowerCase();r.test(e)?n.push(t.name):(s.has(e)&&i.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&n.push(t.name)}n.forEach(e=>a.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}const c={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};function l(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase()}class u{static dependencies;static manifest;aliases;version="2.17.1";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const n={...this.userConfig},o={};for(const t of Object.keys(n))o[t]=this;for(const r of e){const e=r.userConfig;for(const[s,i]of Object.entries(e)){if(void 0===i)continue;if(!(s in n)){n[s]=i,o[s]=r;continue}if(n[s]===i)continue;const e=o[s]?.constructor.name??this.constructor.name,a=r.constructor.name,c=t("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${s}" supplied by both ${e} and ${a}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(c)}}Object.assign(this.userConfig,n)}refreshUserConfigFrom(e){const t=this.userConfig;for(const n of Object.keys(t))delete t[n];Object.assign(t,e.userConfig)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const n=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(n),n.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...c,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),n=parseInt(t,10);if(!isNaN(n))return n}return 200}setIcon(e,t,n){e.dataset.icon=l(t),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const o=this.#t(t,n);void 0!==o?"string"==typeof o?e.innerHTML=a(o):o instanceof HTMLElement&&(e.innerHTML="",e.appendChild(o.cloneNode(!0))):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const n=document.createElement("span");n.setAttribute("part","sort-indicator"),n.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(n,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(n,"sortNone"));const o=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return o?e.insertBefore(n,o):e.appendChild(n),n}warn(n,o){void 0!==o?console.warn(t(n,o,this.gridElement.id,this.name)):console.warn(`${e(this.gridElement.id,this.name)} ${n}`)}throwDiagnostic(e,n){throw new Error(t(e,n,this.gridElement.id,this.name))}}const d="@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 m(e,t){return("function"==typeof e?e(t):e).filter(e=>!0!==e.hidden&&("function"!=typeof e.hidden||!e.hidden(t)))}function h(e,t){return!0===e.disabled||"function"==typeof e.disabled&&e.disabled(t)}function b(e,t,n,o){const r=document.createElement("div");r.className="tbw-context-menu",r.setAttribute("role","menu");const s=e.some(e=>!e.separator&&e.icon);for(const i of e){if(i.separator){const e=document.createElement("div");e.className="tbw-context-menu-separator",e.setAttribute("role","separator"),r.appendChild(e);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",i.cssClass&&e.classList.add(i.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",i.id),e.setAttribute("tabindex","-1");const c=h(i,t);if(c&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),i.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=a(i.icon),e.appendChild(t)}else if(s){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML="&nbsp;",e.appendChild(t)}const u=document.createElement("span");if(u.className="tbw-context-menu-label",u.textContent=i.name,e.appendChild(u),i.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(i.shortcut))i.shortcut.forEach((e,n)=>{n>0&&t.appendChild(document.createTextNode("+"));const o=document.createElement("kbd");o.textContent=e,t.appendChild(o)});else{const e=document.createElement("kbd");e.textContent=i.shortcut,t.appendChild(e)}e.appendChild(t)}if(i.subMenu?.length){const r=document.createElement("span");r.className="tbw-context-menu-arrow",r.dataset.icon=l("submenuArrow"),void 0!==o&&("string"==typeof o?r.innerHTML=a(o):o instanceof HTMLElement&&r.appendChild(o.cloneNode(!0))),e.appendChild(r),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!i.subMenu)return;const r=b(m(i.subMenu,t),t,n,o);r.classList.add("tbw-context-submenu"),r.style.position="absolute",r.style.left="100%",r.style.top="0",e.style.position="relative",e.appendChild(r)}),e.addEventListener("mouseleave",()=>{const t=e.querySelector(".tbw-context-menu");t&&t.remove()})}c||!i.action||i.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),n(i)}),r.appendChild(e)}return r}const p="getContextMenuItems";let f=null,g=null,w=0;const x=/* @__PURE__ */new Set,v=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:e=>{const t=e.grid;t?.query?.("clipboard:copy")}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:e=>{const t=e.grid;t?.query?.("export:csv")}}];class y extends u{static manifest={queries:[{type:p,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:v}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),w++,x.add(this)}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,x.delete(this),this.uninstallGlobalHandlers()}syncSelectionOnContextMenu(e){if(e<0)return[];const t=this.grid?.query("getSelectedRowIndices"),n=t?.[0];return n?n.includes(e)?n:(this.grid?.query("selectRows",[e]),[e]):[e]}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size","--tbw-icon-submenu-arrow"];copyGridStyles(e){const t=this.gridElement;if(!t)return;const n=getComputedStyle(t),o=[],r=n.getPropertyValue("color-scheme").trim();r&&o.push(`color-scheme: ${r}`);for(const s of y.CSS_VARS_TO_COPY){const e=n.getPropertyValue(s).trim();e&&o.push(`${s}: ${e}`)}if(o.length>0){const t=e.getAttribute("style")||"";e.setAttribute("style",t+o.join("; ")+";")}}installGlobalHandlers(){if(!g&&"undefined"!=typeof document&&d&&(g=document.createElement("style"),g.id="tbw-context-menu-styles",g.textContent=d,document.head.appendChild(g)),!f){f=new AbortController;const e=f.signal,t=()=>{for(const e of x)e.isMenuOpen()&&e.hideMenu();document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())};document.addEventListener("click",t,{signal:e}),document.addEventListener("keydown",e=>{"Escape"===e.key&&t()},{signal:e}),document.addEventListener("scroll",t,{capture:!0,signal:e})}}uninstallGlobalHandlers(){w--,w>0||(f&&(f.abort(),f=null),g&&(g.remove(),g=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(p,e),n=[];for(const o of t)Array.isArray(o)&&n.push(...o);return n.sort((e,t)=>(e.order??100)-(t.order??100)),this.insertGroupSeparators(n)}insertGroupSeparators(e){if(e.length<=1)return e;const t=[];let n=-1;for(const o of e){if(o.separator){t.push(o);continue}const e=Math.floor((o.order??100)/10);n>=0&&e!==n&&t.push({id:`__sep-${n}-${e}`,label:"",separator:!0,action:()=>{}}),n=e,t.push(o)}return t}convertPluginItems(e){return e.map(e=>({id:e.id,name:e.label,icon:e.icon,shortcut:e.shortcut,disabled:e.disabled??!1,action:()=>e.action(),separator:e.separator,cssClass:e.cssClass}))}openMenuAt(e,t,n,o=!1){this.params=e,this.position={x:t,y:n};const r=this.collectPluginItems(e);let s=m(this.config.items??v,e);if(r.length>0){const e=this.convertPluginItems(r);s=s.length>0&&e.length>0?[...s,{id:"__plugin-sep",name:"",separator:!0},...e]:[...s,...e]}var i,a;(s=function(e){const t=[];for(const n of e)n.separator&&(0===t.length||t[t.length-1].separator)||t.push(n);return t.length>0&&t[t.length-1].separator&&t.pop(),t}(s),s.length)&&(document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove()),this.menuElement=null,this.menuElement=b(s,e,t=>{t.action&&t.action(e),this.hideMenu()},this.grid?.gridConfig?.icons?.submenuArrow),i=this.menuElement,a=()=>this.hideMenu(),i.addEventListener("keydown",e=>{const t=Array.from(i.querySelectorAll('[role="menuitem"]:not(.disabled)'));if(!t.length)return;const n=document.activeElement,o=t.indexOf(n);switch(e.key){case"ArrowDown":e.preventDefault(),t[o<t.length-1?o+1:0].focus();break;case"ArrowUp":e.preventDefault(),t[o>0?o-1:t.length-1].focus();break;case"Enter":case" ":e.preventDefault(),n&&t.includes(n)&&n.click();break;case"Escape":e.preventDefault(),a()}}),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),function(e,t,n){e.style.position="fixed",e.style.left=`${t}px`,e.style.top=`${n}px`,e.style.visibility="hidden",e.style.zIndex="10000";const o=e.getBoundingClientRect(),r=window.innerWidth,s=window.innerHeight;let i=t,a=n;t+o.width>r&&(i=t-o.width),n+o.height>s&&(a=n-o.height),i=Math.max(0,i),a=Math.max(0,a),e.style.left=`${i}px`,e.style.top=`${a}px`,e.style.visibility="visible"}(this.menuElement,t,n),this.isOpen=!0,o&&function(e){const t=e.querySelector('[role="menuitem"]:not(.disabled)');t?.focus()}(this.menuElement),this.emit("context-menu-open",{params:e,items:s}))}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root");t&&"true"!==t.getAttribute("data-context-menu-bound")&&(t.setAttribute("data-context-menu-bound","true"),t.addEventListener("contextmenu",e=>{const t=e;t.preventDefault();const n=t.target,o=n.closest("[data-row][data-col]"),r=n.closest('[part~="header-cell"]');let s;if(o){const e=parseInt(o.getAttribute("data-row")??"-1",10),n=parseInt(o.getAttribute("data-col")??"-1",10),r=this.visibleColumns[n],i=this.rows[e],a=this.syncSelectionOnContextMenu(e);s={row:i,rowIndex:e,column:r,columnIndex:n,field:r?.field??"",value:i?.[r?.field]??null,isHeader:!1,event:t,selectedRows:a}}else{if(!r)return;{const e=parseInt(r.getAttribute("data-col")??"-1",10),n=this.visibleColumns[e];s={row:null,rowIndex:-1,column:n,columnIndex:e,field:n?.field??"",value:null,isHeader:!0,event:t,selectedRows:[]}}}this.openMenuAt(s,t.clientX,t.clientY)}))}onKeyDown(e){const t="F10"===e.key&&e.shiftKey,n="ContextMenu"===e.key;if(!t&&!n)return;e.preventDefault();const o=this.grid;if(!o)return;const r=o._focusRow,s=o._focusCol,i=this.visibleColumns[s],a=this.rows[r],c=this.gridElement,l=c?.querySelector(`[data-row="${r}"][data-col="${s}"]`);let u=0,d=0;if(l){const e=l.getBoundingClientRect();u=e.left+e.width/2,d=e.bottom}const m=this.syncSelectionOnContextMenu(r),h={row:a,rowIndex:r,column:i,columnIndex:s,field:i?.field??"",value:a?.[i?.field]??null,isHeader:!1,event:e,selectedRows:m};return this.openMenuAt(h,u,d,!0),!0}showMenu(e,t,n){const o={row:n.row??null,rowIndex:n.rowIndex??-1,column:n.column??null,columnIndex:n.columnIndex??-1,field:n.field??"",value:n.value??null,isHeader:n.isHeader??!1,event:n.event??new MouseEvent("contextmenu"),selectedRows:n.selectedRows??[]};this.openMenuAt(o,e,t)}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen&&(this.isOpen=!1)}isMenuOpen(){return this.isOpen}}export{y as ContextMenuPlugin};
1
+ function e(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function t(t,n,o,r){return`${e(o,r)} ${t}: ${n}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(t)}`}const n="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join(""));new RegExp(`__(proto|defineGetter|defineSetter)|${n.slice(3).join("|")}|this\\b`);const o=new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing".split("|")),r=/^on\w+$/i,s=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),i=/^\s*(javascript|vbscript|data|blob):/i;function a(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],n=e.querySelectorAll("*");for(const a of n){const e=a.tagName.toLowerCase();if(o.has(e)){t.push(a);continue}if("svg"===e||"http://www.w3.org/2000/svg"===a.namespaceURI){if(Array.from(a.attributes).some(e=>r.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(a);continue}}const n=[];for(const t of a.attributes){const e=t.name.toLowerCase();r.test(e)?n.push(t.name):(s.has(e)&&i.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&n.push(t.name)}n.forEach(e=>a.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}const c={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};function l(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase()}class u{static dependencies;static manifest;aliases;version="2.17.2";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const n={...this.userConfig},o={};for(const t of Object.keys(n))o[t]=this;for(const r of e){const e=r.userConfig;for(const[s,i]of Object.entries(e)){if(void 0===i)continue;if(!(s in n)){n[s]=i,o[s]=r;continue}if(n[s]===i)continue;const e=o[s]?.constructor.name??this.constructor.name,a=r.constructor.name,c=t("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${s}" supplied by both ${e} and ${a}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(c)}}Object.assign(this.userConfig,n)}refreshUserConfigFrom(e){const t=this.userConfig;for(const n of Object.keys(t))delete t[n];Object.assign(t,e.userConfig)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const n=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(n),n.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...c,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),n=parseInt(t,10);if(!isNaN(n))return n}return 200}setIcon(e,t,n){e.dataset.icon=l(t),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const o=this.#t(t,n);void 0!==o?"string"==typeof o?e.innerHTML=a(o):o instanceof HTMLElement&&(e.innerHTML="",e.appendChild(o.cloneNode(!0))):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const n=document.createElement("span");n.setAttribute("part","sort-indicator"),n.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(n,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(n,"sortNone"));const o=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return o?e.insertBefore(n,o):e.appendChild(n),n}warn(n,o){void 0!==o?console.warn(t(n,o,this.gridElement.id,this.name)):console.warn(`${e(this.gridElement.id,this.name)} ${n}`)}throwDiagnostic(e,n){throw new Error(t(e,n,this.gridElement.id,this.name))}}const d="@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 m(e,t){return("function"==typeof e?e(t):e).filter(e=>!0!==e.hidden&&("function"!=typeof e.hidden||!e.hidden(t)))}function h(e,t){return!0===e.disabled||"function"==typeof e.disabled&&e.disabled(t)}function b(e,t,n,o){const r=document.createElement("div");r.className="tbw-context-menu",r.setAttribute("role","menu");const s=e.some(e=>!e.separator&&e.icon);for(const i of e){if(i.separator){const e=document.createElement("div");e.className="tbw-context-menu-separator",e.setAttribute("role","separator"),r.appendChild(e);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",i.cssClass&&e.classList.add(i.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",i.id),e.setAttribute("tabindex","-1");const c=h(i,t);if(c&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),i.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=a(i.icon),e.appendChild(t)}else if(s){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML="&nbsp;",e.appendChild(t)}const u=document.createElement("span");if(u.className="tbw-context-menu-label",u.textContent=i.name,e.appendChild(u),i.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(i.shortcut))i.shortcut.forEach((e,n)=>{n>0&&t.appendChild(document.createTextNode("+"));const o=document.createElement("kbd");o.textContent=e,t.appendChild(o)});else{const e=document.createElement("kbd");e.textContent=i.shortcut,t.appendChild(e)}e.appendChild(t)}if(i.subMenu?.length){const r=document.createElement("span");r.className="tbw-context-menu-arrow",r.dataset.icon=l("submenuArrow"),void 0!==o&&("string"==typeof o?r.innerHTML=a(o):o instanceof HTMLElement&&r.appendChild(o.cloneNode(!0))),e.appendChild(r),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!i.subMenu)return;const r=b(m(i.subMenu,t),t,n,o);r.classList.add("tbw-context-submenu"),r.style.position="absolute",r.style.left="100%",r.style.top="0",e.style.position="relative",e.appendChild(r)}),e.addEventListener("mouseleave",()=>{const t=e.querySelector(".tbw-context-menu");t&&t.remove()})}c||!i.action||i.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),n(i)}),r.appendChild(e)}return r}const p="getContextMenuItems";let f=null,g=null,w=0;const x=/* @__PURE__ */new Set,v=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:e=>{const t=e.grid;t?.query?.("clipboard:copy")}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:e=>{const t=e.grid;t?.query?.("export:csv")}}];class y extends u{static manifest={queries:[{type:p,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:v}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),w++,x.add(this)}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,x.delete(this),this.uninstallGlobalHandlers()}syncSelectionOnContextMenu(e){if(e<0)return[];const t=this.grid?.query("getSelectedRowIndices"),n=t?.[0];return n?n.includes(e)?n:(this.grid?.query("selectRows",[e]),[e]):[e]}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size","--tbw-icon-submenu-arrow"];copyGridStyles(e){const t=this.gridElement;if(!t)return;const n=getComputedStyle(t),o=[],r=n.getPropertyValue("color-scheme").trim();r&&o.push(`color-scheme: ${r}`);for(const s of y.CSS_VARS_TO_COPY){const e=n.getPropertyValue(s).trim();e&&o.push(`${s}: ${e}`)}if(o.length>0){const t=e.getAttribute("style")||"";e.setAttribute("style",t+o.join("; ")+";")}}installGlobalHandlers(){if(!g&&"undefined"!=typeof document&&d&&(g=document.createElement("style"),g.id="tbw-context-menu-styles",g.textContent=d,document.head.appendChild(g)),!f){f=new AbortController;const e=f.signal,t=()=>{for(const e of x)e.isMenuOpen()&&e.hideMenu();document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())};document.addEventListener("click",t,{signal:e}),document.addEventListener("keydown",e=>{"Escape"===e.key&&t()},{signal:e}),document.addEventListener("scroll",t,{capture:!0,signal:e})}}uninstallGlobalHandlers(){w--,w>0||(f&&(f.abort(),f=null),g&&(g.remove(),g=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(p,e),n=[];for(const o of t)Array.isArray(o)&&n.push(...o);return n.sort((e,t)=>(e.order??100)-(t.order??100)),this.insertGroupSeparators(n)}insertGroupSeparators(e){if(e.length<=1)return e;const t=[];let n=-1;for(const o of e){if(o.separator){t.push(o);continue}const e=Math.floor((o.order??100)/10);n>=0&&e!==n&&t.push({id:`__sep-${n}-${e}`,label:"",separator:!0,action:()=>{}}),n=e,t.push(o)}return t}convertPluginItems(e){return e.map(e=>({id:e.id,name:e.label,icon:e.icon,shortcut:e.shortcut,disabled:e.disabled??!1,action:()=>e.action(),separator:e.separator,cssClass:e.cssClass}))}openMenuAt(e,t,n,o=!1){this.params=e,this.position={x:t,y:n};const r=this.collectPluginItems(e);let s=m(this.config.items??v,e);if(r.length>0){const e=this.convertPluginItems(r);s=s.length>0&&e.length>0?[...s,{id:"__plugin-sep",name:"",separator:!0},...e]:[...s,...e]}var i,a;(s=function(e){const t=[];for(const n of e)n.separator&&(0===t.length||t[t.length-1].separator)||t.push(n);return t.length>0&&t[t.length-1].separator&&t.pop(),t}(s),s.length)&&(document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove()),this.menuElement=null,this.menuElement=b(s,e,t=>{t.action&&t.action(e),this.hideMenu()},this.grid?.gridConfig?.icons?.submenuArrow),i=this.menuElement,a=()=>this.hideMenu(),i.addEventListener("keydown",e=>{const t=Array.from(i.querySelectorAll('[role="menuitem"]:not(.disabled)'));if(!t.length)return;const n=document.activeElement,o=t.indexOf(n);switch(e.key){case"ArrowDown":e.preventDefault(),t[o<t.length-1?o+1:0].focus();break;case"ArrowUp":e.preventDefault(),t[o>0?o-1:t.length-1].focus();break;case"Enter":case" ":e.preventDefault(),n&&t.includes(n)&&n.click();break;case"Escape":e.preventDefault(),a()}}),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),function(e,t,n){e.style.position="fixed",e.style.left=`${t}px`,e.style.top=`${n}px`,e.style.visibility="hidden",e.style.zIndex="10000";const o=e.getBoundingClientRect(),r=window.innerWidth,s=window.innerHeight;let i=t,a=n;t+o.width>r&&(i=t-o.width),n+o.height>s&&(a=n-o.height),i=Math.max(0,i),a=Math.max(0,a),e.style.left=`${i}px`,e.style.top=`${a}px`,e.style.visibility="visible"}(this.menuElement,t,n),this.isOpen=!0,o&&function(e){const t=e.querySelector('[role="menuitem"]:not(.disabled)');t?.focus()}(this.menuElement),this.emit("context-menu-open",{params:e,items:s}))}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root");t&&"true"!==t.getAttribute("data-context-menu-bound")&&(t.setAttribute("data-context-menu-bound","true"),t.addEventListener("contextmenu",e=>{const t=e;t.preventDefault();const n=t.target,o=n.closest("[data-row][data-col]"),r=n.closest('[part~="header-cell"]');let s;if(o){const e=parseInt(o.getAttribute("data-row")??"-1",10),n=parseInt(o.getAttribute("data-col")??"-1",10),r=this.visibleColumns[n],i=this.rows[e],a=this.syncSelectionOnContextMenu(e);s={row:i,rowIndex:e,column:r,columnIndex:n,field:r?.field??"",value:i?.[r?.field]??null,isHeader:!1,event:t,selectedRows:a}}else{if(!r)return;{const e=parseInt(r.getAttribute("data-col")??"-1",10),n=this.visibleColumns[e];s={row:null,rowIndex:-1,column:n,columnIndex:e,field:n?.field??"",value:null,isHeader:!0,event:t,selectedRows:[]}}}this.openMenuAt(s,t.clientX,t.clientY)}))}onKeyDown(e){const t="F10"===e.key&&e.shiftKey,n="ContextMenu"===e.key;if(!t&&!n)return;e.preventDefault();const o=this.grid;if(!o)return;const r=o._focusRow,s=o._focusCol,i=this.visibleColumns[s],a=this.rows[r],c=this.gridElement,l=c?.querySelector(`[data-row="${r}"][data-col="${s}"]`);let u=0,d=0;if(l){const e=l.getBoundingClientRect();u=e.left+e.width/2,d=e.bottom}const m=this.syncSelectionOnContextMenu(r),h={row:a,rowIndex:r,column:i,columnIndex:s,field:i?.field??"",value:a?.[i?.field]??null,isHeader:!1,event:e,selectedRows:m};return this.openMenuAt(h,u,d,!0),!0}showMenu(e,t,n){const o={row:n.row??null,rowIndex:n.rowIndex??-1,column:n.column??null,columnIndex:n.columnIndex??-1,field:n.field??"",value:n.value??null,isHeader:n.isHeader??!1,event:n.event??new MouseEvent("contextmenu"),selectedRows:n.selectedRows??[]};this.openMenuAt(o,e,t)}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen&&(this.isOpen=!1)}isMenuOpen(){return this.isOpen}}export{y as ContextMenuPlugin};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- const t={sortApplied:(t,e)=>`Sorted by ${t}, ${e}`,sortCleared:()=>"Sort cleared",filterApplied:t=>`Filter applied on ${t}`,filterCleared:t=>`Filter cleared from ${t}`,allFiltersCleared:()=>"All filters cleared",groupExpanded:(t,e)=>`Group ${t} expanded, ${e} rows`,groupCollapsed:t=>`Group ${t} collapsed`,selectionChanged:t=>`${t} rows selected`,columnSelected:t=>`Column ${t} selected`,columnSelectionChanged:t=>`${t} columns selected`,columnSelectionCleared:()=>"Column selection cleared",selectionAxisChanged:t=>"column"===t?"Row selection cleared, column selection active":"Column selection cleared, row selection active",editingStarted:t=>`Editing row ${t+1}`,editingCommitted:t=>`Row ${t+1} saved`,dataLoaded:t=>`${t} rows loaded`},e={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};function i(t,e){if(!t)return;const i="effectiveConfig"in t?t.effectiveConfig:void 0;if(!1===i?.a11y?.announcements)return;const n=t.querySelector?.(".tbw-sr-only");n&&(n.textContent="",requestAnimationFrame(()=>{n.textContent=e}))}function n(e,i,...n){const r=e&&"effectiveConfig"in e?e.effectiveConfig:void 0,s=r?.a11y?.messages?.[i];return s?s(...n):t[i](...n)}const r="editing";function s(t,e){return`[tbw-grid${t?`#${t}`:""}${e?`:${e}`:""}]`}function o(t,e,i,n){return`${s(i,n)} ${t}: ${e}\n\n → More info: ${function(t){return`https://toolboxjs.com/grid/errors#${t.toLowerCase()}`}(t)}`}const l="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(t=>t.split("").reverse().join(""));new RegExp(`__(proto|defineGetter|defineSetter)|${l.slice(3).join("|")}|this\\b`);const d=new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing".split("|")),a=/^on\w+$/i,c=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),u=/^\s*(javascript|vbscript|data|blob):/i;function h(t){if(!t||"string"!=typeof t)return"";if(-1===t.indexOf("<"))return t;const e=document.createElement("template");return e.innerHTML=t,function(t){const e=[],i=t.querySelectorAll("*");for(const n of i){const t=n.tagName.toLowerCase();if(d.has(t)){e.push(n);continue}if("svg"===t||"http://www.w3.org/2000/svg"===n.namespaceURI){if(Array.from(n.attributes).some(t=>a.test(t.name)||"href"===t.name||"xlink:href"===t.name)){e.push(n);continue}}const i=[];for(const e of n.attributes){const t=e.name.toLowerCase();a.test(t)?i.push(e.name):(c.has(t)&&u.test(e.value)||"style"===t&&/expression\s*\(|javascript:|behavior\s*:/i.test(e.value))&&i.push(e.name)}i.forEach(t=>n.removeAttribute(t))}e.forEach(t=>t.remove())}(e.content),e.innerHTML}const f=/* @__PURE__ */new WeakMap;document.createElement("template").innerHTML='<div class="cell" role="gridcell" part="cell"></div>';function g(t,e){if(!e.capped)return t;const i=e.spacerHeight-e.viewportHeight,n=e.rawContentHeight-e.viewportHeight;return i<=0||n<=0?t:t*i/n}function w(t,e){if(t._virtualization?.enabled){const{rowHeight:e,container:i,viewportEl:n,scrollMapping:r}=t._virtualization,s=i,o=n?.clientHeight??s?.clientHeight??0;if(s&&o>0){const i=t._focusRow*e,n=r?function(t,e){if(!e.capped)return t;const i=e.spacerHeight-e.viewportHeight,n=e.rawContentHeight-e.viewportHeight;if(i<=0||n<=0)return t;const r=t*n/i;return r<0?0:r>n?n:r}(s.scrollTop,r):s.scrollTop;if(i<n)s.scrollTop=r?g(i,r):i;else if(i+e>n+o){const t=i-o+e;s.scrollTop=r?g(t,r):t}}}const i=void 0!==t._activeEditRows&&-1!==t._activeEditRows||!!t._isGridEditMode;var n;i||t.refreshVirtualWindow(!1),(n=t._bodyEl)&&n.querySelectorAll(".cell-focus").forEach(t=>t.classList.remove("cell-focus")),Array.from(t._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(t=>{t.setAttribute("aria-selected","false")});const s=t._focusRow,o=t._virtualization.start??0,l=t._virtualization.end??t._rows.length;if(s>=o&&s<l){const n=t._bodyEl.querySelectorAll(".data-grid-row")[s-o];let l=n?.children[t._focusCol];if(l&&l.classList?.contains("cell")||(l=n?.querySelector(`.cell[data-col="${t._focusCol}"]`)??n?.querySelector(".cell[data-col]")),l){l.classList.add("cell-focus"),l.setAttribute("aria-selected","true");const s=t.querySelector(".tbw-scroll-area");if(s&&l&&(!i||e?.forceHorizontalScroll))if(e?.forceScrollLeft)s.scrollLeft=0;else if(e?.forceScrollRight)s.scrollLeft=s.scrollWidth-s.clientWidth;else{const e=t._getHorizontalScrollOffsets?.(n??void 0,l)??{left:0,right:0};if(!e.skipScroll){const t=l.getBoundingClientRect(),i=s.getBoundingClientRect(),n=t.left-i.left+s.scrollLeft,r=n+t.width,o=s.scrollLeft+e.left,d=s.scrollLeft+s.clientWidth-e.right;n<o?s.scrollLeft=n-e.left:r>d&&(s.scrollLeft=r-s.clientWidth+e.right)}}if(i&&l.classList.contains(r)){const t=l.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');if(t&&document.activeElement!==t)try{t.focus({preventScroll:!0})}catch{}}else if(i&&!l.contains(document.activeElement)){l.hasAttribute("tabindex")||l.setAttribute("tabindex","-1");try{l.focus({preventScroll:!0})}catch{}}else if(!i){const e=document.activeElement;e instanceof HTMLElement&&e!==t&&"function"==typeof t.contains&&t.contains(e)&&!e.classList.contains("cell")&&!e.closest(".cell")||e===t||t.focus({preventScroll:!0})}}}}document.createElement("template").innerHTML='<div class="data-grid-row" role="row" part="row"></div>';class m{static dependencies;static manifest;aliases;version="2.17.1";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#t;get defaultConfig(){return{}}constructor(t={}){this.userConfig=t}get resolvedConfig(){return this.#t?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(t){if(0===t.length)return;const e={...this.userConfig},i={};for(const n of Object.keys(e))i[n]=this;for(const n of t){const t=n.userConfig;for(const[r,s]of Object.entries(t)){if(void 0===s)continue;if(!(r in e)){e[r]=s,i[r]=n;continue}if(e[r]===s)continue;const t=i[r]?.constructor.name??this.constructor.name,l=n.constructor.name,d=o("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${r}" supplied by both ${t} and ${l}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(d)}}Object.assign(this.userConfig,e)}refreshUserConfigFrom(t){const e=this.userConfig;for(const i of Object.keys(e))delete e[i];Object.assign(e,t.userConfig)}attach(t){this.#t?.abort(),this.#t=new AbortController,this.grid=t,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#t?.abort(),this.#t=void 0}getPlugin(t){return this.grid?.getPlugin(t)}emit(t,e){this.grid?.dispatchEvent?.(new CustomEvent(t,{detail:e,bubbles:!0}))}emitCancelable(t,e){const i=new CustomEvent(t,{detail:e,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(i),i.defaultPrevented}on(t,e){this.grid?._pluginManager?.subscribe(this,t,e)}off(t){this.grid?._pluginManager?.unsubscribe(this,t)}emitPluginEvent(t,e){this.grid?._pluginManager?.emitPluginEvent(t,e)}broadcast(t,e){this.emitPluginEvent(t,e),this.emit(t,e)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#t?.signal??this.grid?.disconnectSignal}get gridIcons(){const t=this.grid?.gridConfig?.icons??{};return{...e,...t}}get isAnimationEnabled(){const t=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===t||"off"===t)return!1;if(!0===t||"on"===t)return!0;const e=this.gridElement;if(e){return"0"!==getComputedStyle(e).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const t=this.gridElement;if(t){const e=getComputedStyle(t).getPropertyValue("--tbw-animation-duration").trim(),i=parseInt(e,10);if(!isNaN(i))return i}return 200}setIcon(t,e,i){t.dataset.icon=e.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===e?t.dataset.expanded="":"expand"===e&&delete t.dataset.expanded;const n=this.#e(e,i);void 0!==n?"string"==typeof n?t.innerHTML=h(n):n instanceof HTMLElement&&(t.innerHTML="",t.appendChild(n.cloneNode(!0))):t.innerHTML=""}#e(t,e){return void 0!==e?e:this.grid?.gridConfig?.icons?.[t]}updateSortIndicator(t,e){t.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const i=document.createElement("span");i.setAttribute("part","sort-indicator"),i.className="sort-indicator",e?(t.setAttribute("aria-sort","asc"===e?"ascending":"descending"),t.setAttribute("data-sort",e),this.setIcon(i,"asc"===e?"sortAsc":"sortDesc")):(t.setAttribute("aria-sort","none"),t.removeAttribute("data-sort"),this.setIcon(i,"sortNone"));const n=t.querySelector(".tbw-filter-btn")??t.querySelector(".resize-handle");return n?t.insertBefore(i,n):t.appendChild(i),i}warn(t,e){void 0!==e?console.warn(o(t,e,this.gridElement.id,this.name)):console.warn(`${s(this.gridElement.id,this.name)} ${t}`)}throwDiagnostic(t,e){throw new Error(o(t,e,this.gridElement.id,this.name))}}function p(t){return e=>{const i=t.editorParams,n=document.createElement("input");n.type="date",e.value instanceof Date?n.valueAsDate=e.value:"string"==typeof e.value&&e.value&&(n.value=e.value.split("T")[0]),i?.min&&(n.min=i.min),i?.max&&(n.max=i.max),i?.placeholder&&(n.placeholder=i.placeholder);return n.addEventListener("change",()=>{var r;if(n.value)"string"==typeof e.value?e.commit(n.value):e.commit(n.valueAsDate);else if(t.nullable)e.commit(null);else{const t=i?.default;"string"==typeof e.value||"string"==typeof t?e.commit("string"==typeof t?t:`${(r=t??/* @__PURE__ */new Date).getFullYear()}-${String(r.getMonth()+1).padStart(2,"0")}-${String(r.getDate()).padStart(2,"0")}`):e.commit(t instanceof Date?t:/* @__PURE__ */new Date)}}),n.addEventListener("keydown",t=>{"Escape"===t.key&&e.cancel()}),n}}const v="__tbw_null__";function b(t){switch(t.type){case"number":return function(t){return e=>{const i=t.editorParams,n=document.createElement("input");n.type="number",n.value=null!=e.value?String(e.value):"",void 0!==i?.min&&(n.min=String(i.min)),void 0!==i?.max&&(n.max=String(i.max)),void 0!==i?.step&&(n.step=String(i.step)),i?.placeholder&&(n.placeholder=i.placeholder);const r=()=>{""===n.value?t.nullable?e.commit(null):e.commit(i?.min??0):e.commit(Number(n.value))};return n.addEventListener("blur",r),n.addEventListener("keydown",t=>{"Enter"===t.key&&r(),"Escape"===t.key&&e.cancel()}),n}}(t);case"boolean":return t=>{const e=document.createElement("input");return e.type="checkbox",e.checked=!!t.value,e.addEventListener("change",()=>t.commit(e.checked)),e};case"date":return p(t);case"select":return function(t){return e=>{const i=t.editorParams,n=document.createElement("select");if(t.multi&&(n.multiple=!0),t.nullable||i?.includeEmpty){const r=document.createElement("option");r.value=t.nullable?v:"",r.textContent=t.nullable?i?.emptyLabel??"(Blank)":i?.emptyLabel??"",null==e.value&&(r.selected=!0),n.appendChild(r)}const r=function(t){const e=t.options;return e?"function"==typeof e?e():e:[]}(t);r.forEach(i=>{const r=document.createElement("option");r.value=String(i.value),r.textContent=i.label,t.multi&&Array.isArray(e.value)&&e.value.includes(i.value)?r.selected=!0:t.multi||e.value!==i.value||(r.selected=!0),n.appendChild(r)});const s=()=>{if(t.multi){const t=Array.from(n.selectedOptions).map(t=>t.value);e.commit(t)}else t.nullable&&n.value===v?e.commit(null):e.commit(n.value)};return n.addEventListener("change",s),n.addEventListener("blur",s),n.addEventListener("keydown",t=>{"Escape"===t.key&&e.cancel()}),n}}(t);default:return function(t){return e=>{const i=t.editorParams,n=document.createElement("input");n.type="text",n.value=null!=e.value?String(e.value):"",void 0!==i?.maxLength&&(n.maxLength=i.maxLength),i?.pattern&&(n.pattern=i.pattern),i?.placeholder&&(n.placeholder=i.placeholder);const r=()=>{const i=n.value;""!==i?"string"==typeof e.value&&i===e.value.replace(/[\n\r]/g,"")||("number"==typeof e.value?e.commit(Number(i)):e.commit(i)):t.nullable?e.commit(null):e.commit("")};return n.addEventListener("blur",r),n.addEventListener("keydown",t=>{"Enter"===t.key&&r(),"Escape"===t.key&&e.cancel()}),n}}(t)}}function y(t,e,i){if(t instanceof HTMLInputElement){if("checkbox"===t.type)return t.checked;if("number"===t.type){if(""===t.value){if(e?.nullable)return null;const t=e?.editorParams;return t?.min??0}return Number(t.value)}if("date"===t.type)return t.value?"string"==typeof i?t.value:t.valueAsDate:e?.nullable?null:"string"==typeof i?i||/* @__PURE__ */(new Date).toISOString().slice(0,10):i??/* @__PURE__ */new Date;if("number"==typeof i){if(""===t.value){if(e?.nullable)return null;const t=e?.editorParams;return t?.min??0}return Number(t.value)}return""===t.value&&null==i?e?.nullable?null:"":"string"==typeof i&&t.value===i.replace(/[\n\r]/g,"")?i:t.value}return"number"===e?.type&&""!==t.value||"number"==typeof i&&""!==t.value?Number(t.value):null==i&&""===t.value?e?.nullable?null:"":t.value}class E{#i=/* @__PURE__ */new Map;#n;constructor(t){this.#n=t}setInvalid(t,e,i=""){let n=this.#i.get(t);n||(n=/* @__PURE__ */new Map,this.#i.set(t,n)),n.set(e,i),this.#n(t,e,!0)}clearInvalid(t,e){const i=this.#i.get(t);i&&(i.delete(e),0===i.size&&this.#i.delete(t)),this.#n(t,e,!1)}clearRowInvalid(t){const e=this.#i.get(t);if(e){const i=Array.from(e.keys());this.#i.delete(t),i.forEach(e=>this.#n(t,e,!1))}}clearAllInvalid(){const t=Array.from(this.#i.entries());this.#i.clear(),t.forEach(([t,e])=>{e.forEach((e,i)=>this.#n(t,i,!1))})}isCellInvalid(t,e){return this.#i.get(t)?.has(e)??!1}getInvalidMessage(t,e){return this.#i.get(t)?.get(e)}hasInvalidCells(t){const e=this.#i.get(t);return!!e&&e.size>0}getInvalidFields(t){return new Map(this.#i.get(t)??[])}}function R(t,e,i){const n=t.get(e);return!!n&&!C(n,i)}function C(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(typeof t!=typeof e)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!C(t[i],e[i]))return!1;return!0}if("object"==typeof t){const i=t,n=e,r=Object.keys(i),s=Object.keys(n);if(r.length!==s.length)return!1;for(const t of r)if(!C(i[t],n[t]))return!1;return!0}return!1}function I(t,e,i){t.set(e,structuredClone(i))}function k(t,e,i){const n=t.get(e);if(!n)return!1;const r=n,s=i;for(const o of Object.keys(r))s[o]=r[o];return!0}class _{baselines=/* @__PURE__ */new Map;baselinesWereCaptured=!1;newRowIds=/* @__PURE__ */new Set;changedRowIds=/* @__PURE__ */new Set;committedDirtyRowIds=/* @__PURE__ */new Set;clear(){this.changedRowIds.clear(),this.committedDirtyRowIds.clear(),this.baselines.clear(),this.newRowIds.clear(),this.baselinesWereCaptured=!1}capture(t,e){const i=this.baselines.size;!function(t,e,i){for(const n of e)try{const e=i(n);null==e||t.has(e)||t.set(e,structuredClone(n))}catch{}}(this.baselines,t,e),this.baselines.size>i&&(this.baselinesWereCaptured=!0)}drainCapturedFlag(){return this.baselinesWereCaptured?(this.baselinesWereCaptured=!1,this.baselines.size):null}isRowDirty(t,e){return R(this.baselines,t,e)}hasAnyDirty(t){if(this.newRowIds.size>0)return!0;for(const[e]of this.baselines){const i=t(e);if(i&&R(this.baselines,e,i))return!0}return!1}isCellDirty(t,e,i){return function(t,e,i,n){const r=t.get(e);return!!r&&!C(r[n],i[n])}(this.baselines,t,e,i)}getRowDirtyState(t,e){const i=this.newRowIds.has(t);return{isNew:i,isCommittedDirty:!i&&this.committedDirtyRowIds.has(t)&&R(this.baselines,t,e),hasBaseline:this.baselines.has(t)}}markPristine(t,e){I(this.baselines,t,e),this.newRowIds.delete(t),this.changedRowIds.delete(t),this.committedDirtyRowIds.delete(t)}markNew(t){this.newRowIds.add(t),this.committedDirtyRowIds.add(t)}markDirty(t){this.changedRowIds.add(t),this.committedDirtyRowIds.add(t)}markAllPristine(t){for(const[e]of this.baselines){const i=t(e);i&&I(this.baselines,e,i)}this.newRowIds.clear(),this.changedRowIds.clear(),this.committedDirtyRowIds.clear()}getOriginalRow(t){return function(t,e){const i=t.get(e);return i?structuredClone(i):void 0}(this.baselines,t)}hasBaseline(t){return this.baselines.has(t)}getDirtyRows(t){const e=[];for(const[i,n]of this.baselines){const r=t(i);r&&R(this.baselines,i,r)&&e.push({id:i,original:structuredClone(n),current:r})}for(const i of this.newRowIds){const n=t(i);n&&e.push({id:i,original:void 0,current:n})}return e}getDirtyRowIds(t){const e=[];for(const[i]of this.baselines){const n=t(i);n&&R(this.baselines,i,n)&&e.push(i)}for(const i of this.newRowIds)e.push(i);return e}revertRow(t,e){const i=k(this.baselines,t,e);return i&&(this.changedRowIds.delete(t),this.committedDirtyRowIds.delete(t)),i}revertAll(t){for(const[e]of this.baselines){const i=t(e);i&&k(this.baselines,e,i)}this.changedRowIds.clear(),this.committedDirtyRowIds.clear()}getChangedRows(t){const e=[];for(const i of this.changedRowIds){const n=t(i);n&&e.push(n)}return e}getChangedRowIds(){return Array.from(this.changedRowIds)}isRowChanged(t){return this.changedRowIds.has(t)}}const S='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function A(t){const e=t;return e?.closest?.(S)??null}function x(t){return"string"==typeof t&&("__proto__"!==t&&"constructor"!==t&&"prototype"!==t)}function M(t){}function L(t,e){return!1===t.onBeforeEditClose?.(e)}function G(t,e,i,n,r,s,l,d){if(!n.editable)return;if(s.classList.contains("editing"))return;const{grid:a,isGridMode:c,config:u,editingCells:h,editorValueCallbacks:f}=t;let g;try{g=a.getRowId?.(e)}catch{}const w=g?t=>a.updateRow(g,t,"cascade"):M,m=x(n.field)?e[n.field]:void 0;s.classList.add("editing"),h.add(`${i}:${r}`);const p=d??s.parentElement;p&&function(t){const e=(t.__editingCellCount??0)+1;t.__editingCellCount=e,t.setAttribute("data-has-editing","")}(p);let v=!1;const E=r=>{if(v||!c&&!t.isEditSessionActive())return;const s=g?a._getRowEntry(g):void 0,o=s?.row??e,l=s?.index??i;t.commitCellValue(l,n,r,o)},R=()=>{if(v=!0,x(n.field)){const t=g?a._getRowEntry(g):void 0;(t?.row??e)[n.field]=m}},C=document.createElement("div");C.className="tbw-editor-host",s.firstElementChild&&a.__frameworkAdapter?.releaseCell?.(s),s.innerHTML="",s.appendChild(C),C.addEventListener("keydown",e=>{if(!e.defaultPrevented){if("Enter"===e.key){const t=e.target;if(t&&"true"===t.getAttribute?.("aria-expanded")&&t.hasAttribute?.("aria-controls"))return}if("Enter"===e.key){if(c){const t=e.target,i=A(t);if(i&&i!==t)return;e.preventDefault();const r=C.querySelector("input,textarea,select");return void(r&&E(y(r,n,m)))}if(L(u,e))return;e.stopPropagation(),e.preventDefault(),v=!0,t.exitRowEdit(i,!1)}if("Escape"===e.key){if(c)return e.stopPropagation(),void e.preventDefault();if(L(u,e))return;e.stopPropagation(),e.preventDefault(),R(),t.exitRowEdit(i,!0)}}});const I=n,k=I.__editorTemplate,_=function(t,e){if(e.editor)return e.editor;if(e.__editorTemplate)return"template";if(!e.type)return;const i=t.effectiveConfig?.typeDefaults;if(i?.[e.type]?.editor)return i[e.type].editor;const n=t.__frameworkAdapter;if(n?.getTypeDefault){const i=n.getTypeDefault(e.type,t._hostElement);if(i?.editor)return i.editor}}(a,I)??b(n),G=m,D=`${i}:${n.field}`,T=[];f.set(D,t=>{for(const e of T)e(t)});const q=t=>{T.push(t)};if("template"===_&&k)!function(t,e,i,n,r,s,o,l,d){const a=i.__editorTemplate;if(!a)return;const c=a.cloneNode(!0),u=i.__compiledEditor;u?c.innerHTML=u({row:n,value:r,field:i.field,column:i,commit:s,cancel:o}):c.querySelectorAll("*").forEach(t=>{1===t.childNodes.length&&t.firstChild?.nodeType===Node.TEXT_NODE&&(t.textContent=t.textContent?.replace(/{{\s*value\s*}}/g,null==r?"":String(r)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(t,e)=>{if(!x(e))return"";const i=n[e];return null==i?"":String(i)})||"")});const h=c.querySelector("input,textarea,select");if(h){h instanceof HTMLInputElement&&"checkbox"===h.type?h.checked=!!r:h.value=String(r??"");let e=!1;h.addEventListener("blur",()=>{e||s(y(h,i,r))}),h.addEventListener("keydown",n=>{const l=n;if("Enter"===l.key){if(L(t.config,l))return;l.stopPropagation(),l.preventDefault(),e=!0,s(y(h,i,r)),t.exitRowEdit(d,!1)}if("Escape"===l.key){if(L(t.config,l))return;l.stopPropagation(),l.preventDefault(),o(),t.exitRowEdit(d,!0)}}),h instanceof HTMLInputElement&&"checkbox"===h.type&&h.addEventListener("change",()=>s(h.checked)),l||setTimeout(()=>h.focus({preventScroll:!0}),0)}e.appendChild(c)}(t,C,I,e,m,E,R,l,i),q(t=>{if(null!=t&&"object"==typeof t)return;const e=C.querySelector("input,textarea,select");e&&(e instanceof HTMLInputElement&&"checkbox"===e.type?e.checked=!!t:e.value=String(t??""))});else if("string"==typeof _){const t=document.createElement(_);t.value=G,t.addEventListener("change",()=>E(t.value)),q(e=>{t.value=e}),C.appendChild(t),l||queueMicrotask(()=>{const t=C.querySelector(S);t?.focus({preventScroll:!0})})}else if("function"==typeof _){const i=_({row:e,rowId:g??"",value:G,field:n.field,column:n,commit:E,cancel:R,updateRow:w,onValueChange:q,grid:t.grid});if("string"==typeof i)C.innerHTML=i,function(t,e,i,n){const r=t.querySelector("input,textarea,select");r&&(r.addEventListener("blur",()=>{i(y(r,e,n))}),r instanceof HTMLInputElement&&"checkbox"===r.type?r.addEventListener("change",()=>i(r.checked)):r instanceof HTMLSelectElement&&r.addEventListener("change",()=>i(y(r,e,n))))}(C,n,E,m),q(t=>{const e=C.querySelector("input,textarea,select");e&&(e instanceof HTMLInputElement&&"checkbox"===e.type?e.checked=!!t:e.value=String(t??""))});else if(i instanceof Node){C.appendChild(i);i instanceof HTMLInputElement||i instanceof HTMLSelectElement||i instanceof HTMLTextAreaElement?q(t=>{i instanceof HTMLInputElement&&"checkbox"===i.type?i.checked=!!t:i.value=String(t??"")}):s.setAttribute("data-editor-managed","")}else!i&&C.hasChildNodes()&&s.setAttribute("data-editor-managed","");l||queueMicrotask(()=>{const t=C.querySelector(S);t?.focus({preventScroll:!0})})}else if(_&&"object"==typeof _){const i=document.createElement("div");i.setAttribute("data-external-editor",""),i.setAttribute("data-field",n.field),C.appendChild(i),s.setAttribute("data-editor-managed","");const r={row:e,rowId:g??"",value:G,field:n.field,column:n,commit:E,cancel:R,updateRow:w,onValueChange:q,grid:t.grid};if(_.mount)try{_.mount({placeholder:i,context:r,spec:_})}catch(N){$="TBW080",F=`External editor mount error for column '${n.field}': ${N}`,P=t.grid.id,console.warn(o($,F,P,H))}else a.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:i,spec:_,context:r}}))}var $,F,P,H}class D extends m{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:t=>!0===t||"function"==typeof t},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'},{property:"nullable",level:"column",description:'the "nullable" column property (allows null values)'}],events:[{type:"cell-edit-committed",description:"Emitted when a cell edit is committed (for plugin-to-plugin coordination)"}],queries:[{type:"isEditing",description:"Returns whether any cell is currently being edited"},{type:"getEditableFields",description:"Returns the field names of columns that are unconditionally editable (editable === true), for consumers like clipboard paste"}]};name="editing";styles="@layer tbw-plugins{tbw-grid{--tbw-editing-bg: var(--tbw-color-selection);--tbw-editing-row-bg: var(--tbw-editing-bg);--tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));--tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);--tbw-font-size-editor: inherit;--tbw-editing-row-outline-color: var(--tbw-color-accent);--tbw-editing-row-outline-width: 1px;--tbw-invalid-bg: light-dark(#fef2f2, #450a0a);--tbw-invalid-border-color: light-dark(#ef4444, #f87171)}tbw-grid:not(.tbw-grid-mode) .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:max(var(--tbw-row-height),calc(1lh + 2 * var(--tbw-cell-padding-v, .25em) + var(--tbw-border-width, 1px)));align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;align-self:stretch;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}tbw-grid .data-grid-row>.cell[data-invalid=true]{background:var(--tbw-invalid-bg);outline:1px solid var(--tbw-invalid-border-color);outline-offset:-1px}}";get defaultConfig(){return{mode:"row",editOn:"click"}}get#r(){return"grid"===this.config.mode}#s(t,e){const i=this.#o.effectiveConfig?.rowEditable;if(i&&!i(e))return!1;const{editable:n}=t;return"function"==typeof n?n(e):!0===n}#l(t){return!0===t.editable||"function"==typeof t.editable}#d=-1;#a;#c;#u=-1;#h=/* @__PURE__ */new Map;#f=/* @__PURE__ */new Set;#g=/* @__PURE__ */new WeakSet;#w=/* @__PURE__ */new Map;#m=!1;#p=-1;#v;#b=!1;#y=!1;#E=!1;#R=null;#C=new _;#I;get#o(){return this.grid}attach(t){super.attach(t);const e=this.disconnectSignal,i=this.#o;if(this.#v=new E((t,e,i)=>{this.#k(t,e,i)}),this.#I={grid:i,isGridMode:this.#r,config:this.config,editingCells:this.#f,editorValueCallbacks:this.#w,isEditSessionActive:()=>-1!==this.#d,commitCellValue:(t,e,i,n)=>this.#_(t,e,i,n),exitRowEdit:(t,e)=>this.#S(t,e)},this.#A(),Object.defineProperty(t,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(t,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),Object.defineProperty(t,"_changedRowIdSet",{get:()=>this.#C.changedRowIds,configurable:!0}),t.resetChangedRows=t=>this.resetChangedRows(t),document.addEventListener("keydown",t=>{if(!this.#r&&"Escape"===t.key&&-1!==this.#d){if(L(this.config,t))return;this.#S(this.#d,!0)}},{capture:!0,signal:e}),document.addEventListener("mousedown",t=>{if(this.#r)return;if(-1===this.#d)return;const e=i.findRenderedRowElement?.(this.#d);if(!e)return;if((t.composedPath&&t.composedPath()||[]).includes(e))return;const n=t.target;if(!n||this.gridElement.contains(n)||!this.grid.containsFocus?.(n)){if(n&&!this.gridElement.contains(n)){const t=i.findRenderedRowElement?.(this.#d);if(t&&function(t,e){if(!t)return!1;const i=e.querySelectorAll('[aria-expanded="true"][aria-controls]');for(let n=0;n<i.length;n++){const r=i[n].getAttribute("aria-controls");if(!r)continue;const s=e.ownerDocument?.getElementById(r);if(s&&s.contains(t))return!0}return!1}(n,t))return}L(this.config,t)||queueMicrotask(()=>{-1!==this.#d&&this.#S(this.#d,!1)})}},{signal:e}),this.config.focusTrap&&this.gridElement.addEventListener("focusout",t=>{if(this.#r)return;if(-1===this.#d)return;const e=t.relatedTarget;e&&this.grid.containsFocus?.(e)||e&&this.gridElement.contains(e)||queueMicrotask(()=>{-1!==this.#d&&this.#x()})},{signal:e}),this.gridElement.addEventListener("cell-change",t=>{const e=t.detail;if("user"===e.source)return;const i=`${e.rowIndex}:${e.field}`,n=this.#w.get(i);n&&n(e.newValue)},{signal:e}),this.config.dirtyTracking){const t=t=>{const e=t.detail,i=e?.action;if(!i)return;const n=this.rows[i.rowIndex];if(!n)return;const r=this.#M(n);if(!r)return;const s=this.#C.isRowDirty(r,n);this.#L(r,n,s?"modified":"pristine")};this.gridElement.addEventListener("undo",t,{signal:e}),this.gridElement.addEventListener("redo",t,{signal:e}),this.on("row-inserted",t=>{const e=this.#M(t.row);null!=e&&this.markAsNew(String(e))})}this.#r&&(i._isGridEditMode=!0,this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",t=>{const e=t.target;if(e!==this.gridElement&&e.matches(S)){if(this.#y)return e.blur(),void this.gridElement.focus();const t=i._focusRow,n=i._focusCol,r=this.#R;if(!r||r.rowIndex!==t||r.colIndex!==n){const e=i._visibleColumns?.[n],r=i._rows?.[t];if(e?.field&&r){const i=e.field;this.#R={rowIndex:t,colIndex:n,field:i,value:r[i]}}}this.#b=!0}},{signal:e}),this.gridElement.addEventListener("focusout",t=>{const e=t.target,i=t.relatedTarget;if(e&&i){if(e.contains(i))return;const t=A(i);if(t&&t!==this.gridElement&&this.gridElement.contains(t))return}i&&(this.gridElement.contains(i)||this.grid.containsFocus?.(i))&&i.matches(S)||(this.#b=!1,this.#R=null)},{signal:e}),this.gridElement.addEventListener("keydown",t=>{if("Escape"===t.key&&this.#b){if(L(this.config,t))return void queueMicrotask(()=>{this.#b&&this.#G()});this.#G(),t.preventDefault(),t.stopPropagation()}},{capture:!0,signal:e}),this.gridElement.addEventListener("mousedown",t=>{t.target.matches(S)&&(this.#y=!1)},{signal:e}))}detach(){this.#o._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#d=-1,this.#a=void 0,this.#c=void 0,this.#u=-1,this.#h.clear(),this.#C.clear(),this.#f.clear(),this.#w.clear(),this.#b=!1,this.#y=!1,this.#R=null,this.#E=!1,this.#g=/* @__PURE__ */new WeakSet,super.detach()}handleQuery(t){if("isEditing"===t.type)return this.#r||-1!==this.#d;if("getEditableFields"===t.type){const e=t.context;return(e?.columns??this.#o.effectiveConfig?.columns??[]).filter(t=>!0===t.editable).map(t=>t.field)}}onCellClick(t){if(this.#r)return!1;const e=this.#o,i=this.config.editOn??e.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;if("click"!==i&&"dblclick"!==i)return!1;const n="dblclick"===t.originalEvent.type;if("click"===i&&n)return!1;if("dblclick"===i&&!n)return!1;const{rowIndex:r}=t,s=e._columns?.some(t=>this.#l(t));return!!s&&(!!this.#D(e._rows[r])&&(t.originalEvent.stopPropagation(),this.beginBulkEdit(r),!0))}onKeyDown(t){const e=this.#o;if("Escape"===t.key){if(this.#r&&this.#b)return this.#G(),this.requestAfterRender(),!0;if(-1!==this.#d&&!this.#r)return L(this.config,t)||this.#S(this.#d,!0),!0}const i=A(t.target),n=!!i&&i!==this.gridElement;if(this.#r&&!this.#b&&!n&&("ArrowUp"===t.key||"ArrowDown"===t.key||"ArrowLeft"===t.key||"ArrowRight"===t.key))return!1;if(this.#r&&(this.#b||n)&&("ArrowUp"===t.key||"ArrowDown"===t.key))return!0;if(("ArrowUp"===t.key||"ArrowDown"===t.key)&&-1!==this.#d&&!this.#r)return!0;if("Tab"===t.key&&(-1!==this.#d||this.#r)){if(t.preventDefault(),this.#E)return this.#S(this.#d,!1),!0;const e=!t.shiftKey;return this.#T(e),!0}if(" "===t.key||"Spacebar"===t.key){if(-1!==this.#d)return!1;const i=e._focusRow,n=e._focusCol;if(i>=0&&n>=0){const r=e._visibleColumns[n],s=e._rows[i];if(r&&s&&this.#s(r,s)&&"boolean"===r.type){const e=r.field;if(x(e)){const n=!s[e];return this.#_(i,r,n,s),t.preventDefault(),this.requestRender(),!0}}}return!1}if(!("Enter"!==t.key||t.shiftKey||t.ctrlKey||t.altKey||t.metaKey)){if(this.#r&&!this.#b)return this.#x(),!0;if(this.#r&&this.#b){const e=A(t.target);if(e&&e!==t.target)return!0;this.#R=null;const i=document.activeElement;return i&&this.gridElement.contains(i)&&(i.blur(),this.gridElement.focus()),this.#b=!1,this.#y=!0,this.requestAfterRender(),!0}if(-1!==this.#d){const e=t.target;return(!e||"true"!==e.getAttribute?.("aria-expanded")||!e.hasAttribute?.("aria-controls"))&&!!L(this.config,t)}const i=this.config.editOn??e.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;const n=e._focusRow,r=e._focusCol;if(n>=0){const i=e._columns?.some(t=>this.#l(t)),s=e._rows[n];if(i&&this.#D(s)){const i=e._visibleColumns[r],s=e._rows[n],o=i?.field??"",l=o&&s?s[o]:void 0,d=this.gridElement.querySelector(`[data-row="${n}"][data-col="${r}"]`),a=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:n,colIndex:r,field:o,value:l,row:s,cellEl:d,trigger:"keyboard",originalEvent:t}});return this.gridElement.dispatchEvent(a),a.defaultPrevented?(t.preventDefault(),!0):(this.beginBulkEdit(n),!0)}}return!1}if("F2"===t.key){if(-1!==this.#d||this.#r)return!1;if(!1===(this.config.editOn??e.effectiveConfig?.editOn))return!1;const i=e._focusRow,n=e._focusCol;if(i>=0&&n>=0){const r=e._visibleColumns[n],s=e._rows[i];if(r&&s&&this.#s(r,s)&&r.field)return t.preventDefault(),this.beginCellEdit(i,r.field),!0}return!1}return!1}processColumns(t){const e=this.#o,i=e.effectiveConfig?.typeDefaults,n=e.__frameworkAdapter,r=!!i||!!n?.getTypeDefault;return t.map(t=>{const s=t.__element;if(s&&!this.#g.has(s)){this.#g.add(s),null==t.editable&&s.hasAttribute("editable")&&(t.editable="false"!==s.getAttribute("editable"));const e=t;if(!e.__editorTemplate){const t=s.querySelector("tbw-grid-column-editor");t&&(e.__editorTemplate=t)}}if(!t.type||!r)return t;let o;if(i?.[t.type]?.editorParams&&(o=i[t.type].editorParams),!o&&n?.getTypeDefault){const i=n.getTypeDefault(t.type,e._hostElement);i?.editorParams&&(o=i.editorParams)}return o?{...t,editorParams:{...o,...t.editorParams}}:t})}processRows(t){const e=this.#o;if(this.config.dirtyTracking&&e.getRowId&&this.#C.capture(t,t=>{try{return e.getRowId?.(t)}catch{return}}),-1===this.#d||this.#r)return t;const i=this.#a,n=this.#c;if(!i||!n)return t;const r=[...t];let s=-1;for(let o=0;o<r.length;o++)if(this.#M(r[o])===i){s=o;break}return-1===s?(setTimeout(()=>this.cancelActiveRowEdit(),0),r):(r[s]=n,this.#d!==s&&this.#q(this.#d,s),r)}afterRender(){const t=this.#o;if(-1!==this.#d&&this.#c&&!this.#r&&t._rows[this.#d]!==this.#c){const e=t._rows.indexOf(this.#c);if(-1===e)return void setTimeout(()=>this.cancelActiveRowEdit(),0);this.#q(this.#d,e)}if(this.#m&&(this.#m=!1,this.#$(t)),-1!==this.#p){const e=this.#p;this.#p=-1,t.animateRow?.(e,"change")}const e=this.#C.drainCapturedFlag();if(null!=e&&this.emit("baselines-captured",{count:e}),!this.#r&&0!==this.#f.size)for(const i of this.#f){const[e,n]=i.split(":"),r=parseInt(e,10),s=parseInt(n,10),o=this.#F(r,s);if(!o||o.classList.contains("editing"))continue;const l=t._rows[r],d=t._visibleColumns[s];l&&d&&this.#P(l,r,d,s,o,!0)}}afterCellRender(t){const{row:e,rowIndex:i,column:n,colIndex:r,cellElement:s}=t,o=this.#s(n,e);if(o)s.removeAttribute("aria-readonly");else if(s.setAttribute("aria-readonly","true"),this.#r&&s.classList.contains("editing")){s.classList.remove("editing");const t=e[n.field];s.textContent=null==t?"":String(t)}this.#r&&o&&(s.classList.contains("editing")||this.#P(e,i,n,r,s,!0,t.rowElement))}afterRowRender(t){if(!this.config.dirtyTracking)return;const e=this.#o,i=e.getRowId?.(t.row);if(!i)return;const{isNew:n,isCommittedDirty:r,hasBaseline:s}=this.#C.getRowDirtyState(i,t.row),o=t.rowElement;if(o.classList.toggle("tbw-row-dirty",r),o.classList.toggle("tbw-row-new",n),s){const e=o.querySelectorAll(".cell[data-field]");for(let n=0;n<e.length;n++){const r=e[n],s=r.getAttribute("data-field");s&&r.classList.toggle("tbw-cell-dirty",this.#C.isCellDirty(i,t.row,s))}}else{const t=o.querySelectorAll(".tbw-cell-dirty");for(let e=0;e<t.length;e++)t[e].classList.remove("tbw-cell-dirty")}}onScrollRender(){this.afterRender()}get changedRows(){return this.#C.getChangedRows(t=>this.grid.getRow(t))}get changedRowIds(){return this.#C.getChangedRowIds()}get activeEditRow(){return this.#d}get activeEditCol(){return this.#u}isRowEditing(t){return this.#d===t}isCellEditing(t,e){return this.#f.has(`${t}:${e}`)}isRowChanged(t){const e=this.#o,i=e._rows[t];if(!i)return!1;try{const t=e.getRowId?.(i);return!!t&&this.#C.isRowChanged(t)}catch{return!1}}isRowChangedById(t){return this.#C.isRowChanged(t)}isDirty(t){if(!this.config.dirtyTracking)return!1;if(this.#C.newRowIds.has(t))return!0;const e=this.grid.getRow(t);return!!e&&this.#C.isRowDirty(t,e)}isPristine(t){return!this.isDirty(t)}get dirty(){if(!this.config.dirtyTracking)return!1;const t=this.#o;return this.#C.hasAnyDirty(e=>t._getRowEntry(e)?.row)}get pristine(){return!this.dirty}markAsPristine(t){if(!this.config.dirtyTracking)return;const e=this.grid.getRow(t);e&&(this.#C.markPristine(t,e),this.emit("dirty-change",{rowId:t,row:e,original:e,type:"pristine"}))}markAsNew(t){if(!this.config.dirtyTracking)return;this.#C.markNew(t);const e=this.grid.getRow(t);this.emit("dirty-change",{rowId:t,row:e,original:void 0,type:"new"})}markAsDirty(t){if(!this.config.dirtyTracking)return;const e=this.grid.getRow(t);e&&(this.#C.markDirty(t),this.#L(t,e,"modified"))}markAllPristine(){if(!this.config.dirtyTracking)return;const t=this.#o;this.#C.markAllPristine(e=>t._getRowEntry(e)?.row)}getOriginalRow(t){if(this.config.dirtyTracking)return this.#C.getOriginalRow(t)}hasBaseline(t){return!!this.config.dirtyTracking&&this.#C.hasBaseline(t)}getDirtyRows(){if(!this.config.dirtyTracking)return[];const t=this.#o;return this.#C.getDirtyRows(e=>t._getRowEntry(e)?.row)}get dirtyRowIds(){if(!this.config.dirtyTracking)return[];const t=this.#o;return this.#C.getDirtyRowIds(e=>t._getRowEntry(e)?.row)}revertRow(t){if(!this.config.dirtyTracking)return;const e=this.grid.getRow(t);e&&this.#C.revertRow(t,e)&&(this.#L(t,e,"reverted"),this.requestRender())}revertAll(){if(!this.config.dirtyTracking)return;const t=this.#o;this.#C.revertAll(e=>t._getRowEntry(e)?.row),this.requestRender()}setInvalid(t,e,i=""){this.#v.setInvalid(t,e,i)}clearInvalid(t,e){this.#v.clearInvalid(t,e)}clearRowInvalid(t){this.#v.clearRowInvalid(t)}clearAllInvalid(){this.#v.clearAllInvalid()}isCellInvalid(t,e){return this.#v.isCellInvalid(t,e)}getInvalidMessage(t,e){return this.#v.getInvalidMessage(t,e)}hasInvalidCells(t){return this.#v.hasInvalidCells(t)}getInvalidFields(t){return this.#v.getInvalidFields(t)}resetChangedRows(t){const e=this.changedRows,i=this.changedRowIds;this.#C.changedRowIds.clear(),this.#C.committedDirtyRowIds.clear(),this.#A(),t||this.emit("changed-rows-reset",{rows:e,ids:i});const n=this.#o;n._rowPool?.forEach(t=>t.classList.remove("changed"))}beginCellEdit(t,e){const i=this.#o,n=i._visibleColumns.findIndex(t=>t.field===e);if(-1===n)return;const r=i._visibleColumns[n],s=i._rows[t];if(!r||!s||!this.#s(r,s))return;const o=this.#F(t,n);o&&(this.#E=!0,this.#H(t,n,o))}beginBulkEdit(t){const e=this.#o;if(!1===(this.config.editOn??e.effectiveConfig?.editOn))return;const i=e._columns?.some(t=>this.#l(t));if(!i)return;const n=e.findRenderedRowElement?.(t);if(!n)return;const r=e._rows[t];this.#D(r)&&(this.#E=!1,this.#N(t,r),Array.from(n.children).forEach((i,n)=>{const s=e._visibleColumns[n];if(s&&this.#s(s,r)){const e=i;e.classList.contains("editing")||this.#P(r,t,s,n,e,!0)}}),setTimeout(()=>{let t=n.querySelector(`.cell[data-col="${e._focusCol}"]`);if(t?.classList.contains("editing")||(t=n.querySelector(".cell.editing")),t?.classList.contains("editing")){const e=t.querySelector(S);try{e?.focus({preventScroll:!0})}catch{}}},0))}commitActiveRowEdit(){-1!==this.#d&&this.#S(this.#d,!1)}cancelActiveRowEdit(){-1!==this.#d&&this.#S(this.#d,!0)}#M(t){if(t)try{return this.#o.getRowId?.(t)}catch{return}}#F(t,e){const i=this.#o.findRenderedRowElement?.(t);return i?.querySelector(`.cell[data-col="${e}"]`)??null}#D(t){if(!t)return!0;const e=this.#o.effectiveConfig?.rowEditable;return!e||!1!==e(t)}#L(t,e,i){this.emit("dirty-change",{rowId:t,row:e,original:this.#C.getOriginalRow(t),type:i})}#G(){this.#O();const t=document.activeElement;t&&this.gridElement.contains(t)&&(t.blur(),this.gridElement.focus()),this.#b=!1,this.#y=!0}#V(t,e,i){i&&(Object.keys(i).forEach(t=>{e[t]=i[t]}),t&&(this.#C.changedRowIds.delete(t),this.#C.committedDirtyRowIds.delete(t),this.clearRowInvalid(t)))}#k(t,e,i){const n=this.#o,r=n._visibleColumns?.findIndex(t=>t.field===e);if(-1===r||void 0===r)return;const s=n._rows,o=s?.findIndex(e=>this.#M(e)===t);if(-1===o||void 0===o)return;const l=this.#F(o,r);if(l)if(i){l.setAttribute("data-invalid","true");const i=this.#v.getInvalidMessage(t,e);i&&l.setAttribute("title",i)}else l.removeAttribute("data-invalid"),l.removeAttribute("title")}#q(t,e){this.#d=e;const i=/* @__PURE__ */new Set,n=`${t}:`;for(const o of this.#f)o.startsWith(n)?i.add(`${e}:${o.substring(n.length)}`):i.add(o);this.#f.clear();for(const o of i)this.#f.add(o);const r=this.#h.get(t);void 0!==r&&(this.#h.delete(t),this.#h.set(e,r));const s=[];for(const[o,l]of this.#w)o.startsWith(n)&&(s.push([`${e}:${o.substring(n.length)}`,l]),this.#w.delete(o));for(const[o,l]of s)this.#w.set(o,l);this.#A()}#H(t,e,i){const n=this.#o,r=n._rows[t],s=n._visibleColumns[e];r&&s&&this.#s(s,r)&&(i.classList.contains("editing")||(this.#d!==t&&this.#N(t,r),this.#u=e,this.#P(r,t,s,e,i,!1)))}#O(){const t=this.#R;if(!t)return;const e=this.#o,i=e._rows?.[t.rowIndex];i&&(i[t.field]=t.value);const n=`${t.rowIndex}:${t.field}`,r=this.#w.get(n);if(r&&r(t.value),this.emit("cell-cancel",{rowIndex:t.rowIndex,colIndex:t.colIndex,field:t.field,previousValue:t.value}),i){const t=this.#M(i);t&&(this.config.dirtyTracking?this.#C.isRowDirty(t,i)||(this.#C.changedRowIds.delete(t),this.#L(t,i,"reverted")):this.#C.changedRowIds.delete(t))}this.requestRender(),this.#R=null}#x(){const t=this.#o,e=t._focusRow,i=t._focusCol;if(e<0||i<0)return;const n=this.#F(e,i);if(n?.classList.contains("editing")){const t=n.querySelector(S);t&&(this.#y=!1,t.focus(),this.#b=!0,t instanceof HTMLInputElement&&("text"===t.type||"number"===t.type)&&t.select())}}#T(t){const e=this.#o,i=e._rows,n=this.#r?e._focusRow:this.#d,r=i[n],s=e._visibleColumns.map((t,e)=>r&&this.#s(t,r)?e:-1).filter(t=>t>=0);if(0===s.length)return;const o=s.indexOf(e._focusCol)+(t?1:-1);if(o>=0&&o<s.length){e._focusCol=s[o];const t=this.#F(n,s[o]);if(t?.classList.contains("editing")){const e=t.querySelector(S);e?.focus({preventScroll:!0})}return void w(e,{forceHorizontalScroll:!0})}const l=n+(t?1:-1);if(l>=0&&l<i.length){const r=i[l],s=e._visibleColumns.map((t,e)=>r&&this.#s(t,r)?e:-1).filter(t=>t>=0);if(0===s.length)return;this.#r?(e._focusRow=l,e._focusCol=t?s[0]:s[s.length-1],w(e,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const t=this.#F(l,e._focusCol);if(t?.classList.contains("editing")){const e=t.querySelector(S);e?.focus({preventScroll:!0})}},0)):(this.#S(n,!1),e._focusRow=l,e._focusCol=t?s[0]:s[s.length-1],this.beginBulkEdit(l),w(e,{forceHorizontalScroll:!0}))}}#A(){const t=this.#o;t._activeEditRows=this.#d,t._rowEditSnapshots=this.#h}#N(t,e){this.#d!==t&&(-1!==this.#d&&this.#S(this.#d,!1),this.#h.set(t,{...e}),this.#d=t,this.#c=e,this.#a=this.#M(e),this.#A(),this.#r||(this.broadcast("edit-open",{rowIndex:t,rowId:this.#a??"",row:e}),i(this.gridElement,n(this.gridElement,"editingStarted",t))))}#S(t,e){if(this.#d!==t)return;const r=this.#o,s=this.#h.get(t),o=r.findRenderedRowElement?.(t);let l=this.#a;const d=l?r._getRowEntry(l):void 0,a=d?.row??this.#c??r._rows[t];if(!l&&a&&(l=this.#M(a)),!e&&o&&a){o.querySelectorAll(".cell.editing").forEach(e=>{const i=Number(e.getAttribute("data-col"));if(isNaN(i))return;const n=r._visibleColumns[i];if(!n)return;if(e.hasAttribute("data-editor-managed"))return;const s=e.querySelector("input,textarea,select");if(s){const e=n.field,i=a[e],r=y(s,n,i);i!==r&&this.#_(t,n,r,a)}})}if(e||this.#r||!a||this.emit("before-edit-close",{rowIndex:t,rowId:l??"",row:a}),e&&a)this.#V(l,a,s);else if(!e&&a){const e=function(t,e){if(!t)return!1;const i=t,n=e,r=/* @__PURE__ */new Set([...Object.keys(i),...Object.keys(n)]);for(const s of r)if(i[s]!==n[s])return!0;return!1}(s,a),i=l?this.#C.changedRowIds.has(l):e,n=this.emitCancelable("row-commit",{rowIndex:t,rowId:l??"",row:a,oldValue:s,newValue:a,changed:i,changedRows:this.changedRows,changedRowIds:this.changedRowIds});n&&s?this.#V(l,a,s):n||(l&&this.config.dirtyTracking&&(this.#C.isRowDirty(l,a)?this.#C.committedDirtyRowIds.add(l):this.#C.committedDirtyRowIds.delete(l)),e&&this.isAnimationEnabled&&(this.#p=t))}this.#h.delete(t),this.#d=-1,this.#a=void 0,this.#c=void 0,this.#u=-1,this.#E=!1,this.#A();for(const i of this.#f)i.startsWith(`${t}:`)&&this.#f.delete(i);for(const i of this.#w.keys())i.startsWith(`${t}:`)&&this.#w.delete(i);if(this.#m=!0,o){const t=r.__frameworkAdapter,e=o.querySelectorAll(".cell.editing");t?.releaseCell&&e.forEach(e=>{t.releaseCell(e)}),e.forEach(t=>{t.classList.remove("editing"),function(t){t.__editingCellCount=0,t.removeAttribute("data-has-editing")}(t.parentElement)}),r.refreshVirtualWindow(!0)}else this.#$(r),this.#m=!1;!this.#r&&a&&(this.broadcast("edit-close",{rowIndex:t,rowId:l??"",row:a,reverted:e}),e||i(this.gridElement,n(this.gridElement,"editingCommitted",t)))}#_(t,e,i,n){const r=e.field;if(!x(r))return;const s=n[r];if(s===i)return;const o=this.#o,l=this.#M(n),d=!l||!this.#C.changedRowIds.has(l),a=l?t=>this.grid.updateRow(l,t,"cascade"):M;let c=!1;const u=l?t=>{c=!0,this.setInvalid(l,r,t??"")}:()=>{};if(this.emitCancelable("cell-commit",{row:n,rowId:l??"",field:r,oldValue:s,value:i,rowIndex:t,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:d,updateRow:a,setInvalid:u}))return;if(l&&!c&&this.isCellInvalid(l,r)&&this.clearInvalid(l,r),n[r]=i,function(t,e){t&&(e?f.get(t)?.delete(e):f.delete(t))}(n,r),l&&this.#C.changedRowIds.add(l),this.#A(),this.config.dirtyTracking&&l){const t=this.#C.isRowDirty(l,n);this.#L(l,n,t?"modified":"pristine")}this.emitPluginEvent("cell-edit-committed",{rowIndex:t,field:r,oldValue:s,newValue:i});const h=o.findRenderedRowElement?.(t);h&&h.classList.add("changed")}#P(t,e,i,n,r,s,o){G(this.#I,t,e,i,n,r,s,o)}#$(t){queueMicrotask(()=>{try{const e=t._focusRow,i=t._focusCol,n=t.findRenderedRowElement?.(e);if(n){Array.from(t._bodyEl.querySelectorAll(".cell-focus")).forEach(t=>t.classList.remove("cell-focus"));const r=n.querySelector(`.cell[data-row="${e}"][data-col="${i}"]`);r&&(r.classList.add("cell-focus"),r.setAttribute("aria-selected","true"),r.hasAttribute("tabindex")||r.setAttribute("tabindex","-1"),r.focus({preventScroll:!0}))}}catch{}})}}export{D as EditingPlugin,b as defaultEditorFor};
1
+ const t={sortApplied:(t,e)=>`Sorted by ${t}, ${e}`,sortCleared:()=>"Sort cleared",filterApplied:t=>`Filter applied on ${t}`,filterCleared:t=>`Filter cleared from ${t}`,allFiltersCleared:()=>"All filters cleared",groupExpanded:(t,e)=>`Group ${t} expanded, ${e} rows`,groupCollapsed:t=>`Group ${t} collapsed`,selectionChanged:t=>`${t} rows selected`,columnSelected:t=>`Column ${t} selected`,columnSelectionChanged:t=>`${t} columns selected`,columnSelectionCleared:()=>"Column selection cleared",selectionAxisChanged:t=>"column"===t?"Row selection cleared, column selection active":"Column selection cleared, row selection active",editingStarted:t=>`Editing row ${t+1}`,editingCommitted:t=>`Row ${t+1} saved`,dataLoaded:t=>`${t} rows loaded`},e={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};function i(t,e){if(!t)return;const i="effectiveConfig"in t?t.effectiveConfig:void 0;if(!1===i?.a11y?.announcements)return;const n=t.querySelector?.(".tbw-sr-only");n&&(n.textContent="",requestAnimationFrame(()=>{n.textContent=e}))}function n(e,i,...n){const r=e&&"effectiveConfig"in e?e.effectiveConfig:void 0,s=r?.a11y?.messages?.[i];return s?s(...n):t[i](...n)}const r="editing";function s(t,e){return`[tbw-grid${t?`#${t}`:""}${e?`:${e}`:""}]`}function o(t,e,i,n){return`${s(i,n)} ${t}: ${e}\n\n → More info: ${function(t){return`https://toolboxjs.com/grid/errors#${t.toLowerCase()}`}(t)}`}const l="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(t=>t.split("").reverse().join(""));new RegExp(`__(proto|defineGetter|defineSetter)|${l.slice(3).join("|")}|this\\b`);const d=new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing".split("|")),a=/^on\w+$/i,c=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),u=/^\s*(javascript|vbscript|data|blob):/i;function h(t){if(!t||"string"!=typeof t)return"";if(-1===t.indexOf("<"))return t;const e=document.createElement("template");return e.innerHTML=t,function(t){const e=[],i=t.querySelectorAll("*");for(const n of i){const t=n.tagName.toLowerCase();if(d.has(t)){e.push(n);continue}if("svg"===t||"http://www.w3.org/2000/svg"===n.namespaceURI){if(Array.from(n.attributes).some(t=>a.test(t.name)||"href"===t.name||"xlink:href"===t.name)){e.push(n);continue}}const i=[];for(const e of n.attributes){const t=e.name.toLowerCase();a.test(t)?i.push(e.name):(c.has(t)&&u.test(e.value)||"style"===t&&/expression\s*\(|javascript:|behavior\s*:/i.test(e.value))&&i.push(e.name)}i.forEach(t=>n.removeAttribute(t))}e.forEach(t=>t.remove())}(e.content),e.innerHTML}const f=/* @__PURE__ */new WeakMap;document.createElement("template").innerHTML='<div class="cell" role="gridcell" part="cell"></div>';function g(t,e){if(!e.capped)return t;const i=e.spacerHeight-e.viewportHeight,n=e.rawContentHeight-e.viewportHeight;return i<=0||n<=0?t:t*i/n}function w(t,e){if(t._virtualization?.enabled){const{rowHeight:e,container:i,viewportEl:n,scrollMapping:r}=t._virtualization,s=i,o=n?.clientHeight??s?.clientHeight??0;if(s&&o>0){const i=t._focusRow*e,n=r?function(t,e){if(!e.capped)return t;const i=e.spacerHeight-e.viewportHeight,n=e.rawContentHeight-e.viewportHeight;if(i<=0||n<=0)return t;const r=t*n/i;return r<0?0:r>n?n:r}(s.scrollTop,r):s.scrollTop;if(i<n)s.scrollTop=r?g(i,r):i;else if(i+e>n+o){const t=i-o+e;s.scrollTop=r?g(t,r):t}}}const i=void 0!==t._activeEditRows&&-1!==t._activeEditRows||!!t._isGridEditMode;var n;i||t.refreshVirtualWindow(!1),(n=t._bodyEl)&&n.querySelectorAll(".cell-focus").forEach(t=>t.classList.remove("cell-focus")),Array.from(t._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(t=>{t.setAttribute("aria-selected","false")});const s=t._focusRow,o=t._virtualization.start??0,l=t._virtualization.end??t._rows.length;if(s>=o&&s<l){const n=t._bodyEl.querySelectorAll(".data-grid-row")[s-o];let l=n?.children[t._focusCol];if(l&&l.classList?.contains("cell")||(l=n?.querySelector(`.cell[data-col="${t._focusCol}"]`)??n?.querySelector(".cell[data-col]")),l){l.classList.add("cell-focus"),l.setAttribute("aria-selected","true");const s=t.querySelector(".tbw-scroll-area");if(s&&l&&(!i||e?.forceHorizontalScroll))if(e?.forceScrollLeft)s.scrollLeft=0;else if(e?.forceScrollRight)s.scrollLeft=s.scrollWidth-s.clientWidth;else{const e=t._getHorizontalScrollOffsets?.(n??void 0,l)??{left:0,right:0};if(!e.skipScroll){const t=l.getBoundingClientRect(),i=s.getBoundingClientRect(),n=t.left-i.left+s.scrollLeft,r=n+t.width,o=s.scrollLeft+e.left,d=s.scrollLeft+s.clientWidth-e.right;n<o?s.scrollLeft=n-e.left:r>d&&(s.scrollLeft=r-s.clientWidth+e.right)}}if(i&&l.classList.contains(r)){const t=l.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');if(t&&document.activeElement!==t)try{t.focus({preventScroll:!0})}catch{}}else if(i&&!l.contains(document.activeElement)){l.hasAttribute("tabindex")||l.setAttribute("tabindex","-1");try{l.focus({preventScroll:!0})}catch{}}else if(!i){const e=document.activeElement;e instanceof HTMLElement&&e!==t&&"function"==typeof t.contains&&t.contains(e)&&!e.classList.contains("cell")&&!e.closest(".cell")||e===t||t.focus({preventScroll:!0})}}}}document.createElement("template").innerHTML='<div class="data-grid-row" role="row" part="row"></div>';class m{static dependencies;static manifest;aliases;version="2.17.2";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#t;get defaultConfig(){return{}}constructor(t={}){this.userConfig=t}get resolvedConfig(){return this.#t?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(t){if(0===t.length)return;const e={...this.userConfig},i={};for(const n of Object.keys(e))i[n]=this;for(const n of t){const t=n.userConfig;for(const[r,s]of Object.entries(t)){if(void 0===s)continue;if(!(r in e)){e[r]=s,i[r]=n;continue}if(e[r]===s)continue;const t=i[r]?.constructor.name??this.constructor.name,l=n.constructor.name,d=o("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${r}" supplied by both ${t} and ${l}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(d)}}Object.assign(this.userConfig,e)}refreshUserConfigFrom(t){const e=this.userConfig;for(const i of Object.keys(e))delete e[i];Object.assign(e,t.userConfig)}attach(t){this.#t?.abort(),this.#t=new AbortController,this.grid=t,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#t?.abort(),this.#t=void 0}getPlugin(t){return this.grid?.getPlugin(t)}emit(t,e){this.grid?.dispatchEvent?.(new CustomEvent(t,{detail:e,bubbles:!0}))}emitCancelable(t,e){const i=new CustomEvent(t,{detail:e,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(i),i.defaultPrevented}on(t,e){this.grid?._pluginManager?.subscribe(this,t,e)}off(t){this.grid?._pluginManager?.unsubscribe(this,t)}emitPluginEvent(t,e){this.grid?._pluginManager?.emitPluginEvent(t,e)}broadcast(t,e){this.emitPluginEvent(t,e),this.emit(t,e)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#t?.signal??this.grid?.disconnectSignal}get gridIcons(){const t=this.grid?.gridConfig?.icons??{};return{...e,...t}}get isAnimationEnabled(){const t=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===t||"off"===t)return!1;if(!0===t||"on"===t)return!0;const e=this.gridElement;if(e){return"0"!==getComputedStyle(e).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const t=this.gridElement;if(t){const e=getComputedStyle(t).getPropertyValue("--tbw-animation-duration").trim(),i=parseInt(e,10);if(!isNaN(i))return i}return 200}setIcon(t,e,i){t.dataset.icon=e.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===e?t.dataset.expanded="":"expand"===e&&delete t.dataset.expanded;const n=this.#e(e,i);void 0!==n?"string"==typeof n?t.innerHTML=h(n):n instanceof HTMLElement&&(t.innerHTML="",t.appendChild(n.cloneNode(!0))):t.innerHTML=""}#e(t,e){return void 0!==e?e:this.grid?.gridConfig?.icons?.[t]}updateSortIndicator(t,e){t.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const i=document.createElement("span");i.setAttribute("part","sort-indicator"),i.className="sort-indicator",e?(t.setAttribute("aria-sort","asc"===e?"ascending":"descending"),t.setAttribute("data-sort",e),this.setIcon(i,"asc"===e?"sortAsc":"sortDesc")):(t.setAttribute("aria-sort","none"),t.removeAttribute("data-sort"),this.setIcon(i,"sortNone"));const n=t.querySelector(".tbw-filter-btn")??t.querySelector(".resize-handle");return n?t.insertBefore(i,n):t.appendChild(i),i}warn(t,e){void 0!==e?console.warn(o(t,e,this.gridElement.id,this.name)):console.warn(`${s(this.gridElement.id,this.name)} ${t}`)}throwDiagnostic(t,e){throw new Error(o(t,e,this.gridElement.id,this.name))}}function p(t){return e=>{const i=t.editorParams,n=document.createElement("input");n.type="date",e.value instanceof Date?n.valueAsDate=e.value:"string"==typeof e.value&&e.value&&(n.value=e.value.split("T")[0]),i?.min&&(n.min=i.min),i?.max&&(n.max=i.max),i?.placeholder&&(n.placeholder=i.placeholder);return n.addEventListener("change",()=>{var r;if(n.value)"string"==typeof e.value?e.commit(n.value):e.commit(n.valueAsDate);else if(t.nullable)e.commit(null);else{const t=i?.default;"string"==typeof e.value||"string"==typeof t?e.commit("string"==typeof t?t:`${(r=t??/* @__PURE__ */new Date).getFullYear()}-${String(r.getMonth()+1).padStart(2,"0")}-${String(r.getDate()).padStart(2,"0")}`):e.commit(t instanceof Date?t:/* @__PURE__ */new Date)}}),n.addEventListener("keydown",t=>{"Escape"===t.key&&e.cancel()}),n}}const v="__tbw_null__";function b(t){switch(t.type){case"number":return function(t){return e=>{const i=t.editorParams,n=document.createElement("input");n.type="number",n.value=null!=e.value?String(e.value):"",void 0!==i?.min&&(n.min=String(i.min)),void 0!==i?.max&&(n.max=String(i.max)),void 0!==i?.step&&(n.step=String(i.step)),i?.placeholder&&(n.placeholder=i.placeholder);const r=()=>{""===n.value?t.nullable?e.commit(null):e.commit(i?.min??0):e.commit(Number(n.value))};return n.addEventListener("blur",r),n.addEventListener("keydown",t=>{"Enter"===t.key&&r(),"Escape"===t.key&&e.cancel()}),n}}(t);case"boolean":return t=>{const e=document.createElement("input");return e.type="checkbox",e.checked=!!t.value,e.addEventListener("change",()=>t.commit(e.checked)),e};case"date":return p(t);case"select":return function(t){return e=>{const i=t.editorParams,n=document.createElement("select");if(t.multi&&(n.multiple=!0),t.nullable||i?.includeEmpty){const r=document.createElement("option");r.value=t.nullable?v:"",r.textContent=t.nullable?i?.emptyLabel??"(Blank)":i?.emptyLabel??"",null==e.value&&(r.selected=!0),n.appendChild(r)}const r=function(t){const e=t.options;return e?"function"==typeof e?e():e:[]}(t);r.forEach(i=>{const r=document.createElement("option");r.value=String(i.value),r.textContent=i.label,t.multi&&Array.isArray(e.value)&&e.value.includes(i.value)?r.selected=!0:t.multi||e.value!==i.value||(r.selected=!0),n.appendChild(r)});const s=()=>{if(t.multi){const t=Array.from(n.selectedOptions).map(t=>t.value);e.commit(t)}else t.nullable&&n.value===v?e.commit(null):e.commit(n.value)};return n.addEventListener("change",s),n.addEventListener("blur",s),n.addEventListener("keydown",t=>{"Escape"===t.key&&e.cancel()}),n}}(t);default:return function(t){return e=>{const i=t.editorParams,n=document.createElement("input");n.type="text",n.value=null!=e.value?String(e.value):"",void 0!==i?.maxLength&&(n.maxLength=i.maxLength),i?.pattern&&(n.pattern=i.pattern),i?.placeholder&&(n.placeholder=i.placeholder);const r=()=>{const i=n.value;""!==i?"string"==typeof e.value&&i===e.value.replace(/[\n\r]/g,"")||("number"==typeof e.value?e.commit(Number(i)):e.commit(i)):t.nullable?e.commit(null):e.commit("")};return n.addEventListener("blur",r),n.addEventListener("keydown",t=>{"Enter"===t.key&&r(),"Escape"===t.key&&e.cancel()}),n}}(t)}}function y(t,e,i){if(t instanceof HTMLInputElement){if("checkbox"===t.type)return t.checked;if("number"===t.type){if(""===t.value){if(e?.nullable)return null;const t=e?.editorParams;return t?.min??0}return Number(t.value)}if("date"===t.type)return t.value?"string"==typeof i?t.value:t.valueAsDate:e?.nullable?null:"string"==typeof i?i||/* @__PURE__ */(new Date).toISOString().slice(0,10):i??/* @__PURE__ */new Date;if("number"==typeof i){if(""===t.value){if(e?.nullable)return null;const t=e?.editorParams;return t?.min??0}return Number(t.value)}return""===t.value&&null==i?e?.nullable?null:"":"string"==typeof i&&t.value===i.replace(/[\n\r]/g,"")?i:t.value}return"number"===e?.type&&""!==t.value||"number"==typeof i&&""!==t.value?Number(t.value):null==i&&""===t.value?e?.nullable?null:"":t.value}class E{#i=/* @__PURE__ */new Map;#n;constructor(t){this.#n=t}setInvalid(t,e,i=""){let n=this.#i.get(t);n||(n=/* @__PURE__ */new Map,this.#i.set(t,n)),n.set(e,i),this.#n(t,e,!0)}clearInvalid(t,e){const i=this.#i.get(t);i&&(i.delete(e),0===i.size&&this.#i.delete(t)),this.#n(t,e,!1)}clearRowInvalid(t){const e=this.#i.get(t);if(e){const i=Array.from(e.keys());this.#i.delete(t),i.forEach(e=>this.#n(t,e,!1))}}clearAllInvalid(){const t=Array.from(this.#i.entries());this.#i.clear(),t.forEach(([t,e])=>{e.forEach((e,i)=>this.#n(t,i,!1))})}isCellInvalid(t,e){return this.#i.get(t)?.has(e)??!1}getInvalidMessage(t,e){return this.#i.get(t)?.get(e)}hasInvalidCells(t){const e=this.#i.get(t);return!!e&&e.size>0}getInvalidFields(t){return new Map(this.#i.get(t)??[])}}function R(t,e,i){const n=t.get(e);return!!n&&!C(n,i)}function C(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(typeof t!=typeof e)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!C(t[i],e[i]))return!1;return!0}if("object"==typeof t){const i=t,n=e,r=Object.keys(i),s=Object.keys(n);if(r.length!==s.length)return!1;for(const t of r)if(!C(i[t],n[t]))return!1;return!0}return!1}function I(t,e,i){t.set(e,structuredClone(i))}function k(t,e,i){const n=t.get(e);if(!n)return!1;const r=n,s=i;for(const o of Object.keys(r))s[o]=r[o];return!0}class _{baselines=/* @__PURE__ */new Map;baselinesWereCaptured=!1;newRowIds=/* @__PURE__ */new Set;changedRowIds=/* @__PURE__ */new Set;committedDirtyRowIds=/* @__PURE__ */new Set;clear(){this.changedRowIds.clear(),this.committedDirtyRowIds.clear(),this.baselines.clear(),this.newRowIds.clear(),this.baselinesWereCaptured=!1}capture(t,e){const i=this.baselines.size;!function(t,e,i){for(const n of e)try{const e=i(n);null==e||t.has(e)||t.set(e,structuredClone(n))}catch{}}(this.baselines,t,e),this.baselines.size>i&&(this.baselinesWereCaptured=!0)}drainCapturedFlag(){return this.baselinesWereCaptured?(this.baselinesWereCaptured=!1,this.baselines.size):null}isRowDirty(t,e){return R(this.baselines,t,e)}hasAnyDirty(t){if(this.newRowIds.size>0)return!0;for(const[e]of this.baselines){const i=t(e);if(i&&R(this.baselines,e,i))return!0}return!1}isCellDirty(t,e,i){return function(t,e,i,n){const r=t.get(e);return!!r&&!C(r[n],i[n])}(this.baselines,t,e,i)}getRowDirtyState(t,e){const i=this.newRowIds.has(t);return{isNew:i,isCommittedDirty:!i&&this.committedDirtyRowIds.has(t)&&R(this.baselines,t,e),hasBaseline:this.baselines.has(t)}}markPristine(t,e){I(this.baselines,t,e),this.newRowIds.delete(t),this.changedRowIds.delete(t),this.committedDirtyRowIds.delete(t)}markNew(t){this.newRowIds.add(t),this.committedDirtyRowIds.add(t)}markDirty(t){this.changedRowIds.add(t),this.committedDirtyRowIds.add(t)}markAllPristine(t){for(const[e]of this.baselines){const i=t(e);i&&I(this.baselines,e,i)}this.newRowIds.clear(),this.changedRowIds.clear(),this.committedDirtyRowIds.clear()}getOriginalRow(t){return function(t,e){const i=t.get(e);return i?structuredClone(i):void 0}(this.baselines,t)}hasBaseline(t){return this.baselines.has(t)}getDirtyRows(t){const e=[];for(const[i,n]of this.baselines){const r=t(i);r&&R(this.baselines,i,r)&&e.push({id:i,original:structuredClone(n),current:r})}for(const i of this.newRowIds){const n=t(i);n&&e.push({id:i,original:void 0,current:n})}return e}getDirtyRowIds(t){const e=[];for(const[i]of this.baselines){const n=t(i);n&&R(this.baselines,i,n)&&e.push(i)}for(const i of this.newRowIds)e.push(i);return e}revertRow(t,e){const i=k(this.baselines,t,e);return i&&(this.changedRowIds.delete(t),this.committedDirtyRowIds.delete(t)),i}revertAll(t){for(const[e]of this.baselines){const i=t(e);i&&k(this.baselines,e,i)}this.changedRowIds.clear(),this.committedDirtyRowIds.clear()}getChangedRows(t){const e=[];for(const i of this.changedRowIds){const n=t(i);n&&e.push(n)}return e}getChangedRowIds(){return Array.from(this.changedRowIds)}isRowChanged(t){return this.changedRowIds.has(t)}}const S='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function A(t){const e=t;return e?.closest?.(S)??null}function x(t){return"string"==typeof t&&("__proto__"!==t&&"constructor"!==t&&"prototype"!==t)}function M(t){}function L(t,e){return!1===t.onBeforeEditClose?.(e)}function G(t,e,i,n,r,s,l,d){if(!n.editable)return;if(s.classList.contains("editing"))return;const{grid:a,isGridMode:c,config:u,editingCells:h,editorValueCallbacks:f}=t;let g;try{g=a.getRowId?.(e)}catch{}const w=g?t=>a.updateRow(g,t,"cascade"):M,m=x(n.field)?e[n.field]:void 0;s.classList.add("editing"),h.add(`${i}:${r}`);const p=d??s.parentElement;p&&function(t){const e=(t.__editingCellCount??0)+1;t.__editingCellCount=e,t.setAttribute("data-has-editing","")}(p);let v=!1;const E=r=>{if(v||!c&&!t.isEditSessionActive())return;const s=g?a._getRowEntry(g):void 0,o=s?.row??e,l=s?.index??i;t.commitCellValue(l,n,r,o)},R=()=>{if(v=!0,x(n.field)){const t=g?a._getRowEntry(g):void 0;(t?.row??e)[n.field]=m}},C=document.createElement("div");C.className="tbw-editor-host",s.firstElementChild&&a.__frameworkAdapter?.releaseCell?.(s),s.innerHTML="",s.appendChild(C),C.addEventListener("keydown",e=>{if(!e.defaultPrevented){if("Enter"===e.key){const t=e.target;if(t&&"true"===t.getAttribute?.("aria-expanded")&&t.hasAttribute?.("aria-controls"))return}if("Enter"===e.key){if(c){const t=e.target,i=A(t);if(i&&i!==t)return;e.preventDefault();const r=C.querySelector("input,textarea,select");return void(r&&E(y(r,n,m)))}if(L(u,e))return;e.stopPropagation(),e.preventDefault(),v=!0,t.exitRowEdit(i,!1)}if("Escape"===e.key){if(c)return e.stopPropagation(),void e.preventDefault();if(L(u,e))return;e.stopPropagation(),e.preventDefault(),R(),t.exitRowEdit(i,!0)}}});const I=n,k=I.__editorTemplate,_=function(t,e){if(e.editor)return e.editor;if(e.__editorTemplate)return"template";if(!e.type)return;const i=t.effectiveConfig?.typeDefaults;if(i?.[e.type]?.editor)return i[e.type].editor;const n=t.__frameworkAdapter;if(n?.getTypeDefault){const i=n.getTypeDefault(e.type,t._hostElement);if(i?.editor)return i.editor}}(a,I)??b(n),G=m,D=`${i}:${n.field}`,T=[];f.set(D,t=>{for(const e of T)e(t)});const q=t=>{T.push(t)};if("template"===_&&k)!function(t,e,i,n,r,s,o,l,d){const a=i.__editorTemplate;if(!a)return;const c=a.cloneNode(!0),u=i.__compiledEditor;u?c.innerHTML=u({row:n,value:r,field:i.field,column:i,commit:s,cancel:o}):c.querySelectorAll("*").forEach(t=>{1===t.childNodes.length&&t.firstChild?.nodeType===Node.TEXT_NODE&&(t.textContent=t.textContent?.replace(/{{\s*value\s*}}/g,null==r?"":String(r)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(t,e)=>{if(!x(e))return"";const i=n[e];return null==i?"":String(i)})||"")});const h=c.querySelector("input,textarea,select");if(h){h instanceof HTMLInputElement&&"checkbox"===h.type?h.checked=!!r:h.value=String(r??"");let e=!1;h.addEventListener("blur",()=>{e||s(y(h,i,r))}),h.addEventListener("keydown",n=>{const l=n;if("Enter"===l.key){if(L(t.config,l))return;l.stopPropagation(),l.preventDefault(),e=!0,s(y(h,i,r)),t.exitRowEdit(d,!1)}if("Escape"===l.key){if(L(t.config,l))return;l.stopPropagation(),l.preventDefault(),o(),t.exitRowEdit(d,!0)}}),h instanceof HTMLInputElement&&"checkbox"===h.type&&h.addEventListener("change",()=>s(h.checked)),l||setTimeout(()=>h.focus({preventScroll:!0}),0)}e.appendChild(c)}(t,C,I,e,m,E,R,l,i),q(t=>{if(null!=t&&"object"==typeof t)return;const e=C.querySelector("input,textarea,select");e&&(e instanceof HTMLInputElement&&"checkbox"===e.type?e.checked=!!t:e.value=String(t??""))});else if("string"==typeof _){const t=document.createElement(_);t.value=G,t.addEventListener("change",()=>E(t.value)),q(e=>{t.value=e}),C.appendChild(t),l||queueMicrotask(()=>{const t=C.querySelector(S);t?.focus({preventScroll:!0})})}else if("function"==typeof _){const i=_({row:e,rowId:g??"",value:G,field:n.field,column:n,commit:E,cancel:R,updateRow:w,onValueChange:q,grid:t.grid});if("string"==typeof i)C.innerHTML=i,function(t,e,i,n){const r=t.querySelector("input,textarea,select");r&&(r.addEventListener("blur",()=>{i(y(r,e,n))}),r instanceof HTMLInputElement&&"checkbox"===r.type?r.addEventListener("change",()=>i(r.checked)):r instanceof HTMLSelectElement&&r.addEventListener("change",()=>i(y(r,e,n))))}(C,n,E,m),q(t=>{const e=C.querySelector("input,textarea,select");e&&(e instanceof HTMLInputElement&&"checkbox"===e.type?e.checked=!!t:e.value=String(t??""))});else if(i instanceof Node){C.appendChild(i);i instanceof HTMLInputElement||i instanceof HTMLSelectElement||i instanceof HTMLTextAreaElement?q(t=>{i instanceof HTMLInputElement&&"checkbox"===i.type?i.checked=!!t:i.value=String(t??"")}):s.setAttribute("data-editor-managed","")}else!i&&C.hasChildNodes()&&s.setAttribute("data-editor-managed","");l||queueMicrotask(()=>{const t=C.querySelector(S);t?.focus({preventScroll:!0})})}else if(_&&"object"==typeof _){const i=document.createElement("div");i.setAttribute("data-external-editor",""),i.setAttribute("data-field",n.field),C.appendChild(i),s.setAttribute("data-editor-managed","");const r={row:e,rowId:g??"",value:G,field:n.field,column:n,commit:E,cancel:R,updateRow:w,onValueChange:q,grid:t.grid};if(_.mount)try{_.mount({placeholder:i,context:r,spec:_})}catch(N){$="TBW080",F=`External editor mount error for column '${n.field}': ${N}`,P=t.grid.id,console.warn(o($,F,P,H))}else a.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:i,spec:_,context:r}}))}var $,F,P,H}class D extends m{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:t=>!0===t||"function"==typeof t},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'},{property:"nullable",level:"column",description:'the "nullable" column property (allows null values)'}],events:[{type:"cell-edit-committed",description:"Emitted when a cell edit is committed (for plugin-to-plugin coordination)"}],queries:[{type:"isEditing",description:"Returns whether any cell is currently being edited"},{type:"getEditableFields",description:"Returns the field names of columns that are unconditionally editable (editable === true), for consumers like clipboard paste"}]};name="editing";styles="@layer tbw-plugins{tbw-grid{--tbw-editing-bg: var(--tbw-color-selection);--tbw-editing-row-bg: var(--tbw-editing-bg);--tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));--tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);--tbw-font-size-editor: inherit;--tbw-editing-row-outline-color: var(--tbw-color-accent);--tbw-editing-row-outline-width: 1px;--tbw-invalid-bg: light-dark(#fef2f2, #450a0a);--tbw-invalid-border-color: light-dark(#ef4444, #f87171)}tbw-grid:not(.tbw-grid-mode) .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:max(var(--tbw-row-height),calc(1lh + 2 * var(--tbw-cell-padding-v, .25em) + var(--tbw-border-width, 1px)));align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;align-self:stretch;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}tbw-grid .data-grid-row>.cell[data-invalid=true]{background:var(--tbw-invalid-bg);outline:1px solid var(--tbw-invalid-border-color);outline-offset:-1px}}";get defaultConfig(){return{mode:"row",editOn:"click"}}get#r(){return"grid"===this.config.mode}#s(t,e){const i=this.#o.effectiveConfig?.rowEditable;if(i&&!i(e))return!1;const{editable:n}=t;return"function"==typeof n?n(e):!0===n}#l(t){return!0===t.editable||"function"==typeof t.editable}#d=-1;#a;#c;#u=-1;#h=/* @__PURE__ */new Map;#f=/* @__PURE__ */new Set;#g=/* @__PURE__ */new WeakSet;#w=/* @__PURE__ */new Map;#m=!1;#p=-1;#v;#b=!1;#y=!1;#E=!1;#R=null;#C=new _;#I;get#o(){return this.grid}attach(t){super.attach(t);const e=this.disconnectSignal,i=this.#o;if(this.#v=new E((t,e,i)=>{this.#k(t,e,i)}),this.#I={grid:i,isGridMode:this.#r,config:this.config,editingCells:this.#f,editorValueCallbacks:this.#w,isEditSessionActive:()=>-1!==this.#d,commitCellValue:(t,e,i,n)=>this.#_(t,e,i,n),exitRowEdit:(t,e)=>this.#S(t,e)},this.#A(),Object.defineProperty(t,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(t,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),Object.defineProperty(t,"_changedRowIdSet",{get:()=>this.#C.changedRowIds,configurable:!0}),t.resetChangedRows=t=>this.resetChangedRows(t),document.addEventListener("keydown",t=>{if(!this.#r&&"Escape"===t.key&&-1!==this.#d){if(L(this.config,t))return;this.#S(this.#d,!0)}},{capture:!0,signal:e}),document.addEventListener("mousedown",t=>{if(this.#r)return;if(-1===this.#d)return;const e=i.findRenderedRowElement?.(this.#d);if(!e)return;if((t.composedPath&&t.composedPath()||[]).includes(e))return;const n=t.target;if(!n||this.gridElement.contains(n)||!this.grid.containsFocus?.(n)){if(n&&!this.gridElement.contains(n)){const t=i.findRenderedRowElement?.(this.#d);if(t&&function(t,e){if(!t)return!1;const i=e.querySelectorAll('[aria-expanded="true"][aria-controls]');for(let n=0;n<i.length;n++){const r=i[n].getAttribute("aria-controls");if(!r)continue;const s=e.ownerDocument?.getElementById(r);if(s&&s.contains(t))return!0}return!1}(n,t))return}L(this.config,t)||queueMicrotask(()=>{-1!==this.#d&&this.#S(this.#d,!1)})}},{signal:e}),this.config.focusTrap&&this.gridElement.addEventListener("focusout",t=>{if(this.#r)return;if(-1===this.#d)return;const e=t.relatedTarget;e&&this.grid.containsFocus?.(e)||e&&this.gridElement.contains(e)||queueMicrotask(()=>{-1!==this.#d&&this.#x()})},{signal:e}),this.gridElement.addEventListener("cell-change",t=>{const e=t.detail;if("user"===e.source)return;const i=`${e.rowIndex}:${e.field}`,n=this.#w.get(i);n&&n(e.newValue)},{signal:e}),this.config.dirtyTracking){const t=t=>{const e=t.detail,i=e?.action;if(!i)return;const n=this.rows[i.rowIndex];if(!n)return;const r=this.#M(n);if(!r)return;const s=this.#C.isRowDirty(r,n);this.#L(r,n,s?"modified":"pristine")};this.gridElement.addEventListener("undo",t,{signal:e}),this.gridElement.addEventListener("redo",t,{signal:e}),this.on("row-inserted",t=>{const e=this.#M(t.row);null!=e&&this.markAsNew(String(e))})}this.#r&&(i._isGridEditMode=!0,this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",t=>{const e=t.target;if(e!==this.gridElement&&e.matches(S)){if(this.#y)return e.blur(),void this.gridElement.focus();const t=i._focusRow,n=i._focusCol,r=this.#R;if(!r||r.rowIndex!==t||r.colIndex!==n){const e=i._visibleColumns?.[n],r=i._rows?.[t];if(e?.field&&r){const i=e.field;this.#R={rowIndex:t,colIndex:n,field:i,value:r[i]}}}this.#b=!0}},{signal:e}),this.gridElement.addEventListener("focusout",t=>{const e=t.target,i=t.relatedTarget;if(e&&i){if(e.contains(i))return;const t=A(i);if(t&&t!==this.gridElement&&this.gridElement.contains(t))return}i&&(this.gridElement.contains(i)||this.grid.containsFocus?.(i))&&i.matches(S)||(this.#b=!1,this.#R=null)},{signal:e}),this.gridElement.addEventListener("keydown",t=>{if("Escape"===t.key&&this.#b){if(L(this.config,t))return void queueMicrotask(()=>{this.#b&&this.#G()});this.#G(),t.preventDefault(),t.stopPropagation()}},{capture:!0,signal:e}),this.gridElement.addEventListener("mousedown",t=>{t.target.matches(S)&&(this.#y=!1)},{signal:e}))}detach(){this.#o._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#d=-1,this.#a=void 0,this.#c=void 0,this.#u=-1,this.#h.clear(),this.#C.clear(),this.#f.clear(),this.#w.clear(),this.#b=!1,this.#y=!1,this.#R=null,this.#E=!1,this.#g=/* @__PURE__ */new WeakSet,super.detach()}handleQuery(t){if("isEditing"===t.type)return this.#r||-1!==this.#d;if("getEditableFields"===t.type){const e=t.context;return(e?.columns??this.#o.effectiveConfig?.columns??[]).filter(t=>!0===t.editable).map(t=>t.field)}}onCellClick(t){if(this.#r)return!1;const e=this.#o,i=this.config.editOn??e.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;if("click"!==i&&"dblclick"!==i)return!1;const n="dblclick"===t.originalEvent.type;if("click"===i&&n)return!1;if("dblclick"===i&&!n)return!1;const{rowIndex:r}=t,s=e._columns?.some(t=>this.#l(t));return!!s&&(!!this.#D(e._rows[r])&&(t.originalEvent.stopPropagation(),this.beginBulkEdit(r),!0))}onKeyDown(t){const e=this.#o;if("Escape"===t.key){if(this.#r&&this.#b)return this.#G(),this.requestAfterRender(),!0;if(-1!==this.#d&&!this.#r)return L(this.config,t)||this.#S(this.#d,!0),!0}const i=A(t.target),n=!!i&&i!==this.gridElement;if(this.#r&&!this.#b&&!n&&("ArrowUp"===t.key||"ArrowDown"===t.key||"ArrowLeft"===t.key||"ArrowRight"===t.key))return!1;if(this.#r&&(this.#b||n)&&("ArrowUp"===t.key||"ArrowDown"===t.key))return!0;if(("ArrowUp"===t.key||"ArrowDown"===t.key)&&-1!==this.#d&&!this.#r)return!0;if("Tab"===t.key&&(-1!==this.#d||this.#r)){if(t.preventDefault(),this.#E)return this.#S(this.#d,!1),!0;const e=!t.shiftKey;return this.#T(e),!0}if(" "===t.key||"Spacebar"===t.key){if(-1!==this.#d)return!1;const i=e._focusRow,n=e._focusCol;if(i>=0&&n>=0){const r=e._visibleColumns[n],s=e._rows[i];if(r&&s&&this.#s(r,s)&&"boolean"===r.type){const e=r.field;if(x(e)){const n=!s[e];return this.#_(i,r,n,s),t.preventDefault(),this.requestRender(),!0}}}return!1}if(!("Enter"!==t.key||t.shiftKey||t.ctrlKey||t.altKey||t.metaKey)){if(this.#r&&!this.#b)return this.#x(),!0;if(this.#r&&this.#b){const e=A(t.target);if(e&&e!==t.target)return!0;this.#R=null;const i=document.activeElement;return i&&this.gridElement.contains(i)&&(i.blur(),this.gridElement.focus()),this.#b=!1,this.#y=!0,this.requestAfterRender(),!0}if(-1!==this.#d){const e=t.target;return(!e||"true"!==e.getAttribute?.("aria-expanded")||!e.hasAttribute?.("aria-controls"))&&!!L(this.config,t)}const i=this.config.editOn??e.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;const n=e._focusRow,r=e._focusCol;if(n>=0){const i=e._columns?.some(t=>this.#l(t)),s=e._rows[n];if(i&&this.#D(s)){const i=e._visibleColumns[r],s=e._rows[n],o=i?.field??"",l=o&&s?s[o]:void 0,d=this.gridElement.querySelector(`[data-row="${n}"][data-col="${r}"]`),a=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:n,colIndex:r,field:o,value:l,row:s,cellEl:d,trigger:"keyboard",originalEvent:t}});return this.gridElement.dispatchEvent(a),a.defaultPrevented?(t.preventDefault(),!0):(this.beginBulkEdit(n),!0)}}return!1}if("F2"===t.key){if(-1!==this.#d||this.#r)return!1;if(!1===(this.config.editOn??e.effectiveConfig?.editOn))return!1;const i=e._focusRow,n=e._focusCol;if(i>=0&&n>=0){const r=e._visibleColumns[n],s=e._rows[i];if(r&&s&&this.#s(r,s)&&r.field)return t.preventDefault(),this.beginCellEdit(i,r.field),!0}return!1}return!1}processColumns(t){const e=this.#o,i=e.effectiveConfig?.typeDefaults,n=e.__frameworkAdapter,r=!!i||!!n?.getTypeDefault;return t.map(t=>{const s=t.__element;if(s&&!this.#g.has(s)){this.#g.add(s),null==t.editable&&s.hasAttribute("editable")&&(t.editable="false"!==s.getAttribute("editable"));const e=t;if(!e.__editorTemplate){const t=s.querySelector("tbw-grid-column-editor");t&&(e.__editorTemplate=t)}}if(!t.type||!r)return t;let o;if(i?.[t.type]?.editorParams&&(o=i[t.type].editorParams),!o&&n?.getTypeDefault){const i=n.getTypeDefault(t.type,e._hostElement);i?.editorParams&&(o=i.editorParams)}return o?{...t,editorParams:{...o,...t.editorParams}}:t})}processRows(t){const e=this.#o;if(this.config.dirtyTracking&&e.getRowId&&this.#C.capture(t,t=>{try{return e.getRowId?.(t)}catch{return}}),-1===this.#d||this.#r)return t;const i=this.#a,n=this.#c;if(!i||!n)return t;const r=[...t];let s=-1;for(let o=0;o<r.length;o++)if(this.#M(r[o])===i){s=o;break}return-1===s?(setTimeout(()=>this.cancelActiveRowEdit(),0),r):(r[s]=n,this.#d!==s&&this.#q(this.#d,s),r)}afterRender(){const t=this.#o;if(-1!==this.#d&&this.#c&&!this.#r&&t._rows[this.#d]!==this.#c){const e=t._rows.indexOf(this.#c);if(-1===e)return void setTimeout(()=>this.cancelActiveRowEdit(),0);this.#q(this.#d,e)}if(this.#m&&(this.#m=!1,this.#$(t)),-1!==this.#p){const e=this.#p;this.#p=-1,t.animateRow?.(e,"change")}const e=this.#C.drainCapturedFlag();if(null!=e&&this.emit("baselines-captured",{count:e}),!this.#r&&0!==this.#f.size)for(const i of this.#f){const[e,n]=i.split(":"),r=parseInt(e,10),s=parseInt(n,10),o=this.#F(r,s);if(!o||o.classList.contains("editing"))continue;const l=t._rows[r],d=t._visibleColumns[s];l&&d&&this.#P(l,r,d,s,o,!0)}}afterCellRender(t){const{row:e,rowIndex:i,column:n,colIndex:r,cellElement:s}=t,o=this.#s(n,e);if(o)s.removeAttribute("aria-readonly");else if(s.setAttribute("aria-readonly","true"),this.#r&&s.classList.contains("editing")){s.classList.remove("editing");const t=e[n.field];s.textContent=null==t?"":String(t)}this.#r&&o&&(s.classList.contains("editing")||this.#P(e,i,n,r,s,!0,t.rowElement))}afterRowRender(t){if(!this.config.dirtyTracking)return;const e=this.#o,i=e.getRowId?.(t.row);if(!i)return;const{isNew:n,isCommittedDirty:r,hasBaseline:s}=this.#C.getRowDirtyState(i,t.row),o=t.rowElement;if(o.classList.toggle("tbw-row-dirty",r),o.classList.toggle("tbw-row-new",n),s){const e=o.querySelectorAll(".cell[data-field]");for(let n=0;n<e.length;n++){const r=e[n],s=r.getAttribute("data-field");s&&r.classList.toggle("tbw-cell-dirty",this.#C.isCellDirty(i,t.row,s))}}else{const t=o.querySelectorAll(".tbw-cell-dirty");for(let e=0;e<t.length;e++)t[e].classList.remove("tbw-cell-dirty")}}onScrollRender(){this.afterRender()}get changedRows(){return this.#C.getChangedRows(t=>this.grid.getRow(t))}get changedRowIds(){return this.#C.getChangedRowIds()}get activeEditRow(){return this.#d}get activeEditCol(){return this.#u}isRowEditing(t){return this.#d===t}isCellEditing(t,e){return this.#f.has(`${t}:${e}`)}isRowChanged(t){const e=this.#o,i=e._rows[t];if(!i)return!1;try{const t=e.getRowId?.(i);return!!t&&this.#C.isRowChanged(t)}catch{return!1}}isRowChangedById(t){return this.#C.isRowChanged(t)}isDirty(t){if(!this.config.dirtyTracking)return!1;if(this.#C.newRowIds.has(t))return!0;const e=this.grid.getRow(t);return!!e&&this.#C.isRowDirty(t,e)}isPristine(t){return!this.isDirty(t)}get dirty(){if(!this.config.dirtyTracking)return!1;const t=this.#o;return this.#C.hasAnyDirty(e=>t._getRowEntry(e)?.row)}get pristine(){return!this.dirty}markAsPristine(t){if(!this.config.dirtyTracking)return;const e=this.grid.getRow(t);e&&(this.#C.markPristine(t,e),this.emit("dirty-change",{rowId:t,row:e,original:e,type:"pristine"}))}markAsNew(t){if(!this.config.dirtyTracking)return;this.#C.markNew(t);const e=this.grid.getRow(t);this.emit("dirty-change",{rowId:t,row:e,original:void 0,type:"new"})}markAsDirty(t){if(!this.config.dirtyTracking)return;const e=this.grid.getRow(t);e&&(this.#C.markDirty(t),this.#L(t,e,"modified"))}markAllPristine(){if(!this.config.dirtyTracking)return;const t=this.#o;this.#C.markAllPristine(e=>t._getRowEntry(e)?.row)}getOriginalRow(t){if(this.config.dirtyTracking)return this.#C.getOriginalRow(t)}hasBaseline(t){return!!this.config.dirtyTracking&&this.#C.hasBaseline(t)}getDirtyRows(){if(!this.config.dirtyTracking)return[];const t=this.#o;return this.#C.getDirtyRows(e=>t._getRowEntry(e)?.row)}get dirtyRowIds(){if(!this.config.dirtyTracking)return[];const t=this.#o;return this.#C.getDirtyRowIds(e=>t._getRowEntry(e)?.row)}revertRow(t){if(!this.config.dirtyTracking)return;const e=this.grid.getRow(t);e&&this.#C.revertRow(t,e)&&(this.#L(t,e,"reverted"),this.requestRender())}revertAll(){if(!this.config.dirtyTracking)return;const t=this.#o;this.#C.revertAll(e=>t._getRowEntry(e)?.row),this.requestRender()}setInvalid(t,e,i=""){this.#v.setInvalid(t,e,i)}clearInvalid(t,e){this.#v.clearInvalid(t,e)}clearRowInvalid(t){this.#v.clearRowInvalid(t)}clearAllInvalid(){this.#v.clearAllInvalid()}isCellInvalid(t,e){return this.#v.isCellInvalid(t,e)}getInvalidMessage(t,e){return this.#v.getInvalidMessage(t,e)}hasInvalidCells(t){return this.#v.hasInvalidCells(t)}getInvalidFields(t){return this.#v.getInvalidFields(t)}resetChangedRows(t){const e=this.changedRows,i=this.changedRowIds;this.#C.changedRowIds.clear(),this.#C.committedDirtyRowIds.clear(),this.#A(),t||this.emit("changed-rows-reset",{rows:e,ids:i});const n=this.#o;n._rowPool?.forEach(t=>t.classList.remove("changed"))}beginCellEdit(t,e){const i=this.#o,n=i._visibleColumns.findIndex(t=>t.field===e);if(-1===n)return;const r=i._visibleColumns[n],s=i._rows[t];if(!r||!s||!this.#s(r,s))return;const o=this.#F(t,n);o&&(this.#E=!0,this.#H(t,n,o))}beginBulkEdit(t){const e=this.#o;if(!1===(this.config.editOn??e.effectiveConfig?.editOn))return;const i=e._columns?.some(t=>this.#l(t));if(!i)return;const n=e.findRenderedRowElement?.(t);if(!n)return;const r=e._rows[t];this.#D(r)&&(this.#E=!1,this.#N(t,r),Array.from(n.children).forEach((i,n)=>{const s=e._visibleColumns[n];if(s&&this.#s(s,r)){const e=i;e.classList.contains("editing")||this.#P(r,t,s,n,e,!0)}}),setTimeout(()=>{let t=n.querySelector(`.cell[data-col="${e._focusCol}"]`);if(t?.classList.contains("editing")||(t=n.querySelector(".cell.editing")),t?.classList.contains("editing")){const e=t.querySelector(S);try{e?.focus({preventScroll:!0})}catch{}}},0))}commitActiveRowEdit(){-1!==this.#d&&this.#S(this.#d,!1)}cancelActiveRowEdit(){-1!==this.#d&&this.#S(this.#d,!0)}#M(t){if(t)try{return this.#o.getRowId?.(t)}catch{return}}#F(t,e){const i=this.#o.findRenderedRowElement?.(t);return i?.querySelector(`.cell[data-col="${e}"]`)??null}#D(t){if(!t)return!0;const e=this.#o.effectiveConfig?.rowEditable;return!e||!1!==e(t)}#L(t,e,i){this.emit("dirty-change",{rowId:t,row:e,original:this.#C.getOriginalRow(t),type:i})}#G(){this.#O();const t=document.activeElement;t&&this.gridElement.contains(t)&&(t.blur(),this.gridElement.focus()),this.#b=!1,this.#y=!0}#V(t,e,i){i&&(Object.keys(i).forEach(t=>{e[t]=i[t]}),t&&(this.#C.changedRowIds.delete(t),this.#C.committedDirtyRowIds.delete(t),this.clearRowInvalid(t)))}#k(t,e,i){const n=this.#o,r=n._visibleColumns?.findIndex(t=>t.field===e);if(-1===r||void 0===r)return;const s=n._rows,o=s?.findIndex(e=>this.#M(e)===t);if(-1===o||void 0===o)return;const l=this.#F(o,r);if(l)if(i){l.setAttribute("data-invalid","true");const i=this.#v.getInvalidMessage(t,e);i&&l.setAttribute("title",i)}else l.removeAttribute("data-invalid"),l.removeAttribute("title")}#q(t,e){this.#d=e;const i=/* @__PURE__ */new Set,n=`${t}:`;for(const o of this.#f)o.startsWith(n)?i.add(`${e}:${o.substring(n.length)}`):i.add(o);this.#f.clear();for(const o of i)this.#f.add(o);const r=this.#h.get(t);void 0!==r&&(this.#h.delete(t),this.#h.set(e,r));const s=[];for(const[o,l]of this.#w)o.startsWith(n)&&(s.push([`${e}:${o.substring(n.length)}`,l]),this.#w.delete(o));for(const[o,l]of s)this.#w.set(o,l);this.#A()}#H(t,e,i){const n=this.#o,r=n._rows[t],s=n._visibleColumns[e];r&&s&&this.#s(s,r)&&(i.classList.contains("editing")||(this.#d!==t&&this.#N(t,r),this.#u=e,this.#P(r,t,s,e,i,!1)))}#O(){const t=this.#R;if(!t)return;const e=this.#o,i=e._rows?.[t.rowIndex];i&&(i[t.field]=t.value);const n=`${t.rowIndex}:${t.field}`,r=this.#w.get(n);if(r&&r(t.value),this.emit("cell-cancel",{rowIndex:t.rowIndex,colIndex:t.colIndex,field:t.field,previousValue:t.value}),i){const t=this.#M(i);t&&(this.config.dirtyTracking?this.#C.isRowDirty(t,i)||(this.#C.changedRowIds.delete(t),this.#L(t,i,"reverted")):this.#C.changedRowIds.delete(t))}this.requestRender(),this.#R=null}#x(){const t=this.#o,e=t._focusRow,i=t._focusCol;if(e<0||i<0)return;const n=this.#F(e,i);if(n?.classList.contains("editing")){const t=n.querySelector(S);t&&(this.#y=!1,t.focus(),this.#b=!0,t instanceof HTMLInputElement&&("text"===t.type||"number"===t.type)&&t.select())}}#T(t){const e=this.#o,i=e._rows,n=this.#r?e._focusRow:this.#d,r=i[n],s=e._visibleColumns.map((t,e)=>r&&this.#s(t,r)?e:-1).filter(t=>t>=0);if(0===s.length)return;const o=s.indexOf(e._focusCol)+(t?1:-1);if(o>=0&&o<s.length){e._focusCol=s[o];const t=this.#F(n,s[o]);if(t?.classList.contains("editing")){const e=t.querySelector(S);e?.focus({preventScroll:!0})}return void w(e,{forceHorizontalScroll:!0})}const l=n+(t?1:-1);if(l>=0&&l<i.length){const r=i[l],s=e._visibleColumns.map((t,e)=>r&&this.#s(t,r)?e:-1).filter(t=>t>=0);if(0===s.length)return;this.#r?(e._focusRow=l,e._focusCol=t?s[0]:s[s.length-1],w(e,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const t=this.#F(l,e._focusCol);if(t?.classList.contains("editing")){const e=t.querySelector(S);e?.focus({preventScroll:!0})}},0)):(this.#S(n,!1),e._focusRow=l,e._focusCol=t?s[0]:s[s.length-1],this.beginBulkEdit(l),w(e,{forceHorizontalScroll:!0}))}}#A(){const t=this.#o;t._activeEditRows=this.#d,t._rowEditSnapshots=this.#h}#N(t,e){this.#d!==t&&(-1!==this.#d&&this.#S(this.#d,!1),this.#h.set(t,{...e}),this.#d=t,this.#c=e,this.#a=this.#M(e),this.#A(),this.#r||(this.broadcast("edit-open",{rowIndex:t,rowId:this.#a??"",row:e}),i(this.gridElement,n(this.gridElement,"editingStarted",t))))}#S(t,e){if(this.#d!==t)return;const r=this.#o,s=this.#h.get(t),o=r.findRenderedRowElement?.(t);let l=this.#a;const d=l?r._getRowEntry(l):void 0,a=d?.row??this.#c??r._rows[t];if(!l&&a&&(l=this.#M(a)),!e&&o&&a){o.querySelectorAll(".cell.editing").forEach(e=>{const i=Number(e.getAttribute("data-col"));if(isNaN(i))return;const n=r._visibleColumns[i];if(!n)return;if(e.hasAttribute("data-editor-managed"))return;const s=e.querySelector("input,textarea,select");if(s){const e=n.field,i=a[e],r=y(s,n,i);i!==r&&this.#_(t,n,r,a)}})}if(e||this.#r||!a||this.emit("before-edit-close",{rowIndex:t,rowId:l??"",row:a}),e&&a)this.#V(l,a,s);else if(!e&&a){const e=function(t,e){if(!t)return!1;const i=t,n=e,r=/* @__PURE__ */new Set([...Object.keys(i),...Object.keys(n)]);for(const s of r)if(i[s]!==n[s])return!0;return!1}(s,a),i=l?this.#C.changedRowIds.has(l):e,n=this.emitCancelable("row-commit",{rowIndex:t,rowId:l??"",row:a,oldValue:s,newValue:a,changed:i,changedRows:this.changedRows,changedRowIds:this.changedRowIds});n&&s?this.#V(l,a,s):n||(l&&this.config.dirtyTracking&&(this.#C.isRowDirty(l,a)?this.#C.committedDirtyRowIds.add(l):this.#C.committedDirtyRowIds.delete(l)),e&&this.isAnimationEnabled&&(this.#p=t))}this.#h.delete(t),this.#d=-1,this.#a=void 0,this.#c=void 0,this.#u=-1,this.#E=!1,this.#A();for(const i of this.#f)i.startsWith(`${t}:`)&&this.#f.delete(i);for(const i of this.#w.keys())i.startsWith(`${t}:`)&&this.#w.delete(i);if(this.#m=!0,o){const t=r.__frameworkAdapter,e=o.querySelectorAll(".cell.editing");t?.releaseCell&&e.forEach(e=>{t.releaseCell(e)}),e.forEach(t=>{t.classList.remove("editing"),function(t){t.__editingCellCount=0,t.removeAttribute("data-has-editing")}(t.parentElement)}),r.refreshVirtualWindow(!0)}else this.#$(r),this.#m=!1;!this.#r&&a&&(this.broadcast("edit-close",{rowIndex:t,rowId:l??"",row:a,reverted:e}),e||i(this.gridElement,n(this.gridElement,"editingCommitted",t)))}#_(t,e,i,n){const r=e.field;if(!x(r))return;const s=n[r];if(s===i)return;const o=this.#o,l=this.#M(n),d=!l||!this.#C.changedRowIds.has(l),a=l?t=>this.grid.updateRow(l,t,"cascade"):M;let c=!1;const u=l?t=>{c=!0,this.setInvalid(l,r,t??"")}:()=>{};if(this.emitCancelable("cell-commit",{row:n,rowId:l??"",field:r,oldValue:s,value:i,rowIndex:t,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:d,updateRow:a,setInvalid:u}))return;if(l&&!c&&this.isCellInvalid(l,r)&&this.clearInvalid(l,r),n[r]=i,function(t,e){t&&(e?f.get(t)?.delete(e):f.delete(t))}(n,r),l&&this.#C.changedRowIds.add(l),this.#A(),this.config.dirtyTracking&&l){const t=this.#C.isRowDirty(l,n);this.#L(l,n,t?"modified":"pristine")}this.emitPluginEvent("cell-edit-committed",{rowIndex:t,field:r,oldValue:s,newValue:i});const h=o.findRenderedRowElement?.(t);h&&h.classList.add("changed")}#P(t,e,i,n,r,s,o){G(this.#I,t,e,i,n,r,s,o)}#$(t){queueMicrotask(()=>{try{const e=t._focusRow,i=t._focusCol,n=t.findRenderedRowElement?.(e);if(n){Array.from(t._bodyEl.querySelectorAll(".cell-focus")).forEach(t=>t.classList.remove("cell-focus"));const r=n.querySelector(`.cell[data-row="${e}"][data-col="${i}"]`);r&&(r.classList.add("cell-focus"),r.setAttribute("aria-selected","true"),r.hasAttribute("tabindex")||r.setAttribute("tabindex","-1"),r.focus({preventScroll:!0}))}}catch{}})}}export{D as EditingPlugin,b as defaultEditorFor};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- const e=/* @__PURE__ */new WeakMap;function t(t,r,s=-1){if(!r.valueAccessor)return t?.[r.field];if("object"!=typeof t||null===t)return r.valueAccessor({row:t,column:r,rowIndex:s});const o=t,n=r.field;let i=e.get(o);if(i){const e=i.get(n);if(void 0!==e)return e.v}else i=/* @__PURE__ */new Map,e.set(o,i);const l=r.valueAccessor({row:t,column:r,rowIndex:s});return i.set(n,{v:l}),l}function r(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function s(e,t,s,o){return`${r(s,o)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}const o="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join(""));new RegExp(`__(proto|defineGetter|defineSetter)|${o.slice(3).join("|")}|this\\b`);const n=new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing".split("|")),i=/^on\w+$/i,l=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),a=/^\s*(javascript|vbscript|data|blob):/i;function c(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],r=e.querySelectorAll("*");for(const s of r){const e=s.tagName.toLowerCase();if(n.has(e)){t.push(s);continue}if("svg"===e||"http://www.w3.org/2000/svg"===s.namespaceURI){if(Array.from(s.attributes).some(e=>i.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(s);continue}}const r=[];for(const t of s.attributes){const e=t.name.toLowerCase();i.test(e)?r.push(t.name):(l.has(e)&&a.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&r.push(t.name)}r.forEach(e=>s.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}const u={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class f{static dependencies;static manifest;aliases;version="2.17.1";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},r={};for(const s of Object.keys(t))r[s]=this;for(const o of e){const e=o.userConfig;for(const[n,i]of Object.entries(e)){if(void 0===i)continue;if(!(n in t)){t[n]=i,r[n]=o;continue}if(t[n]===i)continue;const e=r[n]?.constructor.name??this.constructor.name,l=o.constructor.name,a=s("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${n}" supplied by both ${e} and ${l}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(a)}}Object.assign(this.userConfig,t)}refreshUserConfigFrom(e){const t=this.userConfig;for(const r of Object.keys(t))delete t[r];Object.assign(t,e.userConfig)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const r=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(r),r.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...u,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),r=parseInt(t,10);if(!isNaN(r))return r}return 200}setIcon(e,t,r){e.dataset.icon=t.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const s=this.#t(t,r);void 0!==s?"string"==typeof s?e.innerHTML=c(s):s instanceof HTMLElement&&(e.innerHTML="",e.appendChild(s.cloneNode(!0))):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const r=document.createElement("span");r.setAttribute("part","sort-indicator"),r.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(r,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(r,"sortNone"));const s=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return s?e.insertBefore(r,s):e.appendChild(r),r}warn(e,t){void 0!==t?console.warn(s(e,t,this.gridElement.id,this.name)):console.warn(`${r(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(s(e,t,this.gridElement.id,this.name))}}function d(e,t,r=!0){let s=e;if(r&&(s=s.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.utility)),t?.length){const e=new Set(t);s=s.filter(t=>e.has(t.field))}return s}function h(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}function g(e,t=!0){return"string"==typeof e?t&&(e.includes(",")||e.includes('"')||e.includes("\n")||e.includes("\r"))?`"${e.replace(/"/g,'""')}"`:e:"number"==typeof e?String(e):"boolean"==typeof e?e?"true":"false":null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}function p(e,r,s,o={}){const n=o.delimiter??",",i=o.newline??"\n",l=o.quoteStrings??!0,a=[],c=o.bom?"\ufeff":"";if(!1!==s.includeHeaders){const e=r.map(e=>{const t=e.header||e.field;return g(s.processHeader?s.processHeader(t,e.field):t,l)});a.push(e.join(n))}for(const u of e){const e=r.map(e=>{let r=t(u,e);return s.processCell&&(r=s.processCell(r,e.field,u)),g(r,l)});a.push(e.join(n))}return c+a.join(i)}function m(e,t){const r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.style.display="none",document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(r)}function b(e){return JSON.stringify(y(e))}function y(e){if(null==e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(y);const t={};for(const r of Object.keys(e).sort())t[r]=y(e[r]);return t}class w{#r=/* @__PURE__ */new Map;#s=0;register(e){const t=b(e),r=this.#r.get(t);if(r)return r.id;this.#s++;const s=`s${this.#s}`;return this.#r.set(t,{id:s,style:e}),s}getStyleId(e){return this.#r.get(b(e))?.id}get size(){return this.#r.size}toXml(){if(0===this.#r.size)return"";let e="\n<Styles>";for(const{id:t,style:r}of this.#r.values())e+=S(t,r);return e+="\n</Styles>",e}}function S(e,t){let r=`\n<Style ss:ID="${e}">`;if(t.font&&(r+="<Font",t.font.name&&(r+=` ss:FontName="${t.font.name}"`),t.font.size&&(r+=` ss:Size="${t.font.size}"`),t.font.bold&&(r+=' ss:Bold="1"'),t.font.italic&&(r+=' ss:Italic="1"'),t.font.color&&(r+=` ss:Color="${t.font.color}"`),r+="/>"),t.fill){const e=t.fill.pattern??"Solid";r+=`<Interior ss:Color="${t.fill.color}" ss:Pattern="${e}"/>`}return t.numberFormat&&(r+=`<NumberFormat ss:Format="${t.numberFormat}"/>`),t.alignment&&(r+="<Alignment",t.alignment.horizontal&&(r+=` ss:Horizontal="${t.alignment.horizontal}"`),t.alignment.vertical&&(r+=` ss:Vertical="${t.alignment.vertical}"`),t.alignment.wrapText&&(r+=' ss:WrapText="1"'),r+="/>"),t.borders&&(r+="<Borders>",t.borders.top&&(r+=v("Top",t.borders.top)),t.borders.bottom&&(r+=v("Bottom",t.borders.bottom)),t.borders.left&&(r+=v("Left",t.borders.left)),t.borders.right&&(r+=v("Right",t.borders.right)),r+="</Borders>"),r+="</Style>",r}function v(e,t){let r=`<Border ss:Position="${e}" ss:LineStyle="Continuous" ss:Weight="${function(e){switch(e){case"Thin":return 1;case"Medium":return 2;case"Thick":return 3}}(t.style)}"`;return t.color&&(r+=` ss:Color="${t.color}"`),r+="/>",r}function x(e,t,r,s,o){if(t.cellStyle){const n=t.cellStyle(r,s,o);if(n)return e.register(n)}const n=t.columnStyles?.[s];return n?e.getStyleId(n):t.defaultStyle?e.getStyleId(t.defaultStyle):void 0}function C(e,t){const r=Math.min(t.length,50);let s=(e.header??e.field).length;for(let o=0;o<r;o++){const r=t[o][e.field],n=null==r?0:String(r).length;n>s&&(s=n)}return s+2}function E(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function R(e,r,s){const o=s.excelStyles,n=o?function(e){const t=new w;if(e.headerStyle&&t.register(e.headerStyle),e.groupHeaderStyle&&t.register(e.groupHeaderStyle),e.defaultStyle&&t.register(e.defaultStyle),e.columnStyles)for(const r of Object.values(e.columnStyles))t.register(r);return t}(o):void 0;let i='<?xml version="1.0" encoding="UTF-8"?>\n<?mso-application progid="Excel.Sheet"?>\n<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"\n xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">';if(n){if(o.cellStyle)for(const s of e)for(const e of r){const r=t(s,e),i=o.cellStyle(r,e.field,s);i&&n.register(i)}i+=n.toXml()}i+='\n<Worksheet ss:Name="Sheet1">\n<Table>',o&&(i+=function(e,t,r){const s=r.columnWidths,o=r.autoFitColumns;if(!s&&!o)return"";let n="";for(const i of e){let e=s?.[i.field];null==e&&o&&(e=C(i,t)),n+=null!=e?`\n<Column ss:Width="${7*e}"/>`:"\n<Column/>"}return n}(r,e,o));const l=o?.headerStyle&&n?n.getStyleId(o.headerStyle):void 0,a=o?.groupHeaderStyle&&n?n.getStyleId(o.groupHeaderStyle):l;if(!1!==s.includeHeaders&&s.headerRows&&s.headerRows.length>0){const e=a?` ss:StyleID="${a}"`:"";for(const t of s.headerRows){i+="\n<Row>";for(const r of t.cells){const t=Math.max(1,0|r.span);i+=`<Cell${e}${t>1?` ss:MergeAcross="${t-1}"`:""}><Data ss:Type="String">${E(r.label??"")}</Data></Cell>`}i+="</Row>"}}if(!1!==s.includeHeaders){i+="\n<Row>";for(const e of r){const t=e.header||e.field;i+=`<Cell${l?` ss:StyleID="${l}"`:""}><Data ss:Type="String">${E(s.processHeader?s.processHeader(t,e.field):t)}</Data></Cell>`}i+="</Row>"}for(const c of e){i+="\n<Row>";for(const e of r){let r=t(c,e);s.processCell&&(r=s.processCell(r,e.field,c));let l="String",a="";null==r?a="":"number"!=typeof r||isNaN(r)?r instanceof Date?(l="DateTime",a=r.toISOString()):a=E(String(r)):(l="Number",a=String(r));const u=n&&o?x(n,o,r,e.field,c):void 0;i+=`<Cell${u?` ss:StyleID="${u}"`:""}><Data ss:Type="${l}">${a}</Data></Cell>`}i+="</Row>"}return i+="\n</Table>\n</Worksheet>\n</Workbook>",i}class $ extends f{static manifest={queries:[{type:"export:csv",description:"Triggers a CSV export"}]};name="export";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;handleQuery(e){if("export:csv"===e.type)return this.exportCsv(),!0}resolveExportData(e,t){const r=this.config,s={format:e,fileName:t?.fileName??r.fileName??"export",includeHeaders:t?.includeHeaders??r.includeHeaders,processCell:t?.processCell,processHeader:t?.processHeader,processHeaderRow:t?.processHeaderRow,mode:t?.mode??"raw",columns:t?.columns,rowIndices:t?.rowIndices,excelStyles:t?.excelStyles,fileExtension:t?.fileExtension,headerRows:t?.headerRows},o=d(this.columns,t?.columns,r.onlyVisible);let n;if(t?.rowIndices)n=h(this.rows,t.rowIndices);else if(r.onlySelected){const e=this.getSelectionState();n=e?.selected?.size?h(this.rows,[...e.selected]):[...this.rows]}else n=[...this.rows];if(!1===s.includeHeaders)s.headerRows=void 0;else{const e=s.headerRows??this.#o(o);s.headerRows=this.#n(e,o,s.processHeaderRow)}return{columns:o,rows:n,fullParams:s}}#o(e){if(0===e.length)return[];const t=this.grid;if(!t?.query)return[];const r=t.query("collectHeaderRows",{columns:e});if(!r||0===r.length)return[];const s=[];for(const o of r)if(o)if(Array.isArray(o))for(const e of o)e&&Array.isArray(e.cells)&&e.cells.length>0&&s.push(e);else Array.isArray(o.cells)&&o.cells.length>0&&s.push(o);return s}#n(e,t,r){if(!e||0===e.length)return;const s=t.length,o=[];for(let n=0;n<e.length;n++){const t=e[n];if(!t||!Array.isArray(t.cells)||0===t.cells.length)continue;const i=[];let l=!1,a=0,c=!1;for(const e of t.cells){const t=Math.max(1,0|e.span);if(a+t>s){c=!0;break}a+=t;const o=r?r(e,n):e;null===o?i.push({label:"",span:t}):(i.push({...o,span:t}),""!==(o.label??"")&&(l=!0))}c||(a<s&&i.push({label:"",span:s-a}),l&&o.push({cells:i}))}return o.length>0?o:void 0}resolveCellOutput(e,t,r,s,o){let n=e;if("formatted"===s){const s=this.#i(t);if(s)try{const t=s(e,r);n=null==t?"":String(t)}catch{n=null==e?"":String(e)}else n="date"===t.type?function(e){if(null==e||""===e)return"";if(e instanceof Date)return isNaN(e.getTime())?"":e.toLocaleDateString();if("number"==typeof e||"string"==typeof e){const t=new Date(e);return isNaN(t.getTime())?"":t.toLocaleDateString()}return""}(e):"boolean"===t.type?!!e:e}return o&&(n=o(n,t.field,r)),n}performExport(e,t){const{columns:r,rows:s,fullParams:o}=this.resolveExportData(e,t);this.isExportingFlag=!0;let n=o.fileName??"export";const i=this.#l(r);try{switch(e){case"csv":{const e=p(this.#a(s,r,o),i,{...o,processCell:void 0},{bom:!0});n=n.endsWith(".csv")?n:`${n}.csv`,function(e,t){m(new Blob([e],{type:"text/csv;charset=utf-8;"}),t)}(e,n);break}case"excel":{const e=R(this.#a(s,r,o),i,{...o,processCell:void 0}),t=o.fileExtension??".xls",l=t.startsWith(".")?t:`.${t}`;n=n.endsWith(l)?n:`${n}${l}`,function(e,t){m(new Blob([e],{type:"application/vnd.ms-excel;charset=utf-8;"}),t)}(e,n);break}case"json":{const e=this.#a(s,r,o),t=o.headerRows&&o.headerRows.length>0?{headerRows:o.headerRows,rows:e}:e,i=JSON.stringify(t,null,2);n=n.endsWith(".json")?n:`${n}.json`;m(new Blob([i],{type:"application/json"}),n);break}}this.lastExportInfo={format:e,timestamp:/* @__PURE__ */new Date},this.emit("export-complete",{format:e,fileName:n,rowCount:s.length,columnCount:r.length})}finally{this.isExportingFlag=!1}}#a(e,r,s){const o=s.mode??"raw";return e.map(e=>{const n={};for(const i of r){const r=t(e,i);n[i.field]=this.resolveCellOutput(r,i,e,o,s.processCell)}return n})}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}export(e){const{columns:t,rows:r,fullParams:s}=this.resolveExportData("json",e);return this.#a(r,t,s)}getResolvedColumns(e){return d(this.columns,e?.columns,this.config.onlyVisible)}formatCsv(e,t,r){const{columns:s,fullParams:o}=this.resolveExportData("csv",t);return p(e,this.#l(s),o,r)}formatExcel(e,t){const{columns:r,fullParams:s}=this.resolveExportData("excel",t);return R(e,this.#l(r),s)}#l(e){return e.map(e=>e.valueAccessor?{...e,valueAccessor:void 0}:e)}#i(e){if(e.format)return e.format;if(!e.type)return;const t=this.grid,r=t?.__frameworkAdapter;if(!r?.getTypeDefault)return;const s=r.getTypeDefault(e.type,t?._hostElement);return s?.format}exportCsv(e){this.performExport("csv",e)}exportExcel(e){this.performExport("excel",e)}exportJson(e){this.performExport("json",e)}isExporting(){return this.isExportingFlag}getLastExport(){return this.lastExportInfo}}export{$ as ExportPlugin};
1
+ const e=/* @__PURE__ */new WeakMap;function t(t,r,s=-1){if(!r.valueAccessor)return t?.[r.field];if("object"!=typeof t||null===t)return r.valueAccessor({row:t,column:r,rowIndex:s});const o=t,n=r.field;let i=e.get(o);if(i){const e=i.get(n);if(void 0!==e)return e.v}else i=/* @__PURE__ */new Map,e.set(o,i);const l=r.valueAccessor({row:t,column:r,rowIndex:s});return i.set(n,{v:l}),l}function r(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function s(e,t,s,o){return`${r(s,o)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}const o="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join(""));new RegExp(`__(proto|defineGetter|defineSetter)|${o.slice(3).join("|")}|this\\b`);const n=new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing".split("|")),i=/^on\w+$/i,l=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),a=/^\s*(javascript|vbscript|data|blob):/i;function c(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],r=e.querySelectorAll("*");for(const s of r){const e=s.tagName.toLowerCase();if(n.has(e)){t.push(s);continue}if("svg"===e||"http://www.w3.org/2000/svg"===s.namespaceURI){if(Array.from(s.attributes).some(e=>i.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(s);continue}}const r=[];for(const t of s.attributes){const e=t.name.toLowerCase();i.test(e)?r.push(t.name):(l.has(e)&&a.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&r.push(t.name)}r.forEach(e=>s.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}const u={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class f{static dependencies;static manifest;aliases;version="2.17.2";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},r={};for(const s of Object.keys(t))r[s]=this;for(const o of e){const e=o.userConfig;for(const[n,i]of Object.entries(e)){if(void 0===i)continue;if(!(n in t)){t[n]=i,r[n]=o;continue}if(t[n]===i)continue;const e=r[n]?.constructor.name??this.constructor.name,l=o.constructor.name,a=s("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${n}" supplied by both ${e} and ${l}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(a)}}Object.assign(this.userConfig,t)}refreshUserConfigFrom(e){const t=this.userConfig;for(const r of Object.keys(t))delete t[r];Object.assign(t,e.userConfig)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const r=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(r),r.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...u,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),r=parseInt(t,10);if(!isNaN(r))return r}return 200}setIcon(e,t,r){e.dataset.icon=t.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const s=this.#t(t,r);void 0!==s?"string"==typeof s?e.innerHTML=c(s):s instanceof HTMLElement&&(e.innerHTML="",e.appendChild(s.cloneNode(!0))):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const r=document.createElement("span");r.setAttribute("part","sort-indicator"),r.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(r,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(r,"sortNone"));const s=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return s?e.insertBefore(r,s):e.appendChild(r),r}warn(e,t){void 0!==t?console.warn(s(e,t,this.gridElement.id,this.name)):console.warn(`${r(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(s(e,t,this.gridElement.id,this.name))}}function d(e,t,r=!0){let s=e;if(r&&(s=s.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.utility)),t?.length){const e=new Set(t);s=s.filter(t=>e.has(t.field))}return s}function h(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}function g(e,t=!0){return"string"==typeof e?t&&(e.includes(",")||e.includes('"')||e.includes("\n")||e.includes("\r"))?`"${e.replace(/"/g,'""')}"`:e:"number"==typeof e?String(e):"boolean"==typeof e?e?"true":"false":null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}function p(e,r,s,o={}){const n=o.delimiter??",",i=o.newline??"\n",l=o.quoteStrings??!0,a=[],c=o.bom?"\ufeff":"";if(!1!==s.includeHeaders){const e=r.map(e=>{const t=e.header||e.field;return g(s.processHeader?s.processHeader(t,e.field):t,l)});a.push(e.join(n))}for(const u of e){const e=r.map(e=>{let r=t(u,e);return s.processCell&&(r=s.processCell(r,e.field,u)),g(r,l)});a.push(e.join(n))}return c+a.join(i)}function m(e,t){const r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.style.display="none",document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(r)}function b(e){return JSON.stringify(y(e))}function y(e){if(null==e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(y);const t={};for(const r of Object.keys(e).sort())t[r]=y(e[r]);return t}class w{#r=/* @__PURE__ */new Map;#s=0;register(e){const t=b(e),r=this.#r.get(t);if(r)return r.id;this.#s++;const s=`s${this.#s}`;return this.#r.set(t,{id:s,style:e}),s}getStyleId(e){return this.#r.get(b(e))?.id}get size(){return this.#r.size}toXml(){if(0===this.#r.size)return"";let e="\n<Styles>";for(const{id:t,style:r}of this.#r.values())e+=S(t,r);return e+="\n</Styles>",e}}function S(e,t){let r=`\n<Style ss:ID="${e}">`;if(t.font&&(r+="<Font",t.font.name&&(r+=` ss:FontName="${t.font.name}"`),t.font.size&&(r+=` ss:Size="${t.font.size}"`),t.font.bold&&(r+=' ss:Bold="1"'),t.font.italic&&(r+=' ss:Italic="1"'),t.font.color&&(r+=` ss:Color="${t.font.color}"`),r+="/>"),t.fill){const e=t.fill.pattern??"Solid";r+=`<Interior ss:Color="${t.fill.color}" ss:Pattern="${e}"/>`}return t.numberFormat&&(r+=`<NumberFormat ss:Format="${t.numberFormat}"/>`),t.alignment&&(r+="<Alignment",t.alignment.horizontal&&(r+=` ss:Horizontal="${t.alignment.horizontal}"`),t.alignment.vertical&&(r+=` ss:Vertical="${t.alignment.vertical}"`),t.alignment.wrapText&&(r+=' ss:WrapText="1"'),r+="/>"),t.borders&&(r+="<Borders>",t.borders.top&&(r+=v("Top",t.borders.top)),t.borders.bottom&&(r+=v("Bottom",t.borders.bottom)),t.borders.left&&(r+=v("Left",t.borders.left)),t.borders.right&&(r+=v("Right",t.borders.right)),r+="</Borders>"),r+="</Style>",r}function v(e,t){let r=`<Border ss:Position="${e}" ss:LineStyle="Continuous" ss:Weight="${function(e){switch(e){case"Thin":return 1;case"Medium":return 2;case"Thick":return 3}}(t.style)}"`;return t.color&&(r+=` ss:Color="${t.color}"`),r+="/>",r}function x(e,t,r,s,o){if(t.cellStyle){const n=t.cellStyle(r,s,o);if(n)return e.register(n)}const n=t.columnStyles?.[s];return n?e.getStyleId(n):t.defaultStyle?e.getStyleId(t.defaultStyle):void 0}function C(e,t){const r=Math.min(t.length,50);let s=(e.header??e.field).length;for(let o=0;o<r;o++){const r=t[o][e.field],n=null==r?0:String(r).length;n>s&&(s=n)}return s+2}function E(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function R(e,r,s){const o=s.excelStyles,n=o?function(e){const t=new w;if(e.headerStyle&&t.register(e.headerStyle),e.groupHeaderStyle&&t.register(e.groupHeaderStyle),e.defaultStyle&&t.register(e.defaultStyle),e.columnStyles)for(const r of Object.values(e.columnStyles))t.register(r);return t}(o):void 0;let i='<?xml version="1.0" encoding="UTF-8"?>\n<?mso-application progid="Excel.Sheet"?>\n<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"\n xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">';if(n){if(o.cellStyle)for(const s of e)for(const e of r){const r=t(s,e),i=o.cellStyle(r,e.field,s);i&&n.register(i)}i+=n.toXml()}i+='\n<Worksheet ss:Name="Sheet1">\n<Table>',o&&(i+=function(e,t,r){const s=r.columnWidths,o=r.autoFitColumns;if(!s&&!o)return"";let n="";for(const i of e){let e=s?.[i.field];null==e&&o&&(e=C(i,t)),n+=null!=e?`\n<Column ss:Width="${7*e}"/>`:"\n<Column/>"}return n}(r,e,o));const l=o?.headerStyle&&n?n.getStyleId(o.headerStyle):void 0,a=o?.groupHeaderStyle&&n?n.getStyleId(o.groupHeaderStyle):l;if(!1!==s.includeHeaders&&s.headerRows&&s.headerRows.length>0){const e=a?` ss:StyleID="${a}"`:"";for(const t of s.headerRows){i+="\n<Row>";for(const r of t.cells){const t=Math.max(1,0|r.span);i+=`<Cell${e}${t>1?` ss:MergeAcross="${t-1}"`:""}><Data ss:Type="String">${E(r.label??"")}</Data></Cell>`}i+="</Row>"}}if(!1!==s.includeHeaders){i+="\n<Row>";for(const e of r){const t=e.header||e.field;i+=`<Cell${l?` ss:StyleID="${l}"`:""}><Data ss:Type="String">${E(s.processHeader?s.processHeader(t,e.field):t)}</Data></Cell>`}i+="</Row>"}for(const c of e){i+="\n<Row>";for(const e of r){let r=t(c,e);s.processCell&&(r=s.processCell(r,e.field,c));let l="String",a="";null==r?a="":"number"!=typeof r||isNaN(r)?r instanceof Date?(l="DateTime",a=r.toISOString()):a=E(String(r)):(l="Number",a=String(r));const u=n&&o?x(n,o,r,e.field,c):void 0;i+=`<Cell${u?` ss:StyleID="${u}"`:""}><Data ss:Type="${l}">${a}</Data></Cell>`}i+="</Row>"}return i+="\n</Table>\n</Worksheet>\n</Workbook>",i}class $ extends f{static manifest={queries:[{type:"export:csv",description:"Triggers a CSV export"}]};name="export";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;handleQuery(e){if("export:csv"===e.type)return this.exportCsv(),!0}resolveExportData(e,t){const r=this.config,s={format:e,fileName:t?.fileName??r.fileName??"export",includeHeaders:t?.includeHeaders??r.includeHeaders,processCell:t?.processCell,processHeader:t?.processHeader,processHeaderRow:t?.processHeaderRow,mode:t?.mode??"raw",columns:t?.columns,rowIndices:t?.rowIndices,excelStyles:t?.excelStyles,fileExtension:t?.fileExtension,headerRows:t?.headerRows},o=d(this.columns,t?.columns,r.onlyVisible);let n;if(t?.rowIndices)n=h(this.rows,t.rowIndices);else if(r.onlySelected){const e=this.getSelectionState();n=e?.selected?.size?h(this.rows,[...e.selected]):[...this.rows]}else n=[...this.rows];if(!1===s.includeHeaders)s.headerRows=void 0;else{const e=s.headerRows??this.#o(o);s.headerRows=this.#n(e,o,s.processHeaderRow)}return{columns:o,rows:n,fullParams:s}}#o(e){if(0===e.length)return[];const t=this.grid;if(!t?.query)return[];const r=t.query("collectHeaderRows",{columns:e});if(!r||0===r.length)return[];const s=[];for(const o of r)if(o)if(Array.isArray(o))for(const e of o)e&&Array.isArray(e.cells)&&e.cells.length>0&&s.push(e);else Array.isArray(o.cells)&&o.cells.length>0&&s.push(o);return s}#n(e,t,r){if(!e||0===e.length)return;const s=t.length,o=[];for(let n=0;n<e.length;n++){const t=e[n];if(!t||!Array.isArray(t.cells)||0===t.cells.length)continue;const i=[];let l=!1,a=0,c=!1;for(const e of t.cells){const t=Math.max(1,0|e.span);if(a+t>s){c=!0;break}a+=t;const o=r?r(e,n):e;null===o?i.push({label:"",span:t}):(i.push({...o,span:t}),""!==(o.label??"")&&(l=!0))}c||(a<s&&i.push({label:"",span:s-a}),l&&o.push({cells:i}))}return o.length>0?o:void 0}resolveCellOutput(e,t,r,s,o){let n=e;if("formatted"===s){const s=this.#i(t);if(s)try{const t=s(e,r);n=null==t?"":String(t)}catch{n=null==e?"":String(e)}else n="date"===t.type?function(e){if(null==e||""===e)return"";if(e instanceof Date)return isNaN(e.getTime())?"":e.toLocaleDateString();if("number"==typeof e||"string"==typeof e){const t=new Date(e);return isNaN(t.getTime())?"":t.toLocaleDateString()}return""}(e):"boolean"===t.type?!!e:e}return o&&(n=o(n,t.field,r)),n}performExport(e,t){const{columns:r,rows:s,fullParams:o}=this.resolveExportData(e,t);this.isExportingFlag=!0;let n=o.fileName??"export";const i=this.#l(r);try{switch(e){case"csv":{const e=p(this.#a(s,r,o),i,{...o,processCell:void 0},{bom:!0});n=n.endsWith(".csv")?n:`${n}.csv`,function(e,t){m(new Blob([e],{type:"text/csv;charset=utf-8;"}),t)}(e,n);break}case"excel":{const e=R(this.#a(s,r,o),i,{...o,processCell:void 0}),t=o.fileExtension??".xls",l=t.startsWith(".")?t:`.${t}`;n=n.endsWith(l)?n:`${n}${l}`,function(e,t){m(new Blob([e],{type:"application/vnd.ms-excel;charset=utf-8;"}),t)}(e,n);break}case"json":{const e=this.#a(s,r,o),t=o.headerRows&&o.headerRows.length>0?{headerRows:o.headerRows,rows:e}:e,i=JSON.stringify(t,null,2);n=n.endsWith(".json")?n:`${n}.json`;m(new Blob([i],{type:"application/json"}),n);break}}this.lastExportInfo={format:e,timestamp:/* @__PURE__ */new Date},this.emit("export-complete",{format:e,fileName:n,rowCount:s.length,columnCount:r.length})}finally{this.isExportingFlag=!1}}#a(e,r,s){const o=s.mode??"raw";return e.map(e=>{const n={};for(const i of r){const r=t(e,i);n[i.field]=this.resolveCellOutput(r,i,e,o,s.processCell)}return n})}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}export(e){const{columns:t,rows:r,fullParams:s}=this.resolveExportData("json",e);return this.#a(r,t,s)}getResolvedColumns(e){return d(this.columns,e?.columns,this.config.onlyVisible)}formatCsv(e,t,r){const{columns:s,fullParams:o}=this.resolveExportData("csv",t);return p(e,this.#l(s),o,r)}formatExcel(e,t){const{columns:r,fullParams:s}=this.resolveExportData("excel",t);return R(e,this.#l(r),s)}#l(e){return e.map(e=>e.valueAccessor?{...e,valueAccessor:void 0}:e)}#i(e){if(e.format)return e.format;if(!e.type)return;const t=this.grid,r=t?.__frameworkAdapter;if(!r?.getTypeDefault)return;const s=r.getTypeDefault(e.type,t?._hostElement);return s?.format}exportCsv(e){this.performExport("csv",e)}exportExcel(e){this.performExport("excel",e)}exportJson(e){this.performExport("json",e)}isExporting(){return this.isExportingFlag}getLastExport(){return this.lastExportInfo}}export{$ as ExportPlugin};
2
2
  //# sourceMappingURL=index.js.map