@toolbox-web/grid 1.6.2 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +51 -15
  2. package/all.js +267 -158
  3. package/all.js.map +1 -1
  4. package/index.js +866 -722
  5. package/index.js.map +1 -1
  6. package/lib/core/grid.d.ts +68 -1
  7. package/lib/core/grid.d.ts.map +1 -1
  8. package/lib/core/internal/header.d.ts.map +1 -1
  9. package/lib/core/plugin/base-plugin.d.ts +182 -1
  10. package/lib/core/plugin/base-plugin.d.ts.map +1 -1
  11. package/lib/core/plugin/index.d.ts +1 -1
  12. package/lib/core/plugin/index.d.ts.map +1 -1
  13. package/lib/core/plugin/plugin-manager.d.ts +56 -1
  14. package/lib/core/plugin/plugin-manager.d.ts.map +1 -1
  15. package/lib/core/plugin/types.d.ts +36 -0
  16. package/lib/core/plugin/types.d.ts.map +1 -1
  17. package/lib/core/types.d.ts +1349 -31
  18. package/lib/core/types.d.ts.map +1 -1
  19. package/lib/plugins/clipboard/ClipboardPlugin.d.ts.map +1 -1
  20. package/lib/plugins/clipboard/index.js +140 -87
  21. package/lib/plugins/clipboard/index.js.map +1 -1
  22. package/lib/plugins/column-virtualization/index.js +64 -7
  23. package/lib/plugins/column-virtualization/index.js.map +1 -1
  24. package/lib/plugins/context-menu/ContextMenuPlugin.d.ts.map +1 -1
  25. package/lib/plugins/context-menu/index.js +123 -65
  26. package/lib/plugins/context-menu/index.js.map +1 -1
  27. package/lib/plugins/editing/EditingPlugin.d.ts +6 -1
  28. package/lib/plugins/editing/EditingPlugin.d.ts.map +1 -1
  29. package/lib/plugins/editing/index.js +95 -13
  30. package/lib/plugins/editing/index.js.map +1 -1
  31. package/lib/plugins/export/index.js +91 -34
  32. package/lib/plugins/export/index.js.map +1 -1
  33. package/lib/plugins/filtering/FilteringPlugin.d.ts +6 -1
  34. package/lib/plugins/filtering/FilteringPlugin.d.ts.map +1 -1
  35. package/lib/plugins/filtering/index.js +192 -123
  36. package/lib/plugins/filtering/index.js.map +1 -1
  37. package/lib/plugins/grouping-columns/index.js +57 -0
  38. package/lib/plugins/grouping-columns/index.js.map +1 -1
  39. package/lib/plugins/grouping-rows/GroupingRowsPlugin.d.ts +7 -2
  40. package/lib/plugins/grouping-rows/GroupingRowsPlugin.d.ts.map +1 -1
  41. package/lib/plugins/grouping-rows/index.js +142 -60
  42. package/lib/plugins/grouping-rows/index.js.map +1 -1
  43. package/lib/plugins/master-detail/index.js +69 -12
  44. package/lib/plugins/master-detail/index.js.map +1 -1
  45. package/lib/plugins/multi-sort/index.js +70 -13
  46. package/lib/plugins/multi-sort/index.js.map +1 -1
  47. package/lib/plugins/pinned-columns/PinnedColumnsPlugin.d.ts +3 -3
  48. package/lib/plugins/pinned-columns/PinnedColumnsPlugin.d.ts.map +1 -1
  49. package/lib/plugins/pinned-columns/index.js +106 -36
  50. package/lib/plugins/pinned-columns/index.js.map +1 -1
  51. package/lib/plugins/pinned-rows/index.js +57 -0
  52. package/lib/plugins/pinned-rows/index.js.map +1 -1
  53. package/lib/plugins/pivot/index.js +57 -0
  54. package/lib/plugins/pivot/index.js.map +1 -1
  55. package/lib/plugins/print/PrintPlugin.d.ts.map +1 -1
  56. package/lib/plugins/print/index.js +58 -1
  57. package/lib/plugins/print/index.js.map +1 -1
  58. package/lib/plugins/reorder/ReorderPlugin.d.ts.map +1 -1
  59. package/lib/plugins/reorder/column-drag.d.ts +2 -2
  60. package/lib/plugins/reorder/index.js +68 -17
  61. package/lib/plugins/reorder/index.js.map +1 -1
  62. package/lib/plugins/responsive/ResponsivePlugin.d.ts +6 -1
  63. package/lib/plugins/responsive/ResponsivePlugin.d.ts.map +1 -1
  64. package/lib/plugins/responsive/index.js +125 -54
  65. package/lib/plugins/responsive/index.js.map +1 -1
  66. package/lib/plugins/row-reorder/index.js +169 -112
  67. package/lib/plugins/row-reorder/index.js.map +1 -1
  68. package/lib/plugins/selection/SelectionPlugin.d.ts +14 -2
  69. package/lib/plugins/selection/SelectionPlugin.d.ts.map +1 -1
  70. package/lib/plugins/selection/index.js +84 -7
  71. package/lib/plugins/selection/index.js.map +1 -1
  72. package/lib/plugins/server-side/index.js +79 -22
  73. package/lib/plugins/server-side/index.js.map +1 -1
  74. package/lib/plugins/tree/TreePlugin.d.ts +7 -1
  75. package/lib/plugins/tree/TreePlugin.d.ts.map +1 -1
  76. package/lib/plugins/tree/index.js +140 -58
  77. package/lib/plugins/tree/index.js.map +1 -1
  78. package/lib/plugins/undo-redo/UndoRedoPlugin.d.ts +6 -1
  79. package/lib/plugins/undo-redo/UndoRedoPlugin.d.ts.map +1 -1
  80. package/lib/plugins/undo-redo/index.js +79 -10
  81. package/lib/plugins/undo-redo/index.js.map +1 -1
  82. package/lib/plugins/visibility/index.js +57 -0
  83. package/lib/plugins/visibility/index.js.map +1 -1
  84. package/package.json +1 -1
  85. package/public.d.ts +80 -2
  86. package/public.d.ts.map +1 -1
  87. package/umd/grid.all.umd.js +25 -25
  88. package/umd/grid.all.umd.js.map +1 -1
  89. package/umd/grid.umd.js +15 -15
  90. package/umd/grid.umd.js.map +1 -1
  91. package/umd/plugins/clipboard.umd.js +5 -5
  92. package/umd/plugins/clipboard.umd.js.map +1 -1
  93. package/umd/plugins/context-menu.umd.js +1 -1
  94. package/umd/plugins/context-menu.umd.js.map +1 -1
  95. package/umd/plugins/editing.umd.js +1 -1
  96. package/umd/plugins/editing.umd.js.map +1 -1
  97. package/umd/plugins/filtering.umd.js +1 -1
  98. package/umd/plugins/filtering.umd.js.map +1 -1
  99. package/umd/plugins/grouping-rows.umd.js +2 -2
  100. package/umd/plugins/grouping-rows.umd.js.map +1 -1
  101. package/umd/plugins/pinned-columns.umd.js +1 -1
  102. package/umd/plugins/pinned-columns.umd.js.map +1 -1
  103. package/umd/plugins/print.umd.js +1 -1
  104. package/umd/plugins/print.umd.js.map +1 -1
  105. package/umd/plugins/reorder.umd.js +1 -1
  106. package/umd/plugins/reorder.umd.js.map +1 -1
  107. package/umd/plugins/responsive.umd.js +1 -1
  108. package/umd/plugins/responsive.umd.js.map +1 -1
  109. package/umd/plugins/selection.umd.js +2 -2
  110. package/umd/plugins/selection.umd.js.map +1 -1
  111. package/umd/plugins/tree.umd.js +1 -1
  112. package/umd/plugins/tree.umd.js.map +1 -1
  113. package/umd/plugins/undo-redo.umd.js +1 -1
  114. package/umd/plugins/undo-redo.umd.js.map +1 -1
@@ -1,7 +1,7 @@
1
- (function(w,y){typeof exports=="object"&&typeof module<"u"?y(exports,require("../../core/plugin/base-plugin"),require("../../core/plugin/expander-column")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/plugin/expander-column"],y):(w=typeof globalThis<"u"?globalThis:w||self,y(w.TbwGridPlugin_clipboard={},w.TbwGrid,w.TbwGrid))})(this,(function(w,y,S){"use strict";async function R(C){try{return await navigator.clipboard.writeText(C),!0}catch{const e=document.createElement("textarea");e.value=C,e.style.position="fixed",e.style.opacity="0",e.style.pointerEvents="none",document.body.appendChild(e),e.select();const n=document.execCommand("copy");return document.body.removeChild(e),n}}function b(C,e){const n=e.delimiter??" ",o=e.newline??`
2
- `,a=C.replace(/\r\n/g,`
1
+ (function(p,C){typeof exports=="object"&&typeof module<"u"?C(exports,require("../../core/plugin/base-plugin"),require("../../core/plugin/expander-column")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/plugin/expander-column"],C):(p=typeof globalThis<"u"?globalThis:p||self,C(p.TbwGridPlugin_clipboard={},p.TbwGrid,p.TbwGrid))})(this,(function(p,C,v){"use strict";async function y(m){try{return await navigator.clipboard.writeText(m),!0}catch{const t=document.createElement("textarea");t.value=m,t.style.position="fixed",t.style.opacity="0",t.style.pointerEvents="none",document.body.appendChild(t),t.select();const n=document.execCommand("copy");return document.body.removeChild(t),n}}function b(m,t){const n=t.delimiter??" ",r=t.newline??`
2
+ `,i=m.replace(/\r\n/g,`
3
3
  `).replace(/\r/g,`
4
- `),s=[];let t=[],i="",l=!1;for(let r=0;r<a.length;r++){const c=a[r];c==='"'&&!l?l=!0:c==='"'&&l?a[r+1]==='"'?(i+='"',r++):l=!1:c===n&&!l?(t.push(i),i=""):c===o&&!l?(t.push(i),i="",(t.length>1||t.some(u=>u.trim()!==""))&&s.push(t),t=[]):i+=c}return t.push(i),(t.length>1||t.some(r=>r.trim()!==""))&&s.push(t),s}async function T(){try{return await navigator.clipboard.readText()}catch{return""}}function P(C,e){const{rows:n,target:o,fields:a}=C;if(!o)return;const s=e.rows,t=e.effectiveConfig.columns??[],i=t.map(u=>u.field),l=new Map;t.forEach(u=>{l.set(u.field,u.editable===!0)});const r=[...s],c=o.bounds?o.bounds.endRow:1/0;n.forEach((u,g)=>{const f=o.row+g;if(!(f>c)){if(o.bounds){if(f>=r.length)return}else for(;f>=r.length;){const d={};i.forEach(h=>d[h]=""),r.push(d)}r[f]={...r[f]},u.forEach((d,h)=>{const p=a[h];p&&l.get(p)&&(r[f][p]=d)})}}),e.rows=r}class v extends y.BaseGridPlugin{static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:" ",newline:`
5
- `,quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e),e.addEventListener("paste",n=>this.#o(n),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(e){return(e.ctrlKey||e.metaKey)&&e.key==="c"?(this.#n(e.target),!0):!1}#n(e){const n=this.#t(),o=n?.getSelection(),a=this.columns.length-1,s=this.rows.length-1;let t;if(o&&o.ranges.length>0){const{mode:l,ranges:r}=o,c=r[r.length-1];l==="row"?t={startRow:c.from.row,startCol:0,endRow:c.to.row,endCol:a}:t={startRow:c.from.row,startCol:c.from.col,endRow:c.to.row,endCol:c.to.col}}else if(!n)t={startRow:0,startCol:0,endRow:s,endCol:a};else{const l=this.#l(e);if(!l)return;t={startRow:l.row,startCol:l.col,endRow:l.row,endCol:l.col}}const i=this.#e(t);R(i.text).then(()=>{this.lastCopied={text:i.text,timestamp:Date.now()},this.emit("copy",{text:i.text,rowCount:i.rowCount,columnCount:i.columnCount})})}#o(e){const n=e.clipboardData?.getData("text/plain");if(!n)return;e.preventDefault();const o=b(n,this.config),s=this.#t()?.getSelection(),t=s?.ranges?.[0],i=t?.from.row??0,l=t?.from.col??0,c=t&&(s?.mode==="range"||s?.mode==="row")&&(t.from.row!==t.to.row||t.from.col!==t.to.col)?{endRow:t.to.row,endCol:t.to.col}:null,u=c?.endCol??this.columns.length-1,g=this.columns[l],f=g?{row:i,col:l,field:g.field,bounds:c}:null,d=[],h=o[0]?.length??0;for(let x=0;x<h&&l+x<=u;x++){const m=this.columns[l+x];m&&!m.hidden&&d.push(m.field)}const p={rows:o,text:n,target:f,fields:d};this.emit("paste",p),this.#s(p)}#s(e){if(!this.grid)return;const{pasteHandler:n}=this.config;if(n===null)return;(n??P)(e,this.grid)}#t(){try{const e=this.grid?.getPluginByName("selection");if(e)return e}catch{}}#e(e){const{startRow:n,startCol:o,endRow:a,endCol:s}=e,t=Math.min(n,a),i=Math.max(n,a),l=Math.min(o,s),r=Math.max(o,s),c=this.config.delimiter??" ",u=this.config.newline??`
6
- `,g=[],f=this.columns.slice(l,r+1).filter(d=>!S.isUtilityColumn(d));if(this.config.includeHeaders){const d=f.map(h=>h.header||h.field);g.push(d.join(c))}for(let d=t;d<=i;d++){const h=this.rows[d];if(!h)continue;const p=f.map(x=>{const m=h[x.field];return m==null?"":m instanceof Date?m.toISOString():String(m)});g.push(p.join(c))}return{text:g.join(u),rowCount:i-t+1,columnCount:r-l+1}}#l(e){const n=e.closest("[data-field-cache]");if(!n)return null;const o=n.dataset.fieldCache,a=n.dataset.row;if(!o||!a)return null;const s=parseInt(a,10);if(isNaN(s))return null;const t=this.columns.findIndex(i=>i.field===o);return t===-1?null:{row:s,col:t}}async copy(){const n=this.#t()?.getSelection(),o=this.columns.length-1;let a={startRow:0,startCol:0,endRow:this.rows.length-1,endCol:o};if(n&&n.ranges.length>0){const t=n.ranges[n.ranges.length-1];n.mode==="row"?a={startRow:t.from.row,startCol:0,endRow:t.to.row,endCol:o}:a={startRow:t.from.row,startCol:t.from.col,endRow:t.to.row,endCol:t.to.col}}const s=this.#e(a);return await R(s.text),this.lastCopied={text:s.text,timestamp:Date.now()},s.text}async copyRows(e){if(e.length===0)return"";const n=[...e].sort((t,i)=>t-i),o=this.columns.length-1,a={startRow:n[0],startCol:0,endRow:n[n.length-1],endCol:o},s=this.#e(a);return await R(s.text),this.lastCopied={text:s.text,timestamp:Date.now()},s.text}async paste(){const e=await T();return e?b(e,this.config):null}getLastCopied(){return this.lastCopied}}w.ClipboardPlugin=v,w.defaultPasteHandler=P,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})}));
4
+ `),e=[];let o=[],s="",a=!1;for(let l=0;l<i.length;l++){const u=i[l];u==='"'&&!a?a=!0:u==='"'&&a?i[l+1]==='"'?(s+='"',l++):a=!1:u===n&&!a?(o.push(s),s=""):u===r&&!a?(o.push(s),s="",(o.length>1||o.some(d=>d.trim()!==""))&&e.push(o),o=[]):s+=u}return o.push(s),(o.length>1||o.some(l=>l.trim()!==""))&&e.push(o),e}async function D(){try{return await navigator.clipboard.readText()}catch{return""}}function T(m,t){const{rows:n,target:r,fields:i}=m;if(!r)return;const e=t.rows,o=t.effectiveConfig.columns??[],s=o.map(d=>d.field),a=new Map;o.forEach(d=>{a.set(d.field,d.editable===!0)});const l=[...e],u=r.bounds?r.bounds.endRow:1/0;n.forEach((d,g)=>{const f=r.row+g;if(!(f>u)){if(r.bounds){if(f>=l.length)return}else for(;f>=l.length;){const c={};s.forEach(h=>c[h]=""),l.push(c)}l[f]={...l[f]},d.forEach((c,h)=>{const w=i[h];w&&a.get(w)&&(l[f][w]=c)})}}),t.rows=l}class M extends C.BaseGridPlugin{static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:" ",newline:`
5
+ `,quoteStrings:!1}}lastCopied=null;attach(t){super.attach(t),t.addEventListener("paste",n=>this.#o(n),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(t){return(t.ctrlKey||t.metaKey)&&t.key==="c"?(this.#n(t.target),!0):!1}#n(t){const n=this.#t(),r=this.columns.length-1,i=this.rows.length-1;let e;if(n&&n.ranges.length>0){const{mode:s,ranges:a}=n,l=a[a.length-1];s==="row"?e={startRow:l.from.row,startCol:0,endRow:l.to.row,endCol:r}:e={startRow:l.from.row,startCol:l.from.col,endRow:l.to.row,endCol:l.to.col}}else if(!n)e={startRow:0,startCol:0,endRow:i,endCol:r};else{const s=this.#l(t);if(!s)return;e={startRow:s.row,startCol:s.col,endRow:s.row,endCol:s.col}}const o=this.#e(e);y(o.text).then(()=>{this.lastCopied={text:o.text,timestamp:Date.now()},this.emit("copy",{text:o.text,rowCount:o.rowCount,columnCount:o.columnCount})})}#o(t){const n=t.clipboardData?.getData("text/plain");if(!n)return;t.preventDefault();const r=b(n,this.config),i=this.#t(),e=i?.ranges?.[0],o=e?.from.row??0,s=e?.from.col??0,l=e&&(i?.mode==="range"||i?.mode==="row")&&(e.from.row!==e.to.row||e.from.col!==e.to.col)?{endRow:e.to.row,endCol:e.to.col}:null,u=l?.endCol??this.columns.length-1,d=this.columns[s],g=d?{row:o,col:s,field:d.field,bounds:l}:null,f=[],c=r[0]?.length??0;for(let w=0;w<c&&s+w<=u;w++){const x=this.columns[s+w];x&&!x.hidden&&f.push(x.field)}const h={rows:r,text:n,target:g,fields:f};this.emit("paste",h),this.#s(h)}#s(t){if(!this.grid)return;const{pasteHandler:n}=this.config;if(n===null)return;(n??T)(t,this.grid)}#t(){return this.grid?.query("getSelection",void 0)?.[0]}#e(t){const{startRow:n,startCol:r,endRow:i,endCol:e}=t,o=Math.min(n,i),s=Math.max(n,i),a=Math.min(r,e),l=Math.max(r,e),u=this.config.delimiter??" ",d=this.config.newline??`
6
+ `,g=[],f=this.columns.slice(a,l+1).filter(c=>!v.isUtilityColumn(c));if(this.config.includeHeaders){const c=f.map(h=>h.header||h.field);g.push(c.join(u))}for(let c=o;c<=s;c++){const h=this.rows[c];if(!h)continue;const w=f.map(x=>{const R=h[x.field];return R==null?"":R instanceof Date?R.toISOString():String(R)});g.push(w.join(u))}return{text:g.join(d),rowCount:s-o+1,columnCount:l-a+1}}#l(t){const n=t.closest("[data-field-cache]");if(!n)return null;const r=n.dataset.fieldCache,i=n.dataset.row;if(!r||!i)return null;const e=parseInt(i,10);if(isNaN(e))return null;const o=this.columns.findIndex(s=>s.field===r);return o===-1?null:{row:e,col:o}}async copy(){const t=this.#t(),n=this.columns.length-1;let r={startRow:0,startCol:0,endRow:this.rows.length-1,endCol:n};if(t&&t.ranges.length>0){const e=t.ranges[t.ranges.length-1];t.mode==="row"?r={startRow:e.from.row,startCol:0,endRow:e.to.row,endCol:n}:r={startRow:e.from.row,startCol:e.from.col,endRow:e.to.row,endCol:e.to.col}}const i=this.#e(r);return await y(i.text),this.lastCopied={text:i.text,timestamp:Date.now()},i.text}async copyRows(t){if(t.length===0)return"";const n=[...t].sort((o,s)=>o-s),r=this.columns.length-1,i={startRow:n[0],startCol:0,endRow:n[n.length-1],endCol:r},e=this.#e(i);return await y(e.text),this.lastCopied={text:e.text,timestamp:Date.now()},e.text}async paste(){const t=await D();return t?b(t,this.config):null}getLastCopied(){return this.lastCopied}}p.ClipboardPlugin=M,p.defaultPasteHandler=T,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})}));
7
7
  //# sourceMappingURL=clipboard.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts","../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../libs/grid/src/lib/plugins/clipboard/ClipboardPlugin.ts"],"sourcesContent":["/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { ClipboardConfig } from './types';\n\n/** Parameters for building clipboard text */\nexport interface CopyParams {\n /** All grid rows */\n rows: unknown[];\n /** Column configurations */\n columns: ColumnConfig[];\n /** Selected row indices */\n selectedIndices: Set<number> | number[];\n /** Clipboard configuration */\n config: ClipboardConfig;\n}\n\n/**\n * Format a cell value for clipboard output.\n *\n * Uses custom processCell if provided, otherwise applies default formatting:\n * - null/undefined → empty string\n * - Date → ISO string\n * - Object → JSON string\n * - Other → String conversion with optional quoting\n *\n * @param value - The cell value to format\n * @param field - The field name\n * @param row - The full row object\n * @param config - Clipboard configuration\n * @returns Formatted string value\n */\nexport function formatCellValue(value: unknown, field: string, row: unknown, config: ClipboardConfig): string {\n if (config.processCell) {\n return config.processCell(value, field, row);\n }\n\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n\n const str = String(value);\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Quote if contains delimiter, newline, or quotes (or if quoteStrings is enabled)\n if (config.quoteStrings || str.includes(delimiter) || str.includes(newline) || str.includes('\"')) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build clipboard text from selected rows and columns.\n *\n * @param params - Copy parameters including rows, columns, selection, and config\n * @returns Tab-separated (or custom delimiter) text ready for clipboard\n */\nexport function buildClipboardText(params: CopyParams): string {\n const { rows, columns, selectedIndices, config } = params;\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Filter to visible columns (not hidden, not internal __ prefixed)\n const visibleColumns = columns.filter((c) => !c.hidden && !c.field.startsWith('__'));\n\n const lines: string[] = [];\n\n // Add header row if configured\n if (config.includeHeaders) {\n const headerCells = visibleColumns.map((c) => {\n const header = c.header || c.field;\n // Quote headers if they contain special characters\n if (header.includes(delimiter) || header.includes(newline) || header.includes('\"')) {\n return `\"${header.replace(/\"/g, '\"\"')}\"`;\n }\n return header;\n });\n lines.push(headerCells.join(delimiter));\n }\n\n // Convert indices to sorted array\n const indices = selectedIndices instanceof Set ? [...selectedIndices] : selectedIndices;\n const sortedIndices = [...indices].sort((a, b) => a - b);\n\n // Build data rows\n for (const idx of sortedIndices) {\n const row = rows[idx];\n if (!row) continue;\n\n const cells = visibleColumns.map((col) =>\n formatCellValue((row as Record<string, unknown>)[col.field], col.field, row, config)\n );\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n}\n\n/**\n * Copy text to the system clipboard.\n *\n * Uses the modern Clipboard API when available, with fallback\n * to execCommand for older browsers.\n *\n * @param text - The text to copy\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n // Fallback for older browsers or when Clipboard API is not available\n const textarea = document.createElement('textarea');\n textarea.value = text;\n textarea.style.position = 'fixed';\n textarea.style.opacity = '0';\n textarea.style.pointerEvents = 'none';\n document.body.appendChild(textarea);\n textarea.select();\n const success = document.execCommand('copy');\n document.body.removeChild(textarea);\n return success;\n }\n}\n","/**\n * Clipboard Paste Logic\n *\n * Pure functions for reading and parsing clipboard data.\n */\n\nimport type { ClipboardConfig } from './types';\n\n/**\n * Parse clipboard text into a 2D array of cell values.\n *\n * Handles:\n * - Quoted values (with escaped double quotes \"\")\n * - Multi-line quoted values (newlines within quotes are preserved)\n * - Custom delimiters and newlines\n * - Empty lines (filtered out only if they contain no data)\n *\n * @param text - Raw clipboard text\n * @param config - Clipboard configuration\n * @returns 2D array where each sub-array is a row of cell values\n */\nexport function parseClipboardText(text: string, config: ClipboardConfig): string[][] {\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Handle Windows CRLF line endings\n const normalizedText = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n // Parse the entire text handling quoted fields that may span multiple lines\n const rows: string[][] = [];\n let currentRow: string[] = [];\n let currentCell = '';\n let inQuotes = false;\n\n for (let i = 0; i < normalizedText.length; i++) {\n const char = normalizedText[i];\n\n if (char === '\"' && !inQuotes) {\n // Start of quoted field\n inQuotes = true;\n } else if (char === '\"' && inQuotes) {\n // Check for escaped quote (\"\")\n if (normalizedText[i + 1] === '\"') {\n currentCell += '\"';\n i++; // Skip the second quote\n } else {\n // End of quoted field\n inQuotes = false;\n }\n } else if (char === delimiter && !inQuotes) {\n // Field separator\n currentRow.push(currentCell);\n currentCell = '';\n } else if (char === newline && !inQuotes) {\n // Row separator (only if not inside quotes)\n currentRow.push(currentCell);\n currentCell = '';\n // Only add non-empty rows (at least one non-empty cell or multiple cells)\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n currentRow = [];\n } else {\n currentCell += char;\n }\n }\n\n // Handle the last cell and row\n currentRow.push(currentCell);\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n\n return rows;\n}\n\n/**\n * Read text from the system clipboard.\n *\n * Uses the modern Clipboard API. Returns empty string if\n * the API is not available or permission is denied.\n *\n * @returns Promise resolving to clipboard text or empty string\n */\nexport async function readFromClipboard(): Promise<string> {\n try {\n return await navigator.clipboard.readText();\n } catch {\n // Permission denied or API not available\n return '';\n }\n}\n","/**\n * Clipboard Plugin Types\n *\n * Type definitions for clipboard copy/paste functionality.\n */\n\nimport type { GridElement } from '../../core/plugin/base-plugin';\n\n/**\n * Custom paste handler function.\n *\n * @param detail - The parsed paste data with target and field info\n * @param grid - The grid element to update\n * @returns `false` to prevent the default paste behavior, or `void`/`true` to allow it\n *\n * @example\n * ```ts\n * // Custom handler that validates before pasting\n * new ClipboardPlugin({\n * pasteHandler: (detail, grid) => {\n * if (!detail.target) return false;\n * // Apply custom validation/transformation...\n * applyPasteData(detail, grid);\n * return false; // We handled it, skip default\n * }\n * })\n * ```\n */\nexport type PasteHandler = (detail: PasteDetail, grid: GridElement) => boolean | void;\n\n/** Configuration options for the clipboard plugin */\nexport interface ClipboardConfig {\n /** Include column headers in copied text (default: false) */\n includeHeaders?: boolean;\n /** Column delimiter character (default: '\\t' for tab) */\n delimiter?: string;\n /** Row delimiter/newline character (default: '\\n') */\n newline?: string;\n /** Wrap string values with quotes (default: false) */\n quoteStrings?: boolean;\n /** Custom cell value processor for copy operations */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n /**\n * Custom paste handler. By default, the plugin applies pasted data to `grid.rows`\n * starting at the target cell.\n *\n * - Set to a custom function to handle paste yourself\n * - Set to `null` to disable auto-paste (event still fires)\n * - Return `false` from handler to prevent default behavior\n *\n * @default defaultPasteHandler (auto-applies paste data)\n */\n pasteHandler?: PasteHandler | null;\n}\n\n/** Internal state managed by the clipboard plugin */\nexport interface ClipboardState {\n /** The last copied text (for reference/debugging) */\n lastCopied: string | null;\n}\n\n/** Event detail emitted after a successful copy operation */\nexport interface CopyDetail {\n /** The text that was copied to clipboard */\n text: string;\n /** Number of rows copied */\n rowCount: number;\n /** Number of columns copied */\n columnCount: number;\n}\n\n/** Target cell coordinates and bounds for paste operations */\nexport interface PasteTarget {\n /** Target row index (top-left of paste area) */\n row: number;\n /** Target column index (top-left of paste area) */\n col: number;\n /** Target column field name (for easy data mapping) */\n field: string;\n /**\n * Selection bounds that constrain the paste area.\n * If set, paste data will be clipped to fit within these bounds.\n * If null, paste expands freely from the target cell.\n */\n bounds: {\n /** End row index (inclusive) */\n endRow: number;\n /** End column index (inclusive) */\n endCol: number;\n } | null;\n}\n\n/** Event detail emitted after a paste operation */\nexport interface PasteDetail {\n /** Parsed rows from clipboard (2D array of cell values) */\n rows: string[][];\n /** Raw text that was pasted */\n text: string;\n /** The target cell where paste starts (top-left of paste area). Null if no cell is selected. */\n target: PasteTarget | null;\n /**\n * Column fields for each column in the paste range, starting from target.col.\n * Useful for mapping parsed cell values to data fields.\n * Length matches the width of the pasted data (or available columns, whichever is smaller).\n */\n fields: string[];\n}\n\n/**\n * Default paste handler that applies pasted data to grid.rows.\n *\n * This is the built-in handler used when no custom `pasteHandler` is configured.\n * It clones the rows array for immutability and applies values starting at the target cell.\n *\n * Behavior:\n * - Single cell selection: paste expands freely, adds new rows if needed\n * - Range/row selection: paste is clipped to fit within selection bounds\n * - Non-editable columns: values are skipped (column alignment preserved)\n *\n * @param detail - The parsed paste data from clipboard\n * @param grid - The grid element to update\n */\nexport function defaultPasteHandler(detail: PasteDetail, grid: GridElement): void {\n const { rows: pastedRows, target, fields } = detail;\n\n // No target = nothing to do\n if (!target) return;\n\n // Get current rows and columns from grid\n const currentRows = grid.rows as Record<string, unknown>[];\n const columns = grid.effectiveConfig.columns ?? [];\n const allFields = columns.map((col) => col.field);\n\n // Build a map of field -> editable for quick lookup\n const editableMap = new Map<string, boolean>();\n columns.forEach((col) => {\n editableMap.set(col.field, col.editable === true);\n });\n\n // Clone data for immutability\n const newRows = [...currentRows];\n\n // Calculate row bounds\n const maxPasteRow = target.bounds ? target.bounds.endRow : Infinity;\n\n // Apply pasted data starting at target cell\n pastedRows.forEach((rowData, rowOffset) => {\n const targetRowIndex = target.row + rowOffset;\n\n // Stop if we've exceeded the selection bounds\n if (targetRowIndex > maxPasteRow) return;\n\n // Only grow array if no bounds (single cell selection)\n if (!target.bounds) {\n while (targetRowIndex >= newRows.length) {\n const emptyRow: Record<string, unknown> = {};\n allFields.forEach((field) => (emptyRow[field] = ''));\n newRows.push(emptyRow);\n }\n } else if (targetRowIndex >= newRows.length) {\n // With bounds, don't paste beyond existing rows\n return;\n }\n\n // Clone the target row and apply values\n newRows[targetRowIndex] = { ...newRows[targetRowIndex] };\n rowData.forEach((cellValue, colOffset) => {\n // fields array is already constrained by bounds in ClipboardPlugin\n const field = fields[colOffset];\n if (field && editableMap.get(field)) {\n // Only paste into editable columns\n newRows[targetRowIndex][field] = cellValue;\n }\n });\n });\n\n // Update grid with new data\n grid.rows = newRows;\n}\n","/**\n * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport { isUtilityColumn } from '../../core/plugin/expander-column';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type PasteDetail,\n type PasteTarget,\n} from './types';\n\n/**\n * Clipboard Plugin for tbw-grid\n *\n * Brings familiar copy/cut/paste functionality with full keyboard shortcut support\n * (Ctrl+C, Ctrl+X, Ctrl+V). Handles single cells, multi-cell selections, and integrates\n * seamlessly with Excel and other spreadsheet applications via tab-delimited output.\n *\n * > **Optional Dependency:** Works best with SelectionPlugin for copying/pasting selected\n * > cells. Without SelectionPlugin, copies the entire grid and pastes at row 0, column 0.\n *\n * ## Installation\n *\n * ```ts\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `includeHeaders` | `boolean` | `false` | Include column headers in copied data |\n * | `delimiter` | `string` | `'\\t'` | Column delimiter (tab for Excel compatibility) |\n * | `newline` | `string` | `'\\n'` | Row delimiter |\n * | `quoteStrings` | `boolean` | `false` | Wrap string values in quotes |\n * | `processCell` | `(value, field, row) => string` | - | Custom cell value processor |\n * | `pasteHandler` | `PasteHandler \\| null` | `defaultPasteHandler` | Custom paste handler |\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `copy` | `(options?) => Promise<void>` | Copy selection to clipboard |\n * | `paste` | `() => Promise<void>` | Paste from clipboard |\n * | `getSelectionAsText` | `() => string` | Get clipboard text without copying |\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see {@link SelectionPlugin} for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n // Cast to HTMLElement since GridElement is an interface\n (grid as unknown as HTMLElement).addEventListener(\n 'paste',\n (e: Event) => this.#handleNativePaste(e as ClipboardEvent),\n { signal: this.disconnectSignal },\n );\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n this.#handleCopy(event.target as HTMLElement);\n return true; // Prevent default browser behavior\n }\n\n // For paste, we do NOT return true - let the native paste event fire\n // so we can access clipboardData synchronously in #handleNativePaste\n return false;\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Handle copy operation.\n *\n * Everything is treated as a range:\n * - With selection: copies the selected range\n * - Row mode: range spanning all columns for selected rows\n * - No selection plugin: entire grid as a range\n * - No selection: try to get focused cell from DOM as 1x1 range\n */\n #handleCopy(target: HTMLElement): void {\n const selectionPlugin = this.#getSelectionPlugin();\n const selection = selectionPlugin?.getSelection();\n const lastCol = this.columns.length - 1;\n const lastRow = this.rows.length - 1;\n\n let range: { startRow: number; startCol: number; endRow: number; endCol: number };\n\n if (selection && selection.ranges.length > 0) {\n const { mode, ranges } = selection;\n const activeRange = ranges[ranges.length - 1];\n\n if (mode === 'row') {\n // Row mode: use row bounds, but span all columns\n range = {\n startRow: activeRange.from.row,\n startCol: 0,\n endRow: activeRange.to.row,\n endCol: lastCol,\n };\n } else {\n // Cell or range mode: use the selection as-is\n range = {\n startRow: activeRange.from.row,\n startCol: activeRange.from.col,\n endRow: activeRange.to.row,\n endCol: activeRange.to.col,\n };\n }\n } else if (!selectionPlugin) {\n // No selection plugin: copy entire grid\n range = { startRow: 0, startCol: 0, endRow: lastRow, endCol: lastCol };\n } else {\n // Selection plugin exists but no selection: try focused cell from DOM\n const focused = this.#getFocusedCellFromDOM(target);\n if (!focused) return;\n range = { startRow: focused.row, startCol: focused.col, endRow: focused.row, endCol: focused.col };\n }\n\n const result = this.#buildRangeText(range);\n\n copyToClipboard(result.text).then(() => {\n this.lastCopied = { text: result.text, timestamp: Date.now() };\n this.emit<CopyDetail>('copy', {\n text: result.text,\n rowCount: result.rowCount,\n columnCount: result.columnCount,\n });\n });\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection plugin\n const selectionPlugin = this.#getSelectionPlugin();\n const selection = selectionPlugin?.getSelection();\n const firstRange = selection?.ranges?.[0];\n\n // Determine target cell and bounds\n const targetRow = firstRange?.from.row ?? 0;\n const targetCol = firstRange?.from.col ?? 0;\n\n // Check if multi-cell selection (range with different start/end)\n const isMultiCell =\n firstRange &&\n (selection?.mode === 'range' || selection?.mode === 'row') &&\n (firstRange.from.row !== firstRange.to.row || firstRange.from.col !== firstRange.to.col);\n\n const bounds = isMultiCell ? { endRow: firstRange.to.row, endCol: firstRange.to.col } : null;\n const maxCol = bounds?.endCol ?? this.columns.length - 1;\n\n // Build target info\n const column = this.columns[targetCol];\n const target: PasteTarget | null = column ? { row: targetRow, col: targetCol, field: column.field, bounds } : null;\n\n // Build field list for paste width (constrained by bounds if set)\n const fields: string[] = [];\n const pasteWidth = parsed[0]?.length ?? 0;\n for (let i = 0; i < pasteWidth && targetCol + i <= maxCol; i++) {\n const col = this.columns[targetCol + i];\n if (col && !col.hidden) {\n fields.push(col.field);\n }\n }\n\n const detail: PasteDetail = { rows: parsed, text, target, fields };\n\n // Emit the event for any listeners\n this.emit<PasteDetail>('paste', detail);\n\n // Apply paste data using the configured handler (or default)\n this.#applyPasteHandler(detail);\n }\n\n /**\n * Apply the paste handler to update grid data.\n *\n * Uses the configured `pasteHandler`, or the default handler if not specified.\n * Set `pasteHandler: null` in config to disable auto-paste.\n */\n #applyPasteHandler(detail: PasteDetail): void {\n if (!this.grid) return;\n\n const { pasteHandler } = this.config;\n\n // pasteHandler: null means explicitly disabled\n if (pasteHandler === null) return;\n\n // Use custom handler or default\n const handler = pasteHandler ?? defaultPasteHandler;\n handler(detail, this.grid);\n }\n\n /**\n * Get the selection plugin instance if available.\n */\n #getSelectionPlugin(): SelectionPluginInterface | undefined {\n // Use getPluginByName for duck-typing approach to avoid import order issues\n try {\n const plugin = this.grid?.getPluginByName('selection');\n if (plugin) {\n return plugin as unknown as SelectionPluginInterface;\n }\n } catch {\n // Selection plugin not available\n }\n return undefined;\n }\n\n /**\n * Build text for a rectangular range of cells.\n * Utility columns (like expander columns) are automatically excluded.\n */\n #buildRangeText(range: { startRow: number; startCol: number; endRow: number; endCol: number }): {\n text: string;\n rowCount: number;\n columnCount: number;\n } {\n const { startRow, startCol, endRow, endCol } = range;\n const minRow = Math.min(startRow, endRow);\n const maxRow = Math.max(startRow, endRow);\n const minCol = Math.min(startCol, endCol);\n const maxCol = Math.max(startCol, endCol);\n\n const delimiter = this.config.delimiter ?? '\\t';\n const newline = this.config.newline ?? '\\n';\n const lines: string[] = [];\n\n // Get columns in the range, excluding utility columns (expander, etc.)\n const rangeColumns = this.columns.slice(minCol, maxCol + 1).filter((col) => !isUtilityColumn(col));\n\n // Add header row if configured\n if (this.config.includeHeaders) {\n const headerCells = rangeColumns.map((c) => c.header || c.field);\n lines.push(headerCells.join(delimiter));\n }\n\n // Add data rows\n for (let r = minRow; r <= maxRow; r++) {\n const rowData = this.rows[r] as Record<string, unknown> | undefined;\n if (!rowData) continue;\n\n const cells = rangeColumns.map((col) => {\n const value = rowData[col.field];\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n return String(value);\n });\n lines.push(cells.join(delimiter));\n }\n\n return {\n text: lines.join(newline),\n rowCount: maxRow - minRow + 1,\n columnCount: maxCol - minCol + 1,\n };\n }\n\n /**\n * Get focused cell coordinates from DOM.\n * Used as fallback when SelectionPlugin has no selection.\n */\n #getFocusedCellFromDOM(target: HTMLElement): { row: number; col: number } | null {\n const cell = target.closest('[data-field-cache]') as HTMLElement | null;\n if (!cell) return null;\n\n const field = cell.dataset.fieldCache;\n const rowIndexStr = cell.dataset.row;\n if (!field || !rowIndexStr) return null;\n\n const row = parseInt(rowIndexStr, 10);\n if (isNaN(row)) return null;\n\n const col = this.columns.findIndex((c) => c.field === field);\n if (col === -1) return null;\n\n return { row, col };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Copy currently selected rows to clipboard.\n * @returns The copied text\n */\n async copy(): Promise<string> {\n const selectionPlugin = this.#getSelectionPlugin();\n const selection = selectionPlugin?.getSelection();\n const lastCol = this.columns.length - 1;\n\n // Default to entire grid if no selection\n let range = { startRow: 0, startCol: 0, endRow: this.rows.length - 1, endCol: lastCol };\n\n if (selection && selection.ranges.length > 0) {\n const activeRange = selection.ranges[selection.ranges.length - 1];\n if (selection.mode === 'row') {\n range = { startRow: activeRange.from.row, startCol: 0, endRow: activeRange.to.row, endCol: lastCol };\n } else {\n range = {\n startRow: activeRange.from.row,\n startCol: activeRange.from.col,\n endRow: activeRange.to.row,\n endCol: activeRange.to.col,\n };\n }\n }\n\n const result = this.#buildRangeText(range);\n await copyToClipboard(result.text);\n this.lastCopied = { text: result.text, timestamp: Date.now() };\n return result.text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n * @param indices - Array of row indices to copy\n * @returns The copied text\n */\n async copyRows(indices: number[]): Promise<string> {\n if (indices.length === 0) return '';\n\n const sortedIndices = [...indices].sort((a, b) => a - b);\n const lastCol = this.columns.length - 1;\n\n // For non-contiguous rows, we need to copy each row separately\n // For now, copy the range from first to last selected row\n const range = {\n startRow: sortedIndices[0],\n startCol: 0,\n endRow: sortedIndices[sortedIndices.length - 1],\n endCol: lastCol,\n };\n\n const result = this.#buildRangeText(range);\n await copyToClipboard(result.text);\n this.lastCopied = { text: result.text, timestamp: Date.now() };\n return result.text;\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Interface for SelectionPlugin methods we need.\n * This avoids circular imports while providing type safety.\n */\ninterface SelectionPluginInterface {\n name: string;\n /**\n * Get unified selection result (preferred API).\n * Works for all selection modes.\n */\n getSelection(): {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n };\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, PasteDetail } from './types';\n"],"names":["copyToClipboard","text","textarea","success","parseClipboardText","config","delimiter","newline","normalizedText","rows","currentRow","currentCell","inQuotes","i","char","c","readFromClipboard","defaultPasteHandler","detail","grid","pastedRows","target","fields","currentRows","columns","allFields","col","editableMap","newRows","maxPasteRow","rowData","rowOffset","targetRowIndex","emptyRow","field","cellValue","colOffset","ClipboardPlugin","BaseGridPlugin","e","#handleNativePaste","event","#handleCopy","selectionPlugin","#getSelectionPlugin","selection","lastCol","lastRow","range","mode","ranges","activeRange","focused","#getFocusedCellFromDOM","result","#buildRangeText","parsed","firstRange","targetRow","targetCol","bounds","maxCol","column","pasteWidth","#applyPasteHandler","pasteHandler","plugin","startRow","startCol","endRow","endCol","minRow","maxRow","minCol","lines","rangeColumns","isUtilityColumn","headerCells","r","cells","value","cell","rowIndexStr","row","indices","sortedIndices","a","b"],"mappings":"kaAiHA,eAAsBA,EAAgBC,EAAgC,CACpE,GAAI,CACF,aAAM,UAAU,UAAU,UAAUA,CAAI,EACjC,EACT,MAAQ,CAEN,MAAMC,EAAW,SAAS,cAAc,UAAU,EAClDA,EAAS,MAAQD,EACjBC,EAAS,MAAM,SAAW,QAC1BA,EAAS,MAAM,QAAU,IACzBA,EAAS,MAAM,cAAgB,OAC/B,SAAS,KAAK,YAAYA,CAAQ,EAClCA,EAAS,OAAA,EACT,MAAMC,EAAU,SAAS,YAAY,MAAM,EAC3C,gBAAS,KAAK,YAAYD,CAAQ,EAC3BC,CACT,CACF,CC7GO,SAASC,EAAmBH,EAAcI,EAAqC,CACpF,MAAMC,EAAYD,EAAO,WAAa,IAChCE,EAAUF,EAAO,SAAW;AAAA,EAG5BG,EAAiBP,EAAK,QAAQ,QAAS;AAAA,CAAI,EAAE,QAAQ,MAAO;AAAA,CAAI,EAGhEQ,EAAmB,CAAA,EACzB,IAAIC,EAAuB,CAAA,EACvBC,EAAc,GACdC,EAAW,GAEf,QAASC,EAAI,EAAGA,EAAIL,EAAe,OAAQK,IAAK,CAC9C,MAAMC,EAAON,EAAeK,CAAC,EAEzBC,IAAS,KAAO,CAACF,EAEnBA,EAAW,GACFE,IAAS,KAAOF,EAErBJ,EAAeK,EAAI,CAAC,IAAM,KAC5BF,GAAe,IACfE,KAGAD,EAAW,GAEJE,IAASR,GAAa,CAACM,GAEhCF,EAAW,KAAKC,CAAW,EAC3BA,EAAc,IACLG,IAASP,GAAW,CAACK,GAE9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A,EAE9E,GAAID,GAAaA,EAAU,OAAO,OAAS,EAAG,CAC5C,MAAMM,EAAcN,EAAU,OAAOA,EAAU,OAAO,OAAS,CAAC,EAC5DA,EAAU,OAAS,MACrBG,EAAQ,CAAE,SAAUG,EAAY,KAAK,IAAK,SAAU,EAAG,OAAQA,EAAY,GAAG,IAAK,OAAQL,CAAA,EAE3FE,EAAQ,CACN,SAAUG,EAAY,KAAK,IAC3B,SAAUA,EAAY,KAAK,IAC3B,OAAQA,EAAY,GAAG,IACvB,OAAQA,EAAY,GAAG,GAAA,CAG7B,CAEA,MAAMG,EAAS,KAAKC,GAAgBP,CAAK,EACzC,aAAMhD,EAAgBsD,EAAO,IAAI,EACjC,KAAK,WAAa,CAAE,KAAMA,EAAO,KAAM,UAAW,KAAK,KAAI,EACpDA,EAAO,IAChB,CAOA,MAAM,SAAS8B,EAAoC,CACjD,GAAIA,EAAQ,SAAW,EAAG,MAAO,GAEjC,MAAMC,EAAgB,CAAC,GAAGD,CAAO,EAAE,KAAK,CAACE,EAAGC,IAAMD,EAAIC,CAAC,EACjDzC,EAAU,KAAK,QAAQ,OAAS,EAIhCE,EAAQ,CACZ,SAAUqC,EAAc,CAAC,EACzB,SAAU,EACV,OAAQA,EAAcA,EAAc,OAAS,CAAC,EAC9C,OAAQvC,CAAA,EAGJQ,EAAS,KAAKC,GAAgBP,CAAK,EACzC,aAAMhD,EAAgBsD,EAAO,IAAI,EACjC,KAAK,WAAa,CAAE,KAAMA,EAAO,KAAM,UAAW,KAAK,KAAI,EACpDA,EAAO,IAChB,CAMA,MAAM,OAAoC,CACxC,MAAMrD,EAAO,MAAMe,EAAA,EACnB,OAAKf,EACEG,EAAmBH,EAAM,KAAK,MAAM,EADzB,IAEpB,CAMA,eAA4D,CAC1D,OAAO,KAAK,UACd,CAEF"}
1
+ {"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts","../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../libs/grid/src/lib/plugins/clipboard/ClipboardPlugin.ts"],"sourcesContent":["/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { ClipboardConfig } from './types';\n\n/** Parameters for building clipboard text */\nexport interface CopyParams {\n /** All grid rows */\n rows: unknown[];\n /** Column configurations */\n columns: ColumnConfig[];\n /** Selected row indices */\n selectedIndices: Set<number> | number[];\n /** Clipboard configuration */\n config: ClipboardConfig;\n}\n\n/**\n * Format a cell value for clipboard output.\n *\n * Uses custom processCell if provided, otherwise applies default formatting:\n * - null/undefined → empty string\n * - Date → ISO string\n * - Object → JSON string\n * - Other → String conversion with optional quoting\n *\n * @param value - The cell value to format\n * @param field - The field name\n * @param row - The full row object\n * @param config - Clipboard configuration\n * @returns Formatted string value\n */\nexport function formatCellValue(value: unknown, field: string, row: unknown, config: ClipboardConfig): string {\n if (config.processCell) {\n return config.processCell(value, field, row);\n }\n\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n\n const str = String(value);\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Quote if contains delimiter, newline, or quotes (or if quoteStrings is enabled)\n if (config.quoteStrings || str.includes(delimiter) || str.includes(newline) || str.includes('\"')) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build clipboard text from selected rows and columns.\n *\n * @param params - Copy parameters including rows, columns, selection, and config\n * @returns Tab-separated (or custom delimiter) text ready for clipboard\n */\nexport function buildClipboardText(params: CopyParams): string {\n const { rows, columns, selectedIndices, config } = params;\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Filter to visible columns (not hidden, not internal __ prefixed)\n const visibleColumns = columns.filter((c) => !c.hidden && !c.field.startsWith('__'));\n\n const lines: string[] = [];\n\n // Add header row if configured\n if (config.includeHeaders) {\n const headerCells = visibleColumns.map((c) => {\n const header = c.header || c.field;\n // Quote headers if they contain special characters\n if (header.includes(delimiter) || header.includes(newline) || header.includes('\"')) {\n return `\"${header.replace(/\"/g, '\"\"')}\"`;\n }\n return header;\n });\n lines.push(headerCells.join(delimiter));\n }\n\n // Convert indices to sorted array\n const indices = selectedIndices instanceof Set ? [...selectedIndices] : selectedIndices;\n const sortedIndices = [...indices].sort((a, b) => a - b);\n\n // Build data rows\n for (const idx of sortedIndices) {\n const row = rows[idx];\n if (!row) continue;\n\n const cells = visibleColumns.map((col) =>\n formatCellValue((row as Record<string, unknown>)[col.field], col.field, row, config)\n );\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n}\n\n/**\n * Copy text to the system clipboard.\n *\n * Uses the modern Clipboard API when available, with fallback\n * to execCommand for older browsers.\n *\n * @param text - The text to copy\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n // Fallback for older browsers or when Clipboard API is not available\n const textarea = document.createElement('textarea');\n textarea.value = text;\n textarea.style.position = 'fixed';\n textarea.style.opacity = '0';\n textarea.style.pointerEvents = 'none';\n document.body.appendChild(textarea);\n textarea.select();\n const success = document.execCommand('copy');\n document.body.removeChild(textarea);\n return success;\n }\n}\n","/**\n * Clipboard Paste Logic\n *\n * Pure functions for reading and parsing clipboard data.\n */\n\nimport type { ClipboardConfig } from './types';\n\n/**\n * Parse clipboard text into a 2D array of cell values.\n *\n * Handles:\n * - Quoted values (with escaped double quotes \"\")\n * - Multi-line quoted values (newlines within quotes are preserved)\n * - Custom delimiters and newlines\n * - Empty lines (filtered out only if they contain no data)\n *\n * @param text - Raw clipboard text\n * @param config - Clipboard configuration\n * @returns 2D array where each sub-array is a row of cell values\n */\nexport function parseClipboardText(text: string, config: ClipboardConfig): string[][] {\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Handle Windows CRLF line endings\n const normalizedText = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n // Parse the entire text handling quoted fields that may span multiple lines\n const rows: string[][] = [];\n let currentRow: string[] = [];\n let currentCell = '';\n let inQuotes = false;\n\n for (let i = 0; i < normalizedText.length; i++) {\n const char = normalizedText[i];\n\n if (char === '\"' && !inQuotes) {\n // Start of quoted field\n inQuotes = true;\n } else if (char === '\"' && inQuotes) {\n // Check for escaped quote (\"\")\n if (normalizedText[i + 1] === '\"') {\n currentCell += '\"';\n i++; // Skip the second quote\n } else {\n // End of quoted field\n inQuotes = false;\n }\n } else if (char === delimiter && !inQuotes) {\n // Field separator\n currentRow.push(currentCell);\n currentCell = '';\n } else if (char === newline && !inQuotes) {\n // Row separator (only if not inside quotes)\n currentRow.push(currentCell);\n currentCell = '';\n // Only add non-empty rows (at least one non-empty cell or multiple cells)\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n currentRow = [];\n } else {\n currentCell += char;\n }\n }\n\n // Handle the last cell and row\n currentRow.push(currentCell);\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n\n return rows;\n}\n\n/**\n * Read text from the system clipboard.\n *\n * Uses the modern Clipboard API. Returns empty string if\n * the API is not available or permission is denied.\n *\n * @returns Promise resolving to clipboard text or empty string\n */\nexport async function readFromClipboard(): Promise<string> {\n try {\n return await navigator.clipboard.readText();\n } catch {\n // Permission denied or API not available\n return '';\n }\n}\n","/**\n * Clipboard Plugin Types\n *\n * Type definitions for clipboard copy/paste functionality.\n */\n\nimport type { GridElement } from '../../core/plugin/base-plugin';\n\n/**\n * Custom paste handler function.\n *\n * @param detail - The parsed paste data with target and field info\n * @param grid - The grid element to update\n * @returns `false` to prevent the default paste behavior, or `void`/`true` to allow it\n *\n * @example\n * ```ts\n * // Custom handler that validates before pasting\n * new ClipboardPlugin({\n * pasteHandler: (detail, grid) => {\n * if (!detail.target) return false;\n * // Apply custom validation/transformation...\n * applyPasteData(detail, grid);\n * return false; // We handled it, skip default\n * }\n * })\n * ```\n */\nexport type PasteHandler = (detail: PasteDetail, grid: GridElement) => boolean | void;\n\n/** Configuration options for the clipboard plugin */\nexport interface ClipboardConfig {\n /** Include column headers in copied text (default: false) */\n includeHeaders?: boolean;\n /** Column delimiter character (default: '\\t' for tab) */\n delimiter?: string;\n /** Row delimiter/newline character (default: '\\n') */\n newline?: string;\n /** Wrap string values with quotes (default: false) */\n quoteStrings?: boolean;\n /** Custom cell value processor for copy operations */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n /**\n * Custom paste handler. By default, the plugin applies pasted data to `grid.rows`\n * starting at the target cell.\n *\n * - Set to a custom function to handle paste yourself\n * - Set to `null` to disable auto-paste (event still fires)\n * - Return `false` from handler to prevent default behavior\n *\n * @default defaultPasteHandler (auto-applies paste data)\n */\n pasteHandler?: PasteHandler | null;\n}\n\n/** Internal state managed by the clipboard plugin */\nexport interface ClipboardState {\n /** The last copied text (for reference/debugging) */\n lastCopied: string | null;\n}\n\n/** Event detail emitted after a successful copy operation */\nexport interface CopyDetail {\n /** The text that was copied to clipboard */\n text: string;\n /** Number of rows copied */\n rowCount: number;\n /** Number of columns copied */\n columnCount: number;\n}\n\n/** Target cell coordinates and bounds for paste operations */\nexport interface PasteTarget {\n /** Target row index (top-left of paste area) */\n row: number;\n /** Target column index (top-left of paste area) */\n col: number;\n /** Target column field name (for easy data mapping) */\n field: string;\n /**\n * Selection bounds that constrain the paste area.\n * If set, paste data will be clipped to fit within these bounds.\n * If null, paste expands freely from the target cell.\n */\n bounds: {\n /** End row index (inclusive) */\n endRow: number;\n /** End column index (inclusive) */\n endCol: number;\n } | null;\n}\n\n/** Event detail emitted after a paste operation */\nexport interface PasteDetail {\n /** Parsed rows from clipboard (2D array of cell values) */\n rows: string[][];\n /** Raw text that was pasted */\n text: string;\n /** The target cell where paste starts (top-left of paste area). Null if no cell is selected. */\n target: PasteTarget | null;\n /**\n * Column fields for each column in the paste range, starting from target.col.\n * Useful for mapping parsed cell values to data fields.\n * Length matches the width of the pasted data (or available columns, whichever is smaller).\n */\n fields: string[];\n}\n\n/**\n * Default paste handler that applies pasted data to grid.rows.\n *\n * This is the built-in handler used when no custom `pasteHandler` is configured.\n * It clones the rows array for immutability and applies values starting at the target cell.\n *\n * Behavior:\n * - Single cell selection: paste expands freely, adds new rows if needed\n * - Range/row selection: paste is clipped to fit within selection bounds\n * - Non-editable columns: values are skipped (column alignment preserved)\n *\n * @param detail - The parsed paste data from clipboard\n * @param grid - The grid element to update\n */\nexport function defaultPasteHandler(detail: PasteDetail, grid: GridElement): void {\n const { rows: pastedRows, target, fields } = detail;\n\n // No target = nothing to do\n if (!target) return;\n\n // Get current rows and columns from grid\n const currentRows = grid.rows as Record<string, unknown>[];\n const columns = grid.effectiveConfig.columns ?? [];\n const allFields = columns.map((col) => col.field);\n\n // Build a map of field -> editable for quick lookup\n const editableMap = new Map<string, boolean>();\n columns.forEach((col) => {\n editableMap.set(col.field, col.editable === true);\n });\n\n // Clone data for immutability\n const newRows = [...currentRows];\n\n // Calculate row bounds\n const maxPasteRow = target.bounds ? target.bounds.endRow : Infinity;\n\n // Apply pasted data starting at target cell\n pastedRows.forEach((rowData, rowOffset) => {\n const targetRowIndex = target.row + rowOffset;\n\n // Stop if we've exceeded the selection bounds\n if (targetRowIndex > maxPasteRow) return;\n\n // Only grow array if no bounds (single cell selection)\n if (!target.bounds) {\n while (targetRowIndex >= newRows.length) {\n const emptyRow: Record<string, unknown> = {};\n allFields.forEach((field) => (emptyRow[field] = ''));\n newRows.push(emptyRow);\n }\n } else if (targetRowIndex >= newRows.length) {\n // With bounds, don't paste beyond existing rows\n return;\n }\n\n // Clone the target row and apply values\n newRows[targetRowIndex] = { ...newRows[targetRowIndex] };\n rowData.forEach((cellValue, colOffset) => {\n // fields array is already constrained by bounds in ClipboardPlugin\n const field = fields[colOffset];\n if (field && editableMap.get(field)) {\n // Only paste into editable columns\n newRows[targetRowIndex][field] = cellValue;\n }\n });\n });\n\n // Update grid with new data\n grid.rows = newRows;\n}\n","/**\n * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport { isUtilityColumn } from '../../core/plugin/expander-column';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type PasteDetail,\n type PasteTarget,\n} from './types';\n\n/**\n * Clipboard Plugin for tbw-grid\n *\n * Brings familiar copy/cut/paste functionality with full keyboard shortcut support\n * (Ctrl+C, Ctrl+X, Ctrl+V). Handles single cells, multi-cell selections, and integrates\n * seamlessly with Excel and other spreadsheet applications via tab-delimited output.\n *\n * > **Optional Dependency:** Works best with SelectionPlugin for copying/pasting selected\n * > cells. Without SelectionPlugin, copies the entire grid and pastes at row 0, column 0.\n *\n * ## Installation\n *\n * ```ts\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `includeHeaders` | `boolean` | `false` | Include column headers in copied data |\n * | `delimiter` | `string` | `'\\t'` | Column delimiter (tab for Excel compatibility) |\n * | `newline` | `string` | `'\\n'` | Row delimiter |\n * | `quoteStrings` | `boolean` | `false` | Wrap string values in quotes |\n * | `processCell` | `(value, field, row) => string` | - | Custom cell value processor |\n * | `pasteHandler` | `PasteHandler \\| null` | `defaultPasteHandler` | Custom paste handler |\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `copy` | `(options?) => Promise<void>` | Copy selection to clipboard |\n * | `paste` | `() => Promise<void>` | Paste from clipboard |\n * | `getSelectionAsText` | `() => string` | Get clipboard text without copying |\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see {@link SelectionPlugin} for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n // Cast to HTMLElement since GridElement is an interface\n (grid as unknown as HTMLElement).addEventListener(\n 'paste',\n (e: Event) => this.#handleNativePaste(e as ClipboardEvent),\n { signal: this.disconnectSignal },\n );\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n this.#handleCopy(event.target as HTMLElement);\n return true; // Prevent default browser behavior\n }\n\n // For paste, we do NOT return true - let the native paste event fire\n // so we can access clipboardData synchronously in #handleNativePaste\n return false;\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Handle copy operation.\n *\n * Everything is treated as a range:\n * - With selection: copies the selected range\n * - Row mode: range spanning all columns for selected rows\n * - No selection plugin: entire grid as a range\n * - No selection: try to get focused cell from DOM as 1x1 range\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n const lastCol = this.columns.length - 1;\n const lastRow = this.rows.length - 1;\n\n let range: { startRow: number; startCol: number; endRow: number; endCol: number };\n\n if (selection && selection.ranges.length > 0) {\n const { mode, ranges } = selection;\n const activeRange = ranges[ranges.length - 1];\n\n if (mode === 'row') {\n // Row mode: use row bounds, but span all columns\n range = {\n startRow: activeRange.from.row,\n startCol: 0,\n endRow: activeRange.to.row,\n endCol: lastCol,\n };\n } else {\n // Cell or range mode: use the selection as-is\n range = {\n startRow: activeRange.from.row,\n startCol: activeRange.from.col,\n endRow: activeRange.to.row,\n endCol: activeRange.to.col,\n };\n }\n } else if (!selection) {\n // No selection plugin: copy entire grid\n range = { startRow: 0, startCol: 0, endRow: lastRow, endCol: lastCol };\n } else {\n // Selection plugin exists but no selection: try focused cell from DOM\n const focused = this.#getFocusedCellFromDOM(target);\n if (!focused) return;\n range = { startRow: focused.row, startCol: focused.col, endRow: focused.row, endCol: focused.col };\n }\n\n const result = this.#buildRangeText(range);\n\n copyToClipboard(result.text).then(() => {\n this.lastCopied = { text: result.text, timestamp: Date.now() };\n this.emit<CopyDetail>('copy', {\n text: result.text,\n rowCount: result.rowCount,\n columnCount: result.columnCount,\n });\n });\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection via query\n const selection = this.#getSelection();\n const firstRange = selection?.ranges?.[0];\n\n // Determine target cell and bounds\n const targetRow = firstRange?.from.row ?? 0;\n const targetCol = firstRange?.from.col ?? 0;\n\n // Check if multi-cell selection (range with different start/end)\n const isMultiCell =\n firstRange &&\n (selection?.mode === 'range' || selection?.mode === 'row') &&\n (firstRange.from.row !== firstRange.to.row || firstRange.from.col !== firstRange.to.col);\n\n const bounds = isMultiCell ? { endRow: firstRange.to.row, endCol: firstRange.to.col } : null;\n const maxCol = bounds?.endCol ?? this.columns.length - 1;\n\n // Build target info\n const column = this.columns[targetCol];\n const target: PasteTarget | null = column ? { row: targetRow, col: targetCol, field: column.field, bounds } : null;\n\n // Build field list for paste width (constrained by bounds if set)\n const fields: string[] = [];\n const pasteWidth = parsed[0]?.length ?? 0;\n for (let i = 0; i < pasteWidth && targetCol + i <= maxCol; i++) {\n const col = this.columns[targetCol + i];\n if (col && !col.hidden) {\n fields.push(col.field);\n }\n }\n\n const detail: PasteDetail = { rows: parsed, text, target, fields };\n\n // Emit the event for any listeners\n this.emit<PasteDetail>('paste', detail);\n\n // Apply paste data using the configured handler (or default)\n this.#applyPasteHandler(detail);\n }\n\n /**\n * Apply the paste handler to update grid data.\n *\n * Uses the configured `pasteHandler`, or the default handler if not specified.\n * Set `pasteHandler: null` in config to disable auto-paste.\n */\n #applyPasteHandler(detail: PasteDetail): void {\n if (!this.grid) return;\n\n const { pasteHandler } = this.config;\n\n // pasteHandler: null means explicitly disabled\n if (pasteHandler === null) return;\n\n // Use custom handler or default\n const handler = pasteHandler ?? defaultPasteHandler;\n handler(detail, this.grid);\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection', undefined);\n return responses?.[0];\n }\n\n /**\n * Build text for a rectangular range of cells.\n * Utility columns (like expander columns) are automatically excluded.\n */\n #buildRangeText(range: { startRow: number; startCol: number; endRow: number; endCol: number }): {\n text: string;\n rowCount: number;\n columnCount: number;\n } {\n const { startRow, startCol, endRow, endCol } = range;\n const minRow = Math.min(startRow, endRow);\n const maxRow = Math.max(startRow, endRow);\n const minCol = Math.min(startCol, endCol);\n const maxCol = Math.max(startCol, endCol);\n\n const delimiter = this.config.delimiter ?? '\\t';\n const newline = this.config.newline ?? '\\n';\n const lines: string[] = [];\n\n // Get columns in the range, excluding utility columns (expander, etc.)\n const rangeColumns = this.columns.slice(minCol, maxCol + 1).filter((col) => !isUtilityColumn(col));\n\n // Add header row if configured\n if (this.config.includeHeaders) {\n const headerCells = rangeColumns.map((c) => c.header || c.field);\n lines.push(headerCells.join(delimiter));\n }\n\n // Add data rows\n for (let r = minRow; r <= maxRow; r++) {\n const rowData = this.rows[r] as Record<string, unknown> | undefined;\n if (!rowData) continue;\n\n const cells = rangeColumns.map((col) => {\n const value = rowData[col.field];\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n return String(value);\n });\n lines.push(cells.join(delimiter));\n }\n\n return {\n text: lines.join(newline),\n rowCount: maxRow - minRow + 1,\n columnCount: maxCol - minCol + 1,\n };\n }\n\n /**\n * Get focused cell coordinates from DOM.\n * Used as fallback when SelectionPlugin has no selection.\n */\n #getFocusedCellFromDOM(target: HTMLElement): { row: number; col: number } | null {\n const cell = target.closest('[data-field-cache]') as HTMLElement | null;\n if (!cell) return null;\n\n const field = cell.dataset.fieldCache;\n const rowIndexStr = cell.dataset.row;\n if (!field || !rowIndexStr) return null;\n\n const row = parseInt(rowIndexStr, 10);\n if (isNaN(row)) return null;\n\n const col = this.columns.findIndex((c) => c.field === field);\n if (col === -1) return null;\n\n return { row, col };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Copy currently selected rows to clipboard.\n * @returns The copied text\n */\n async copy(): Promise<string> {\n const selection = this.#getSelection();\n const lastCol = this.columns.length - 1;\n\n // Default to entire grid if no selection\n let range = { startRow: 0, startCol: 0, endRow: this.rows.length - 1, endCol: lastCol };\n\n if (selection && selection.ranges.length > 0) {\n const activeRange = selection.ranges[selection.ranges.length - 1];\n if (selection.mode === 'row') {\n range = { startRow: activeRange.from.row, startCol: 0, endRow: activeRange.to.row, endCol: lastCol };\n } else {\n range = {\n startRow: activeRange.from.row,\n startCol: activeRange.from.col,\n endRow: activeRange.to.row,\n endCol: activeRange.to.col,\n };\n }\n }\n\n const result = this.#buildRangeText(range);\n await copyToClipboard(result.text);\n this.lastCopied = { text: result.text, timestamp: Date.now() };\n return result.text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n * @param indices - Array of row indices to copy\n * @returns The copied text\n */\n async copyRows(indices: number[]): Promise<string> {\n if (indices.length === 0) return '';\n\n const sortedIndices = [...indices].sort((a, b) => a - b);\n const lastCol = this.columns.length - 1;\n\n // For non-contiguous rows, we need to copy each row separately\n // For now, copy the range from first to last selected row\n const range = {\n startRow: sortedIndices[0],\n startCol: 0,\n endRow: sortedIndices[sortedIndices.length - 1],\n endCol: lastCol,\n };\n\n const result = this.#buildRangeText(range);\n await copyToClipboard(result.text);\n this.lastCopied = { text: result.text, timestamp: Date.now() };\n return result.text;\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, PasteDetail } from './types';\n"],"names":["copyToClipboard","text","textarea","success","parseClipboardText","config","delimiter","newline","normalizedText","rows","currentRow","currentCell","inQuotes","i","char","c","readFromClipboard","defaultPasteHandler","detail","grid","pastedRows","target","fields","currentRows","columns","allFields","col","editableMap","newRows","maxPasteRow","rowData","rowOffset","targetRowIndex","emptyRow","field","cellValue","colOffset","ClipboardPlugin","BaseGridPlugin","e","#handleNativePaste","event","#handleCopy","selection","#getSelection","lastCol","lastRow","range","mode","ranges","activeRange","focused","#getFocusedCellFromDOM","result","#buildRangeText","parsed","firstRange","targetRow","targetCol","bounds","maxCol","column","pasteWidth","#applyPasteHandler","pasteHandler","startRow","startCol","endRow","endCol","minRow","maxRow","minCol","lines","rangeColumns","isUtilityColumn","headerCells","r","cells","value","cell","rowIndexStr","row","indices","sortedIndices","a","b"],"mappings":"kaAiHA,eAAsBA,EAAgBC,EAAgC,CACpE,GAAI,CACF,aAAM,UAAU,UAAU,UAAUA,CAAI,EACjC,EACT,MAAQ,CAEN,MAAMC,EAAW,SAAS,cAAc,UAAU,EAClDA,EAAS,MAAQD,EACjBC,EAAS,MAAM,SAAW,QAC1BA,EAAS,MAAM,QAAU,IACzBA,EAAS,MAAM,cAAgB,OAC/B,SAAS,KAAK,YAAYA,CAAQ,EAClCA,EAAS,OAAA,EACT,MAAMC,EAAU,SAAS,YAAY,MAAM,EAC3C,gBAAS,KAAK,YAAYD,CAAQ,EAC3BC,CACT,CACF,CC7GO,SAASC,EAAmBH,EAAcI,EAAqC,CACpF,MAAMC,EAAYD,EAAO,WAAa,IAChCE,EAAUF,EAAO,SAAW;AAAA,EAG5BG,EAAiBP,EAAK,QAAQ,QAAS;AAAA,CAAI,EAAE,QAAQ,MAAO;AAAA,CAAI,EAGhEQ,EAAmB,CAAA,EACzB,IAAIC,EAAuB,CAAA,EACvBC,EAAc,GACdC,EAAW,GAEf,QAASC,EAAI,EAAGA,EAAIL,EAAe,OAAQK,IAAK,CAC9C,MAAMC,EAAON,EAAeK,CAAC,EAEzBC,IAAS,KAAO,CAACF,EAEnBA,EAAW,GACFE,IAAS,KAAOF,EAErBJ,EAAeK,EAAI,CAAC,IAAM,KAC5BF,GAAe,IACfE,KAGAD,EAAW,GAEJE,IAASR,GAAa,CAACM,GAEhCF,EAAW,KAAKC,CAAW,EAC3BA,EAAc,IACLG,IAASP,GAAW,CAACK,GAE9BF,EAAW,KAAKC,CAAW,EAC3BA,EAAc,IAEVD,EAAW,OAAS,GAAKA,EAAW,KAAMK,GAAMA,EAAE,KAAA,IAAW,EAAE,IACjEN,EAAK,KAAKC,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,EAE3FE,EAAQ,CACN,SAAUG,EAAY,KAAK,IAC3B,SAAUA,EAAY,KAAK,IAC3B,OAAQA,EAAY,GAAG,IACvB,OAAQA,EAAY,GAAG,GAAA,CAG7B,CAEA,MAAMG,EAAS,KAAKC,GAAgBP,CAAK,EACzC,aAAM/C,EAAgBqD,EAAO,IAAI,EACjC,KAAK,WAAa,CAAE,KAAMA,EAAO,KAAM,UAAW,KAAK,KAAI,EACpDA,EAAO,IAChB,CAOA,MAAM,SAAS6B,EAAoC,CACjD,GAAIA,EAAQ,SAAW,EAAG,MAAO,GAEjC,MAAMC,EAAgB,CAAC,GAAGD,CAAO,EAAE,KAAK,CAACE,EAAGC,IAAMD,EAAIC,CAAC,EACjDxC,EAAU,KAAK,QAAQ,OAAS,EAIhCE,EAAQ,CACZ,SAAUoC,EAAc,CAAC,EACzB,SAAU,EACV,OAAQA,EAAcA,EAAc,OAAS,CAAC,EAC9C,OAAQtC,CAAA,EAGJQ,EAAS,KAAKC,GAAgBP,CAAK,EACzC,aAAM/C,EAAgBqD,EAAO,IAAI,EACjC,KAAK,WAAa,CAAE,KAAMA,EAAO,KAAM,UAAW,KAAK,KAAI,EACpDA,EAAO,IAChB,CAMA,MAAM,OAAoC,CACxC,MAAMpD,EAAO,MAAMe,EAAA,EACnB,OAAKf,EACEG,EAAmBH,EAAM,KAAK,MAAM,EADzB,IAEpB,CAMA,eAA4D,CAC1D,OAAO,KAAK,UACd,CAEF"}
@@ -1,2 +1,2 @@
1
- (function(m,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("../../core/plugin/base-plugin"),require("../../core/types")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/types"],h):(m=typeof globalThis<"u"?globalThis:m||self,h(m.TbwGridPlugin_contextMenu={},m.TbwGrid,m.TbwGrid))})(this,(function(m,h,S){"use strict";const x="@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:0 2px 10px var(--tbw-context-menu-shadow, 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{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 g(s,n){return(typeof s=="function"?s(n):s).filter(t=>!(t.hidden===!0||typeof t.hidden=="function"&&t.hidden(n)))}function z(s,n){return s.disabled===!0?!0:typeof s.disabled=="function"?s.disabled(n):!1}function v(s,n,l,t=S.DEFAULT_GRID_ICONS.submenuArrow){const i=document.createElement("div");i.className="tbw-context-menu",i.setAttribute("role","menu");for(const o of s){if(o.separator){const r=document.createElement("div");r.className="tbw-context-menu-separator",r.setAttribute("role","separator"),i.appendChild(r);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",o.cssClass&&e.classList.add(o.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",o.id);const a=z(o,n);if(a&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),o.icon){const r=document.createElement("span");r.className="tbw-context-menu-icon",r.innerHTML=o.icon,e.appendChild(r)}const c=document.createElement("span");if(c.className="tbw-context-menu-label",c.textContent=o.name,e.appendChild(c),o.shortcut){const r=document.createElement("span");r.className="tbw-context-menu-shortcut",r.textContent=o.shortcut,e.appendChild(r)}if(o.subMenu?.length){const r=document.createElement("span");r.className="tbw-context-menu-arrow",typeof t=="string"?r.innerHTML=t:t instanceof HTMLElement&&r.appendChild(t.cloneNode(!0)),e.appendChild(r),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu")||!o.subMenu)return;const w=g(o.subMenu,n),d=v(w,n,l,t);d.classList.add("tbw-context-submenu"),d.style.position="absolute",d.style.left="100%",d.style.top="0",e.style.position="relative",e.appendChild(d)}),e.addEventListener("mouseleave",()=>{const u=e.querySelector(".tbw-context-menu");u&&u.remove()})}!a&&o.action&&!o.subMenu&&e.addEventListener("click",r=>{r.stopPropagation(),l(o)}),i.appendChild(e)}return i}function M(s,n,l){s.style.position="fixed",s.style.left=`${n}px`,s.style.top=`${l}px`,s.style.visibility="hidden",s.style.zIndex="10000";const t=s.getBoundingClientRect(),i=window.innerWidth,o=window.innerHeight;let e=n,a=l;n+t.width>i&&(e=n-t.width),l+t.height>o&&(a=l-t.height),e=Math.max(0,e),a=Math.max(0,a),s.style.left=`${e}px`,s.style.top=`${a}px`,s.style.visibility="visible"}let f=null,p=null,b=null,y=0;const E=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:s=>{s.grid?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:s=>{s.grid?.plugins?.export?.exportCsv?.()}}];class C extends h.BaseGridPlugin{name="contextMenu";get defaultConfig(){return{items:E}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(n){super.attach(n),this.installGlobalHandlers(),y++}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,this.uninstallGlobalHandlers()}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size"];copyGridStyles(n){const l=this.gridElement;if(!l)return;const t=getComputedStyle(l),i=[];for(const o of C.CSS_VARS_TO_COPY){const e=t.getPropertyValue(o).trim();e&&i.push(`${o}: ${e}`)}if(i.length>0){const o=n.getAttribute("style")||"";n.setAttribute("style",o+i.join("; ")+";")}}installGlobalHandlers(){!b&&typeof document<"u"&&typeof x=="string"&&x&&(b=document.createElement("style"),b.id="tbw-context-menu-styles",b.textContent=x,document.head.appendChild(b)),f||(f=()=>{document.querySelectorAll(".tbw-context-menu").forEach(l=>l.remove())},document.addEventListener("click",f)),p||(p=n=>{n.key==="Escape"&&document.querySelectorAll(".tbw-context-menu").forEach(t=>t.remove())},document.addEventListener("keydown",p))}uninstallGlobalHandlers(){y--,!(y>0)&&(f&&(document.removeEventListener("click",f),f=null),p&&(document.removeEventListener("keydown",p),p=null),b&&(b.remove(),b=null))}afterRender(){const n=this.gridElement;if(!n)return;const l=n.children[0];l&&l.getAttribute("data-context-menu-bound")!=="true"&&(l.setAttribute("data-context-menu-bound","true"),l.addEventListener("contextmenu",t=>{const i=t;i.preventDefault();const o=i.target,e=o.closest("[data-row][data-col]"),a=o.closest(".header-cell");let c;if(e){const u=parseInt(e.getAttribute("data-row")??"-1",10),w=parseInt(e.getAttribute("data-col")??"-1",10),d=this.columns[w],I=this.rows[u];c={row:I,rowIndex:u,column:d,columnIndex:w,field:d?.field??"",value:I?.[d?.field]??null,isHeader:!1,event:i}}else if(a){const u=parseInt(a.getAttribute("data-col")??"-1",10),w=this.columns[u];c={row:null,rowIndex:-1,column:w,columnIndex:u,field:w?.field??"",value:null,isHeader:!0,event:i}}else return;this.params=c,this.position={x:i.clientX,y:i.clientY};const r=g(this.config.items??E,c);r.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=v(r,c,u=>{u.action&&u.action(c),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),M(this.menuElement,i.clientX,i.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:c,items:r}))}))}showMenu(n,l,t){const i={row:t.row??null,rowIndex:t.rowIndex??-1,column:t.column??null,columnIndex:t.columnIndex??-1,field:t.field??"",value:t.value??null,isHeader:t.isHeader??!1,event:t.event??new MouseEvent("contextmenu")},o=g(this.config.items??E,i);this.menuElement&&this.menuElement.remove(),this.menuElement=v(o,i,e=>{e.action&&e.action(i),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),M(this.menuElement,n,l),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}m.ContextMenuPlugin=C,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(m,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("../../core/plugin/base-plugin"),require("../../core/types")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/types"],h):(m=typeof globalThis<"u"?globalThis:m||self,h(m.TbwGridPlugin_contextMenu={},m.TbwGrid,m.TbwGrid))})(this,(function(m,h,S){"use strict";const x="@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{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 g(s,n){return(typeof s=="function"?s(n):s).filter(t=>!(t.hidden===!0||typeof t.hidden=="function"&&t.hidden(n)))}function z(s,n){return s.disabled===!0?!0:typeof s.disabled=="function"?s.disabled(n):!1}function v(s,n,l,t=S.DEFAULT_GRID_ICONS.submenuArrow){const i=document.createElement("div");i.className="tbw-context-menu",i.setAttribute("role","menu");for(const o of s){if(o.separator){const r=document.createElement("div");r.className="tbw-context-menu-separator",r.setAttribute("role","separator"),i.appendChild(r);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",o.cssClass&&e.classList.add(o.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",o.id);const u=z(o,n);if(u&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),o.icon){const r=document.createElement("span");r.className="tbw-context-menu-icon",r.innerHTML=o.icon,e.appendChild(r)}const a=document.createElement("span");if(a.className="tbw-context-menu-label",a.textContent=o.name,e.appendChild(a),o.shortcut){const r=document.createElement("span");r.className="tbw-context-menu-shortcut",r.textContent=o.shortcut,e.appendChild(r)}if(o.subMenu?.length){const r=document.createElement("span");r.className="tbw-context-menu-arrow",typeof t=="string"?r.innerHTML=t:t instanceof HTMLElement&&r.appendChild(t.cloneNode(!0)),e.appendChild(r),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu")||!o.subMenu)return;const f=g(o.subMenu,n),d=v(f,n,l,t);d.classList.add("tbw-context-submenu"),d.style.position="absolute",d.style.left="100%",d.style.top="0",e.style.position="relative",e.appendChild(d)}),e.addEventListener("mouseleave",()=>{const c=e.querySelector(".tbw-context-menu");c&&c.remove()})}!u&&o.action&&!o.subMenu&&e.addEventListener("click",r=>{r.stopPropagation(),l(o)}),i.appendChild(e)}return i}function M(s,n,l){s.style.position="fixed",s.style.left=`${n}px`,s.style.top=`${l}px`,s.style.visibility="hidden",s.style.zIndex="10000";const t=s.getBoundingClientRect(),i=window.innerWidth,o=window.innerHeight;let e=n,u=l;n+t.width>i&&(e=n-t.width),l+t.height>o&&(u=l-t.height),e=Math.max(0,e),u=Math.max(0,u),s.style.left=`${e}px`,s.style.top=`${u}px`,s.style.visibility="visible"}let w=null,p=null,b=null,y=0;const E=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:s=>{s.grid?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:s=>{s.grid?.plugins?.export?.exportCsv?.()}}];class C extends h.BaseGridPlugin{name="contextMenu";get defaultConfig(){return{items:E}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(n){super.attach(n),this.installGlobalHandlers(),y++}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,this.uninstallGlobalHandlers()}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size"];copyGridStyles(n){const l=this.gridElement;if(!l)return;const t=getComputedStyle(l),i=[],o=t.getPropertyValue("color-scheme").trim();o&&i.push(`color-scheme: ${o}`);for(const e of C.CSS_VARS_TO_COPY){const u=t.getPropertyValue(e).trim();u&&i.push(`${e}: ${u}`)}if(i.length>0){const e=n.getAttribute("style")||"";n.setAttribute("style",e+i.join("; ")+";")}}installGlobalHandlers(){!b&&typeof document<"u"&&typeof x=="string"&&x&&(b=document.createElement("style"),b.id="tbw-context-menu-styles",b.textContent=x,document.head.appendChild(b)),w||(w=()=>{document.querySelectorAll(".tbw-context-menu").forEach(l=>l.remove())},document.addEventListener("click",w)),p||(p=n=>{n.key==="Escape"&&document.querySelectorAll(".tbw-context-menu").forEach(t=>t.remove())},document.addEventListener("keydown",p))}uninstallGlobalHandlers(){y--,!(y>0)&&(w&&(document.removeEventListener("click",w),w=null),p&&(document.removeEventListener("keydown",p),p=null),b&&(b.remove(),b=null))}afterRender(){const n=this.gridElement;if(!n)return;const l=n.children[0];l&&l.getAttribute("data-context-menu-bound")!=="true"&&(l.setAttribute("data-context-menu-bound","true"),l.addEventListener("contextmenu",t=>{const i=t;i.preventDefault();const o=i.target,e=o.closest("[data-row][data-col]"),u=o.closest(".header-cell");let a;if(e){const c=parseInt(e.getAttribute("data-row")??"-1",10),f=parseInt(e.getAttribute("data-col")??"-1",10),d=this.columns[f],I=this.rows[c];a={row:I,rowIndex:c,column:d,columnIndex:f,field:d?.field??"",value:I?.[d?.field]??null,isHeader:!1,event:i}}else if(u){const c=parseInt(u.getAttribute("data-col")??"-1",10),f=this.columns[c];a={row:null,rowIndex:-1,column:f,columnIndex:c,field:f?.field??"",value:null,isHeader:!0,event:i}}else return;this.params=a,this.position={x:i.clientX,y:i.clientY};const r=g(this.config.items??E,a);r.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=v(r,a,c=>{c.action&&c.action(a),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),M(this.menuElement,i.clientX,i.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:a,items:r}))}))}showMenu(n,l,t){const i={row:t.row??null,rowIndex:t.rowIndex??-1,column:t.column??null,columnIndex:t.columnIndex??-1,field:t.field??"",value:t.value??null,isHeader:t.isHeader??!1,event:t.event??new MouseEvent("contextmenu")},o=g(this.config.items??E,i);this.menuElement&&this.menuElement.remove(),this.menuElement=v(o,i,e=>{e.action&&e.action(i),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),M(this.menuElement,n,l),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}m.ContextMenuPlugin=C,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
2
2
  //# sourceMappingURL=context-menu.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-menu.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/context-menu/menu.ts","../../../../../libs/grid/src/lib/plugins/context-menu/ContextMenuPlugin.ts"],"sourcesContent":["/**\n * Context Menu Rendering Logic\n *\n * Pure functions for building and positioning context menus.\n */\n\nimport type { IconValue } from '../../core/types';\nimport { DEFAULT_GRID_ICONS } from '../../core/types';\nimport type { ContextMenuItem, ContextMenuParams } from './types';\n\n/**\n * Build the visible menu items by resolving dynamic items and filtering hidden ones.\n *\n * @param items - Menu items configuration (array or factory function)\n * @param params - Context menu parameters for evaluating dynamic properties\n * @returns Filtered array of visible menu items\n */\nexport function buildMenuItems(\n items: ContextMenuItem[] | ((params: ContextMenuParams) => ContextMenuItem[]),\n params: ContextMenuParams\n): ContextMenuItem[] {\n const menuItems = typeof items === 'function' ? items(params) : items;\n\n return menuItems.filter((item) => {\n if (item.hidden === true) return false;\n if (typeof item.hidden === 'function' && item.hidden(params)) return false;\n return true;\n });\n}\n\n/**\n * Check if a menu item is disabled.\n *\n * @param item - The menu item to check\n * @param params - Context menu parameters for evaluating dynamic disabled state\n * @returns True if the item is disabled\n */\nexport function isItemDisabled(item: ContextMenuItem, params: ContextMenuParams): boolean {\n if (item.disabled === true) return true;\n if (typeof item.disabled === 'function') return item.disabled(params);\n return false;\n}\n\n/**\n * Create the menu DOM element from a list of menu items.\n *\n * @param items - Array of menu items to render\n * @param params - Context menu parameters for evaluating dynamic properties\n * @param onAction - Callback when a menu item action is triggered\n * @param submenuArrow - Optional custom submenu arrow icon\n * @returns The created menu element\n */\nexport function createMenuElement(\n items: ContextMenuItem[],\n params: ContextMenuParams,\n onAction: (item: ContextMenuItem) => void,\n submenuArrow: IconValue = DEFAULT_GRID_ICONS.submenuArrow\n): HTMLElement {\n const menu = document.createElement('div');\n menu.className = 'tbw-context-menu';\n menu.setAttribute('role', 'menu');\n\n for (const item of items) {\n if (item.separator) {\n const separator = document.createElement('div');\n separator.className = 'tbw-context-menu-separator';\n separator.setAttribute('role', 'separator');\n menu.appendChild(separator);\n continue;\n }\n\n const menuItem = document.createElement('div');\n menuItem.className = 'tbw-context-menu-item';\n if (item.cssClass) menuItem.classList.add(item.cssClass);\n menuItem.setAttribute('role', 'menuitem');\n menuItem.setAttribute('data-id', item.id);\n\n const disabled = isItemDisabled(item, params);\n if (disabled) {\n menuItem.classList.add('disabled');\n menuItem.setAttribute('aria-disabled', 'true');\n }\n\n if (item.icon) {\n const icon = document.createElement('span');\n icon.className = 'tbw-context-menu-icon';\n icon.innerHTML = item.icon;\n menuItem.appendChild(icon);\n }\n\n const label = document.createElement('span');\n label.className = 'tbw-context-menu-label';\n label.textContent = item.name;\n menuItem.appendChild(label);\n\n if (item.shortcut) {\n const shortcut = document.createElement('span');\n shortcut.className = 'tbw-context-menu-shortcut';\n shortcut.textContent = item.shortcut;\n menuItem.appendChild(shortcut);\n }\n\n if (item.subMenu?.length) {\n const arrow = document.createElement('span');\n arrow.className = 'tbw-context-menu-arrow';\n // Use provided submenu arrow icon (string or HTMLElement)\n if (typeof submenuArrow === 'string') {\n arrow.innerHTML = submenuArrow;\n } else if (submenuArrow instanceof HTMLElement) {\n arrow.appendChild(submenuArrow.cloneNode(true));\n }\n menuItem.appendChild(arrow);\n\n // Add submenu on hover\n menuItem.addEventListener('mouseenter', () => {\n const existingSubMenu = menuItem.querySelector('.tbw-context-menu');\n if (existingSubMenu) return;\n if (!item.subMenu) return;\n\n const subMenuItems = buildMenuItems(item.subMenu, params);\n const subMenu = createMenuElement(subMenuItems, params, onAction, submenuArrow);\n subMenu.classList.add('tbw-context-submenu');\n subMenu.style.position = 'absolute';\n subMenu.style.left = '100%';\n subMenu.style.top = '0';\n menuItem.style.position = 'relative';\n menuItem.appendChild(subMenu);\n });\n\n menuItem.addEventListener('mouseleave', () => {\n const subMenu = menuItem.querySelector('.tbw-context-menu');\n if (subMenu) subMenu.remove();\n });\n }\n\n if (!disabled && item.action && !item.subMenu) {\n menuItem.addEventListener('click', (e) => {\n e.stopPropagation();\n onAction(item);\n });\n }\n\n menu.appendChild(menuItem);\n }\n\n return menu;\n}\n\n/**\n * Position the menu at the given viewport coordinates.\n * Menu is rendered in document.body with fixed positioning for top-layer behavior.\n *\n * @param menu - The menu element to position\n * @param x - Desired X coordinate (viewport)\n * @param y - Desired Y coordinate (viewport)\n */\nexport function positionMenu(menu: HTMLElement, x: number, y: number): void {\n // Use fixed positioning for top-layer behavior\n menu.style.position = 'fixed';\n menu.style.left = `${x}px`;\n menu.style.top = `${y}px`;\n menu.style.visibility = 'hidden';\n menu.style.zIndex = '10000';\n\n // Force layout to get dimensions\n const menuRect = menu.getBoundingClientRect();\n\n // Calculate visible area within viewport\n const viewportWidth = window.innerWidth;\n const viewportHeight = window.innerHeight;\n\n let left = x;\n let top = y;\n\n // Check if menu overflows right edge of viewport\n if (x + menuRect.width > viewportWidth) {\n left = x - menuRect.width;\n }\n // Check if menu overflows bottom edge of viewport\n if (y + menuRect.height > viewportHeight) {\n top = y - menuRect.height;\n }\n\n // Ensure we don't go negative\n left = Math.max(0, left);\n top = Math.max(0, top);\n\n menu.style.left = `${left}px`;\n menu.style.top = `${top}px`;\n menu.style.visibility = 'visible';\n}\n","/**\n * Context Menu Plugin (Class-based)\n *\n * Provides right-click context menu functionality for tbw-grid.\n * Supports custom menu items, submenus, icons, shortcuts, and dynamic item generation.\n */\n\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport contextMenuStyles from './context-menu.css?inline';\nimport { buildMenuItems, createMenuElement, positionMenu } from './menu';\nimport type { ContextMenuConfig, ContextMenuItem, ContextMenuParams } from './types';\n\n/** Global click handler reference for cleanup */\nlet globalClickHandler: ((e: Event) => void) | null = null;\n/** Global keydown handler reference for cleanup */\nlet globalKeydownHandler: ((e: KeyboardEvent) => void) | null = null;\n/** Global stylesheet for context menu (injected once) */\nlet globalStyleSheet: HTMLStyleElement | null = null;\n/** Reference count for instances using global handlers */\nlet globalHandlerRefCount = 0;\n\n/** Default menu items when none are configured */\nconst defaultItems: ContextMenuItem[] = [\n {\n id: 'copy',\n name: 'Copy',\n shortcut: 'Ctrl+C',\n action: (params) => {\n const grid = (params as ContextMenuParams & { grid?: { plugins?: { clipboard?: { copy?: () => void } } } }).grid;\n grid?.plugins?.clipboard?.copy?.();\n },\n },\n { separator: true, id: 'sep1', name: '' },\n {\n id: 'export-csv',\n name: 'Export CSV',\n action: (params) => {\n const grid = (params as ContextMenuParams & { grid?: { plugins?: { export?: { exportCsv?: () => void } } } })\n .grid;\n grid?.plugins?.export?.exportCsv?.();\n },\n },\n];\n\n/**\n * Context Menu Plugin for tbw-grid\n *\n * Adds a customizable right-click menu to grid cells. Build anything from simple\n * copy/paste actions to complex nested menus with conditional visibility, icons,\n * and keyboard shortcuts.\n *\n * ## Installation\n *\n * ```ts\n * import { ContextMenuPlugin } from '@toolbox-web/grid/plugins/context-menu';\n * ```\n *\n * ## Menu Item Structure\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `id` | `string` | Unique item identifier |\n * | `name` | `string` | Display label |\n * | `icon` | `string` | Icon class or HTML |\n * | `shortcut` | `string` | Keyboard shortcut hint |\n * | `action` | `(params) => void` | Click handler |\n * | `disabled` | `boolean \\| (params) => boolean` | Disable condition |\n * | `visible` | `boolean \\| (params) => boolean` | Visibility condition |\n * | `items` | `MenuItem[]` | Submenu items |\n * | `separator` | `boolean` | Create a divider line |\n *\n * ## Menu Context (params)\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `rowIndex` | `number` | Clicked row index |\n * | `colIndex` | `number` | Clicked column index |\n * | `field` | `string` | Column field name |\n * | `value` | `any` | Cell value |\n * | `row` | `any` | Full row data |\n * | `column` | `ColumnConfig` | Column configuration |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-context-menu-bg` | `var(--tbw-color-panel-bg)` | Menu background |\n * | `--tbw-context-menu-fg` | `var(--tbw-color-fg)` | Menu text color |\n * | `--tbw-context-menu-hover` | `var(--tbw-color-row-hover)` | Item hover background |\n *\n * @example Basic Context Menu\n * ```ts\n * import '@toolbox-web/grid';\n * import { ContextMenuPlugin } from '@toolbox-web/grid/plugins/context-menu';\n *\n * grid.gridConfig = {\n * plugins: [\n * new ContextMenuPlugin({\n * items: [\n * { id: 'copy', name: 'Copy', shortcut: 'Ctrl+C', action: (ctx) => navigator.clipboard.writeText(ctx.value) },\n * { separator: true, id: 'sep1', name: '' },\n * { id: 'delete', name: 'Delete', action: (ctx) => removeRow(ctx.rowIndex) },\n * ],\n * }),\n * ],\n * };\n * ```\n *\n * @example Conditional Menu Items\n * ```ts\n * new ContextMenuPlugin({\n * items: [\n * { id: 'edit', name: 'Edit', visible: (ctx) => ctx.column.editable === true },\n * { id: 'delete', name: 'Delete', disabled: (ctx) => ctx.row.locked === true },\n * ],\n * })\n * ```\n *\n * @see {@link ContextMenuConfig} for configuration options\n * @see {@link ContextMenuItem} for menu item structure\n * @see {@link ContextMenuParams} for action callback parameters\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ContextMenuPlugin extends BaseGridPlugin<ContextMenuConfig> {\n /** @internal */\n readonly name = 'contextMenu';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ContextMenuConfig> {\n return {\n items: defaultItems,\n };\n }\n\n // #region Internal State\n private isOpen = false;\n private position = { x: 0, y: 0 };\n private params: ContextMenuParams | null = null;\n private menuElement: HTMLElement | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n this.installGlobalHandlers();\n globalHandlerRefCount++;\n }\n\n /** @internal */\n override detach(): void {\n if (this.menuElement) {\n this.menuElement.remove();\n this.menuElement = null;\n }\n this.isOpen = false;\n this.params = null;\n this.uninstallGlobalHandlers();\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * CSS variables to copy from the grid element to the context menu.\n * Includes both base variables and context-menu specific overrides.\n */\n private static readonly CSS_VARS_TO_COPY = [\n // Base palette (for themes that only set base vars)\n '--tbw-color-panel-bg',\n '--tbw-color-fg',\n '--tbw-color-fg-muted',\n '--tbw-color-border',\n '--tbw-color-row-hover',\n '--tbw-color-shadow',\n '--tbw-color-danger',\n '--tbw-border-radius',\n '--tbw-font-family',\n '--tbw-font-size-sm',\n '--tbw-font-size-xs',\n '--tbw-font-size-2xs',\n '--tbw-spacing-xs',\n '--tbw-icon-size',\n '--tbw-menu-min-width',\n '--tbw-menu-item-padding',\n '--tbw-menu-item-gap',\n // Context menu specific overrides\n '--tbw-context-menu-bg',\n '--tbw-context-menu-fg',\n '--tbw-context-menu-border',\n '--tbw-context-menu-radius',\n '--tbw-context-menu-shadow',\n '--tbw-context-menu-hover',\n '--tbw-context-menu-danger',\n '--tbw-context-menu-muted',\n '--tbw-context-menu-min-width',\n '--tbw-context-menu-font-size',\n '--tbw-context-menu-font-family',\n '--tbw-context-menu-item-padding',\n '--tbw-context-menu-item-gap',\n '--tbw-context-menu-icon-size',\n '--tbw-context-menu-shortcut-size',\n '--tbw-context-menu-arrow-size',\n ];\n\n /**\n * Copy CSS custom properties from the grid element to the menu element.\n * This allows the context menu (appended to document.body) to inherit\n * theme variables set on tbw-grid.\n */\n private copyGridStyles(menuElement: HTMLElement): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const computed = getComputedStyle(gridEl);\n const styles: string[] = [];\n\n for (const varName of ContextMenuPlugin.CSS_VARS_TO_COPY) {\n const value = computed.getPropertyValue(varName).trim();\n if (value) {\n styles.push(`${varName}: ${value}`);\n }\n }\n\n if (styles.length > 0) {\n // Append to existing inline styles (don't overwrite)\n const existing = menuElement.getAttribute('style') || '';\n menuElement.setAttribute('style', existing + styles.join('; ') + ';');\n }\n }\n\n private installGlobalHandlers(): void {\n // Inject global stylesheet for context menu (once)\n // Only inject if we have valid CSS text (Vite's ?inline import)\n // When importing from source without Vite, the import is a module object, not a string\n if (\n !globalStyleSheet &&\n typeof document !== 'undefined' &&\n typeof contextMenuStyles === 'string' &&\n contextMenuStyles\n ) {\n globalStyleSheet = document.createElement('style');\n globalStyleSheet.id = 'tbw-context-menu-styles';\n globalStyleSheet.textContent = contextMenuStyles;\n document.head.appendChild(globalStyleSheet);\n }\n\n // Close menu on click outside\n if (!globalClickHandler) {\n globalClickHandler = () => {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n };\n document.addEventListener('click', globalClickHandler);\n }\n\n // Close on escape\n if (!globalKeydownHandler) {\n globalKeydownHandler = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n }\n };\n document.addEventListener('keydown', globalKeydownHandler);\n }\n }\n\n /**\n * Clean up global handlers when the last instance detaches.\n * Uses reference counting to ensure handlers persist while any grid uses the plugin.\n */\n private uninstallGlobalHandlers(): void {\n globalHandlerRefCount--;\n if (globalHandlerRefCount > 0) return;\n\n // Last instance - clean up all global resources\n if (globalClickHandler) {\n document.removeEventListener('click', globalClickHandler);\n globalClickHandler = null;\n }\n if (globalKeydownHandler) {\n document.removeEventListener('keydown', globalKeydownHandler);\n globalKeydownHandler = null;\n }\n if (globalStyleSheet) {\n globalStyleSheet.remove();\n globalStyleSheet = null;\n }\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override afterRender(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const container = gridEl.children[0];\n if (!container) return;\n\n // Check if handler already attached\n if (container.getAttribute('data-context-menu-bound') === 'true') return;\n container.setAttribute('data-context-menu-bound', 'true');\n\n container.addEventListener('contextmenu', (e: Event) => {\n const event = e as MouseEvent;\n event.preventDefault();\n\n const target = event.target as HTMLElement;\n const cell = target.closest('[data-row][data-col]');\n const header = target.closest('.header-cell');\n\n let params: ContextMenuParams;\n\n if (cell) {\n const rowIndex = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n const column = this.columns[colIndex];\n const row = this.rows[rowIndex];\n\n params = {\n row,\n rowIndex,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: row?.[column?.field as keyof typeof row] ?? null,\n isHeader: false,\n event,\n };\n } else if (header) {\n const colIndex = parseInt(header.getAttribute('data-col') ?? '-1', 10);\n const column = this.columns[colIndex];\n\n params = {\n row: null,\n rowIndex: -1,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: null,\n isHeader: true,\n event,\n };\n } else {\n return;\n }\n\n this.params = params;\n this.position = { x: event.clientX, y: event.clientY };\n\n const items = buildMenuItems(this.config.items ?? defaultItems, params);\n if (!items.length) return;\n\n if (this.menuElement) {\n this.menuElement.remove();\n }\n\n this.menuElement = createMenuElement(\n items,\n params,\n (item) => {\n if (item.action) {\n item.action(params);\n }\n this.menuElement?.remove();\n this.menuElement = null;\n this.isOpen = false;\n },\n this.gridIcons.submenuArrow,\n );\n\n document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, event.clientX, event.clientY);\n this.isOpen = true;\n\n this.emit('context-menu-open', { params, items });\n });\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Programmatically show the context menu at the specified position.\n * @param x - X coordinate\n * @param y - Y coordinate\n * @param params - Partial context menu parameters\n */\n showMenu(x: number, y: number, params: Partial<ContextMenuParams>): void {\n const fullParams: ContextMenuParams = {\n row: params.row ?? null,\n rowIndex: params.rowIndex ?? -1,\n column: params.column ?? null,\n columnIndex: params.columnIndex ?? -1,\n field: params.field ?? '',\n value: params.value ?? null,\n isHeader: params.isHeader ?? false,\n event: params.event ?? new MouseEvent('contextmenu'),\n };\n\n const items = buildMenuItems(this.config.items ?? defaultItems, fullParams);\n\n if (this.menuElement) {\n this.menuElement.remove();\n }\n\n this.menuElement = createMenuElement(\n items,\n fullParams,\n (item) => {\n if (item.action) item.action(fullParams);\n this.menuElement?.remove();\n this.menuElement = null;\n this.isOpen = false;\n },\n this.gridIcons.submenuArrow,\n );\n\n document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, x, y);\n this.isOpen = true;\n }\n\n /**\n * Hide the context menu.\n */\n hideMenu(): void {\n if (this.menuElement) {\n this.menuElement.remove();\n this.menuElement = null;\n this.isOpen = false;\n }\n }\n\n /**\n * Check if the context menu is currently open.\n * @returns Whether the menu is open\n */\n isMenuOpen(): boolean {\n return this.isOpen;\n }\n // #endregion\n\n // Styles are injected globally via installGlobalHandlers() since menu renders in document.body\n}\n"],"names":["buildMenuItems","items","params","item","isItemDisabled","createMenuElement","onAction","submenuArrow","DEFAULT_GRID_ICONS","menu","separator","menuItem","disabled","icon","label","shortcut","arrow","subMenuItems","subMenu","e","positionMenu","x","y","menuRect","viewportWidth","viewportHeight","left","top","globalClickHandler","globalKeydownHandler","globalStyleSheet","globalHandlerRefCount","defaultItems","ContextMenuPlugin","BaseGridPlugin","grid","menuElement","gridEl","computed","styles","varName","value","existing","contextMenuStyles","container","event","target","cell","header","rowIndex","colIndex","column","row","fullParams"],"mappings":"gkEAiBO,SAASA,EACdC,EACAC,EACmB,CAGnB,OAFkB,OAAOD,GAAU,WAAaA,EAAMC,CAAM,EAAID,GAE/C,OAAQE,GACnB,EAAAA,EAAK,SAAW,IAChB,OAAOA,EAAK,QAAW,YAAcA,EAAK,OAAOD,CAAM,EAE5D,CACH,CASO,SAASE,EAAeD,EAAuBD,E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W,EACpCkB,EAAa,KAAK,YAAayB,EAAM,QAASA,EAAM,OAAO,EAC3D,KAAK,OAAS,GAEd,KAAK,KAAK,oBAAqB,CAAE,OAAA3C,EAAQ,MAAAD,EAAO,EAClD,CAAC,EACH,CAWA,SAASoB,EAAWC,EAAWpB,EAA0C,CACvE,MAAMmD,EAAgC,CACpC,IAAKnD,EAAO,KAAO,KACnB,SAAUA,EAAO,UAAY,GAC7B,OAAQA,EAAO,QAAU,KACzB,YAAaA,EAAO,aAAe,GACnC,MAAOA,EAAO,OAAS,GACvB,MAAOA,EAAO,OAAS,KACvB,SAAUA,EAAO,UAAY,GAC7B,MAAOA,EAAO,OAAS,IAAI,WAAW,aAAa,CAAA,EAG/CD,EAAQD,EAAe,KAAK,OAAO,OAASgC,EAAcqB,CAAU,EAEtE,KAAK,aACP,KAAK,YAAY,OAAA,EAGnB,KAAK,YAAchD,EACjBJ,EACAoD,EACClD,GAAS,CACJA,EAAK,QAAQA,EAAK,OAAOkD,CAAU,EACvC,KAAK,aAAa,OAAA,EAClB,KAAK,YAAc,KACnB,KAAK,OAAS,EAChB,EACA,KAAK,UAAU,YAAA,EAGjB,SAAS,KAAK,YAAY,KAAK,WAAW,EAC1C,KAAK,eAAe,KAAK,WAAW,EACpCjC,EAAa,KAAK,YAAaC,EAAGC,CAAC,EACnC,KAAK,OAAS,EAChB,CAKA,UAAiB,CACX,KAAK,cACP,KAAK,YAAY,OAAA,EACjB,KAAK,YAAc,KACnB,KAAK,OAAS,GAElB,CAMA,YAAsB,CACpB,OAAO,KAAK,MACd,CAIF"}
1
+ {"version":3,"file":"context-menu.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/context-menu/menu.ts","../../../../../libs/grid/src/lib/plugins/context-menu/ContextMenuPlugin.ts"],"sourcesContent":["/**\n * Context Menu Rendering Logic\n *\n * Pure functions for building and positioning context menus.\n */\n\nimport type { IconValue } from '../../core/types';\nimport { DEFAULT_GRID_ICONS } from '../../core/types';\nimport type { ContextMenuItem, ContextMenuParams } from './types';\n\n/**\n * Build the visible menu items by resolving dynamic items and filtering hidden ones.\n *\n * @param items - Menu items configuration (array or factory function)\n * @param params - Context menu parameters for evaluating dynamic properties\n * @returns Filtered array of visible menu items\n */\nexport function buildMenuItems(\n items: ContextMenuItem[] | ((params: ContextMenuParams) => ContextMenuItem[]),\n params: ContextMenuParams\n): ContextMenuItem[] {\n const menuItems = typeof items === 'function' ? items(params) : items;\n\n return menuItems.filter((item) => {\n if (item.hidden === true) return false;\n if (typeof item.hidden === 'function' && item.hidden(params)) return false;\n return true;\n });\n}\n\n/**\n * Check if a menu item is disabled.\n *\n * @param item - The menu item to check\n * @param params - Context menu parameters for evaluating dynamic disabled state\n * @returns True if the item is disabled\n */\nexport function isItemDisabled(item: ContextMenuItem, params: ContextMenuParams): boolean {\n if (item.disabled === true) return true;\n if (typeof item.disabled === 'function') return item.disabled(params);\n return false;\n}\n\n/**\n * Create the menu DOM element from a list of menu items.\n *\n * @param items - Array of menu items to render\n * @param params - Context menu parameters for evaluating dynamic properties\n * @param onAction - Callback when a menu item action is triggered\n * @param submenuArrow - Optional custom submenu arrow icon\n * @returns The created menu element\n */\nexport function createMenuElement(\n items: ContextMenuItem[],\n params: ContextMenuParams,\n onAction: (item: ContextMenuItem) => void,\n submenuArrow: IconValue = DEFAULT_GRID_ICONS.submenuArrow\n): HTMLElement {\n const menu = document.createElement('div');\n menu.className = 'tbw-context-menu';\n menu.setAttribute('role', 'menu');\n\n for (const item of items) {\n if (item.separator) {\n const separator = document.createElement('div');\n separator.className = 'tbw-context-menu-separator';\n separator.setAttribute('role', 'separator');\n menu.appendChild(separator);\n continue;\n }\n\n const menuItem = document.createElement('div');\n menuItem.className = 'tbw-context-menu-item';\n if (item.cssClass) menuItem.classList.add(item.cssClass);\n menuItem.setAttribute('role', 'menuitem');\n menuItem.setAttribute('data-id', item.id);\n\n const disabled = isItemDisabled(item, params);\n if (disabled) {\n menuItem.classList.add('disabled');\n menuItem.setAttribute('aria-disabled', 'true');\n }\n\n if (item.icon) {\n const icon = document.createElement('span');\n icon.className = 'tbw-context-menu-icon';\n icon.innerHTML = item.icon;\n menuItem.appendChild(icon);\n }\n\n const label = document.createElement('span');\n label.className = 'tbw-context-menu-label';\n label.textContent = item.name;\n menuItem.appendChild(label);\n\n if (item.shortcut) {\n const shortcut = document.createElement('span');\n shortcut.className = 'tbw-context-menu-shortcut';\n shortcut.textContent = item.shortcut;\n menuItem.appendChild(shortcut);\n }\n\n if (item.subMenu?.length) {\n const arrow = document.createElement('span');\n arrow.className = 'tbw-context-menu-arrow';\n // Use provided submenu arrow icon (string or HTMLElement)\n if (typeof submenuArrow === 'string') {\n arrow.innerHTML = submenuArrow;\n } else if (submenuArrow instanceof HTMLElement) {\n arrow.appendChild(submenuArrow.cloneNode(true));\n }\n menuItem.appendChild(arrow);\n\n // Add submenu on hover\n menuItem.addEventListener('mouseenter', () => {\n const existingSubMenu = menuItem.querySelector('.tbw-context-menu');\n if (existingSubMenu) return;\n if (!item.subMenu) return;\n\n const subMenuItems = buildMenuItems(item.subMenu, params);\n const subMenu = createMenuElement(subMenuItems, params, onAction, submenuArrow);\n subMenu.classList.add('tbw-context-submenu');\n subMenu.style.position = 'absolute';\n subMenu.style.left = '100%';\n subMenu.style.top = '0';\n menuItem.style.position = 'relative';\n menuItem.appendChild(subMenu);\n });\n\n menuItem.addEventListener('mouseleave', () => {\n const subMenu = menuItem.querySelector('.tbw-context-menu');\n if (subMenu) subMenu.remove();\n });\n }\n\n if (!disabled && item.action && !item.subMenu) {\n menuItem.addEventListener('click', (e) => {\n e.stopPropagation();\n onAction(item);\n });\n }\n\n menu.appendChild(menuItem);\n }\n\n return menu;\n}\n\n/**\n * Position the menu at the given viewport coordinates.\n * Menu is rendered in document.body with fixed positioning for top-layer behavior.\n *\n * @param menu - The menu element to position\n * @param x - Desired X coordinate (viewport)\n * @param y - Desired Y coordinate (viewport)\n */\nexport function positionMenu(menu: HTMLElement, x: number, y: number): void {\n // Use fixed positioning for top-layer behavior\n menu.style.position = 'fixed';\n menu.style.left = `${x}px`;\n menu.style.top = `${y}px`;\n menu.style.visibility = 'hidden';\n menu.style.zIndex = '10000';\n\n // Force layout to get dimensions\n const menuRect = menu.getBoundingClientRect();\n\n // Calculate visible area within viewport\n const viewportWidth = window.innerWidth;\n const viewportHeight = window.innerHeight;\n\n let left = x;\n let top = y;\n\n // Check if menu overflows right edge of viewport\n if (x + menuRect.width > viewportWidth) {\n left = x - menuRect.width;\n }\n // Check if menu overflows bottom edge of viewport\n if (y + menuRect.height > viewportHeight) {\n top = y - menuRect.height;\n }\n\n // Ensure we don't go negative\n left = Math.max(0, left);\n top = Math.max(0, top);\n\n menu.style.left = `${left}px`;\n menu.style.top = `${top}px`;\n menu.style.visibility = 'visible';\n}\n","/**\n * Context Menu Plugin (Class-based)\n *\n * Provides right-click context menu functionality for tbw-grid.\n * Supports custom menu items, submenus, icons, shortcuts, and dynamic item generation.\n */\n\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport contextMenuStyles from './context-menu.css?inline';\nimport { buildMenuItems, createMenuElement, positionMenu } from './menu';\nimport type { ContextMenuConfig, ContextMenuItem, ContextMenuParams } from './types';\n\n/** Global click handler reference for cleanup */\nlet globalClickHandler: ((e: Event) => void) | null = null;\n/** Global keydown handler reference for cleanup */\nlet globalKeydownHandler: ((e: KeyboardEvent) => void) | null = null;\n/** Global stylesheet for context menu (injected once) */\nlet globalStyleSheet: HTMLStyleElement | null = null;\n/** Reference count for instances using global handlers */\nlet globalHandlerRefCount = 0;\n\n/** Default menu items when none are configured */\nconst defaultItems: ContextMenuItem[] = [\n {\n id: 'copy',\n name: 'Copy',\n shortcut: 'Ctrl+C',\n action: (params) => {\n const grid = (params as ContextMenuParams & { grid?: { plugins?: { clipboard?: { copy?: () => void } } } }).grid;\n grid?.plugins?.clipboard?.copy?.();\n },\n },\n { separator: true, id: 'sep1', name: '' },\n {\n id: 'export-csv',\n name: 'Export CSV',\n action: (params) => {\n const grid = (params as ContextMenuParams & { grid?: { plugins?: { export?: { exportCsv?: () => void } } } })\n .grid;\n grid?.plugins?.export?.exportCsv?.();\n },\n },\n];\n\n/**\n * Context Menu Plugin for tbw-grid\n *\n * Adds a customizable right-click menu to grid cells. Build anything from simple\n * copy/paste actions to complex nested menus with conditional visibility, icons,\n * and keyboard shortcuts.\n *\n * ## Installation\n *\n * ```ts\n * import { ContextMenuPlugin } from '@toolbox-web/grid/plugins/context-menu';\n * ```\n *\n * ## Menu Item Structure\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `id` | `string` | Unique item identifier |\n * | `name` | `string` | Display label |\n * | `icon` | `string` | Icon class or HTML |\n * | `shortcut` | `string` | Keyboard shortcut hint |\n * | `action` | `(params) => void` | Click handler |\n * | `disabled` | `boolean \\| (params) => boolean` | Disable condition |\n * | `visible` | `boolean \\| (params) => boolean` | Visibility condition |\n * | `items` | `MenuItem[]` | Submenu items |\n * | `separator` | `boolean` | Create a divider line |\n *\n * ## Menu Context (params)\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `rowIndex` | `number` | Clicked row index |\n * | `colIndex` | `number` | Clicked column index |\n * | `field` | `string` | Column field name |\n * | `value` | `any` | Cell value |\n * | `row` | `any` | Full row data |\n * | `column` | `ColumnConfig` | Column configuration |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-context-menu-bg` | `var(--tbw-color-panel-bg)` | Menu background |\n * | `--tbw-context-menu-fg` | `var(--tbw-color-fg)` | Menu text color |\n * | `--tbw-context-menu-hover` | `var(--tbw-color-row-hover)` | Item hover background |\n *\n * @example Basic Context Menu\n * ```ts\n * import '@toolbox-web/grid';\n * import { ContextMenuPlugin } from '@toolbox-web/grid/plugins/context-menu';\n *\n * grid.gridConfig = {\n * plugins: [\n * new ContextMenuPlugin({\n * items: [\n * { id: 'copy', name: 'Copy', shortcut: 'Ctrl+C', action: (ctx) => navigator.clipboard.writeText(ctx.value) },\n * { separator: true, id: 'sep1', name: '' },\n * { id: 'delete', name: 'Delete', action: (ctx) => removeRow(ctx.rowIndex) },\n * ],\n * }),\n * ],\n * };\n * ```\n *\n * @example Conditional Menu Items\n * ```ts\n * new ContextMenuPlugin({\n * items: [\n * { id: 'edit', name: 'Edit', visible: (ctx) => ctx.column.editable === true },\n * { id: 'delete', name: 'Delete', disabled: (ctx) => ctx.row.locked === true },\n * ],\n * })\n * ```\n *\n * @see {@link ContextMenuConfig} for configuration options\n * @see {@link ContextMenuItem} for menu item structure\n * @see {@link ContextMenuParams} for action callback parameters\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ContextMenuPlugin extends BaseGridPlugin<ContextMenuConfig> {\n /** @internal */\n readonly name = 'contextMenu';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ContextMenuConfig> {\n return {\n items: defaultItems,\n };\n }\n\n // #region Internal State\n private isOpen = false;\n private position = { x: 0, y: 0 };\n private params: ContextMenuParams | null = null;\n private menuElement: HTMLElement | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n this.installGlobalHandlers();\n globalHandlerRefCount++;\n }\n\n /** @internal */\n override detach(): void {\n if (this.menuElement) {\n this.menuElement.remove();\n this.menuElement = null;\n }\n this.isOpen = false;\n this.params = null;\n this.uninstallGlobalHandlers();\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * CSS variables to copy from the grid element to the context menu.\n * Includes both base variables and context-menu specific overrides.\n */\n private static readonly CSS_VARS_TO_COPY = [\n // Base palette (for themes that only set base vars)\n '--tbw-color-panel-bg',\n '--tbw-color-fg',\n '--tbw-color-fg-muted',\n '--tbw-color-border',\n '--tbw-color-row-hover',\n '--tbw-color-shadow',\n '--tbw-color-danger',\n '--tbw-border-radius',\n '--tbw-font-family',\n '--tbw-font-size-sm',\n '--tbw-font-size-xs',\n '--tbw-font-size-2xs',\n '--tbw-spacing-xs',\n '--tbw-icon-size',\n '--tbw-menu-min-width',\n '--tbw-menu-item-padding',\n '--tbw-menu-item-gap',\n // Context menu specific overrides\n '--tbw-context-menu-bg',\n '--tbw-context-menu-fg',\n '--tbw-context-menu-border',\n '--tbw-context-menu-radius',\n '--tbw-context-menu-shadow',\n '--tbw-context-menu-hover',\n '--tbw-context-menu-danger',\n '--tbw-context-menu-muted',\n '--tbw-context-menu-min-width',\n '--tbw-context-menu-font-size',\n '--tbw-context-menu-font-family',\n '--tbw-context-menu-item-padding',\n '--tbw-context-menu-item-gap',\n '--tbw-context-menu-icon-size',\n '--tbw-context-menu-shortcut-size',\n '--tbw-context-menu-arrow-size',\n ];\n\n /**\n * Copy CSS custom properties from the grid element to the menu element.\n * This allows the context menu (appended to document.body) to inherit\n * theme variables set on tbw-grid.\n */\n private copyGridStyles(menuElement: HTMLElement): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const computed = getComputedStyle(gridEl);\n const styles: string[] = [];\n\n // Copy color-scheme so light-dark() can resolve in the context menu\n const colorScheme = computed.getPropertyValue('color-scheme').trim();\n if (colorScheme) {\n styles.push(`color-scheme: ${colorScheme}`);\n }\n\n for (const varName of ContextMenuPlugin.CSS_VARS_TO_COPY) {\n const value = computed.getPropertyValue(varName).trim();\n if (value) {\n styles.push(`${varName}: ${value}`);\n }\n }\n\n if (styles.length > 0) {\n // Append to existing inline styles (don't overwrite)\n const existing = menuElement.getAttribute('style') || '';\n menuElement.setAttribute('style', existing + styles.join('; ') + ';');\n }\n }\n\n private installGlobalHandlers(): void {\n // Inject global stylesheet for context menu (once)\n // Only inject if we have valid CSS text (Vite's ?inline import)\n // When importing from source without Vite, the import is a module object, not a string\n if (\n !globalStyleSheet &&\n typeof document !== 'undefined' &&\n typeof contextMenuStyles === 'string' &&\n contextMenuStyles\n ) {\n globalStyleSheet = document.createElement('style');\n globalStyleSheet.id = 'tbw-context-menu-styles';\n globalStyleSheet.textContent = contextMenuStyles;\n document.head.appendChild(globalStyleSheet);\n }\n\n // Close menu on click outside\n if (!globalClickHandler) {\n globalClickHandler = () => {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n };\n document.addEventListener('click', globalClickHandler);\n }\n\n // Close on escape\n if (!globalKeydownHandler) {\n globalKeydownHandler = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n }\n };\n document.addEventListener('keydown', globalKeydownHandler);\n }\n }\n\n /**\n * Clean up global handlers when the last instance detaches.\n * Uses reference counting to ensure handlers persist while any grid uses the plugin.\n */\n private uninstallGlobalHandlers(): void {\n globalHandlerRefCount--;\n if (globalHandlerRefCount > 0) return;\n\n // Last instance - clean up all global resources\n if (globalClickHandler) {\n document.removeEventListener('click', globalClickHandler);\n globalClickHandler = null;\n }\n if (globalKeydownHandler) {\n document.removeEventListener('keydown', globalKeydownHandler);\n globalKeydownHandler = null;\n }\n if (globalStyleSheet) {\n globalStyleSheet.remove();\n globalStyleSheet = null;\n }\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override afterRender(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const container = gridEl.children[0];\n if (!container) return;\n\n // Check if handler already attached\n if (container.getAttribute('data-context-menu-bound') === 'true') return;\n container.setAttribute('data-context-menu-bound', 'true');\n\n container.addEventListener('contextmenu', (e: Event) => {\n const event = e as MouseEvent;\n event.preventDefault();\n\n const target = event.target as HTMLElement;\n const cell = target.closest('[data-row][data-col]');\n const header = target.closest('.header-cell');\n\n let params: ContextMenuParams;\n\n if (cell) {\n const rowIndex = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n const column = this.columns[colIndex];\n const row = this.rows[rowIndex];\n\n params = {\n row,\n rowIndex,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: row?.[column?.field as keyof typeof row] ?? null,\n isHeader: false,\n event,\n };\n } else if (header) {\n const colIndex = parseInt(header.getAttribute('data-col') ?? '-1', 10);\n const column = this.columns[colIndex];\n\n params = {\n row: null,\n rowIndex: -1,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: null,\n isHeader: true,\n event,\n };\n } else {\n return;\n }\n\n this.params = params;\n this.position = { x: event.clientX, y: event.clientY };\n\n const items = buildMenuItems(this.config.items ?? defaultItems, params);\n if (!items.length) return;\n\n if (this.menuElement) {\n this.menuElement.remove();\n }\n\n this.menuElement = createMenuElement(\n items,\n params,\n (item) => {\n if (item.action) {\n item.action(params);\n }\n this.menuElement?.remove();\n this.menuElement = null;\n this.isOpen = false;\n },\n this.gridIcons.submenuArrow,\n );\n\n document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, event.clientX, event.clientY);\n this.isOpen = true;\n\n this.emit('context-menu-open', { params, items });\n });\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Programmatically show the context menu at the specified position.\n * @param x - X coordinate\n * @param y - Y coordinate\n * @param params - Partial context menu parameters\n */\n showMenu(x: number, y: number, params: Partial<ContextMenuParams>): void {\n const fullParams: ContextMenuParams = {\n row: params.row ?? null,\n rowIndex: params.rowIndex ?? -1,\n column: params.column ?? null,\n columnIndex: params.columnIndex ?? -1,\n field: params.field ?? '',\n value: params.value ?? null,\n isHeader: params.isHeader ?? false,\n event: params.event ?? new MouseEvent('contextmenu'),\n };\n\n const items = buildMenuItems(this.config.items ?? defaultItems, fullParams);\n\n if (this.menuElement) {\n this.menuElement.remove();\n }\n\n this.menuElement = createMenuElement(\n items,\n fullParams,\n (item) => {\n if (item.action) item.action(fullParams);\n this.menuElement?.remove();\n this.menuElement = null;\n this.isOpen = false;\n },\n this.gridIcons.submenuArrow,\n );\n\n document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, x, y);\n this.isOpen = true;\n }\n\n /**\n * Hide the context menu.\n */\n hideMenu(): void {\n if (this.menuElement) {\n this.menuElement.remove();\n this.menuElement = null;\n this.isOpen = false;\n }\n }\n\n /**\n * Check if the context menu is currently open.\n * @returns Whether the menu is open\n */\n isMenuOpen(): boolean {\n return this.isOpen;\n }\n // #endregion\n\n // Styles are injected globally via installGlobalHandlers() since menu renders in document.body\n}\n"],"names":["buildMenuItems","items","params","item","isItemDisabled","createMenuElement","onAction","submenuArrow","DEFAULT_GRID_ICONS","menu","separator","menuItem","disabled","icon","label","shortcut","arrow","subMenuItems","subMenu","e","positionMenu","x","y","menuRect","viewportWidth","viewportHeight","left","top","globalClickHandler","globalKeydownHandler","globalStyleSheet","globalHandlerRefCount","defaultItems","ContextMenuPlugin","BaseGridPlugin","grid","menuElement","gridEl","computed","styles","colorScheme","varName","value","existing","contextMenuStyles","container","event","target","cell","header","rowIndex","colIndex","column","row","fullParams"],"mappings":"gkEAiBO,SAASA,EACdC,EACAC,EACmB,CAGnB,OAFkB,OAAOD,GAAU,WAAaA,EAAMC,CAAM,EAAID,GAE/C,OAAQE,GACnB,EAAAA,EAAK,SAAW,IAChB,OAAOA,EAAK,QAAW,YAAcA,EAAK,OAAOD,CAAM,EAE5D,CACH,CASO,SAASE,EAAeD,EAAuBD,EAAoC,CACxF,OAAIC,EAAK,WAAa,GAAa,GAC/B,OAAOA,EAAK,UAAa,WAAmBA,EAAK,SAASD,CAAM,EAC7D,EACT,CAWO,SAASG,EACdJ,EACAC,EACAI,EACAC,EAA0BC,EAAAA,mBAAmB,aAChC,CACb,MAAMC,EAAO,SAAS,cAAc,KAAK,EACzCA,EAAK,UAAY,mBACjBA,EAAK,aAAa,OAAQ,MAAM,EAEhC,UAAWN,KAAQF,EAAO,CACxB,GAAIE,EAAK,UAAW,CAClB,MAAMO,EAAY,SAAS,cAAc,KAAK,EAC9CA,EAAU,UAAY,6BACtBA,EAAU,aAAa,OAAQ,WAAW,EAC1CD,EAAK,YAAYC,CAAS,EAC1B,QACF,CAEA,MAAMC,EAAW,SAAS,cAAc,KAAK,EAC7CA,EAA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GAC7B,MAAOA,EAAO,OAAS,IAAI,WAAW,aAAa,CAAA,EAG/CD,EAAQD,EAAe,KAAK,OAAO,OAASgC,EAAcsB,CAAU,EAEtE,KAAK,aACP,KAAK,YAAY,OAAA,EAGnB,KAAK,YAAcjD,EACjBJ,EACAqD,EACCnD,GAAS,CACJA,EAAK,QAAQA,EAAK,OAAOmD,CAAU,EACvC,KAAK,aAAa,OAAA,EAClB,KAAK,YAAc,KACnB,KAAK,OAAS,EAChB,EACA,KAAK,UAAU,YAAA,EAGjB,SAAS,KAAK,YAAY,KAAK,WAAW,EAC1C,KAAK,eAAe,KAAK,WAAW,EACpClC,EAAa,KAAK,YAAaC,EAAGC,CAAC,EACnC,KAAK,OAAS,EAChB,CAKA,UAAiB,CACX,KAAK,cACP,KAAK,YAAY,OAAA,EACjB,KAAK,YAAc,KACnB,KAAK,OAAS,GAElB,CAMA,YAAsB,CACpB,OAAO,KAAK,MACd,CAIF"}
@@ -1,2 +1,2 @@
1
- (function(E,v){typeof exports=="object"&&typeof module<"u"?v(exports,require("../../core/internal/row-animation"),require("../../core/plugin/base-plugin")):typeof define=="function"&&define.amd?define(["exports","../../core/internal/row-animation","../../core/plugin/base-plugin"],v):(E=typeof globalThis<"u"?globalThis:E||self,v(E.TbwGridPlugin_editing={},E.TbwGrid,E.TbwGrid))})(this,(function(E,v,P){"use strict";const A="@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-grid .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:calc(var(--tbw-row-height) + 2px);align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}}";function q(s){const e=s.options;return e?typeof e=="function"?e():e:[]}function O(s){return e=>{const i=s.editorParams,t=document.createElement("input");t.type="number",t.value=e.value!=null?String(e.value):"",i?.min!==void 0&&(t.min=String(i.min)),i?.max!==void 0&&(t.max=String(i.max)),i?.step!==void 0&&(t.step=String(i.step)),i?.placeholder&&(t.placeholder=i.placeholder);const r=()=>e.commit(t.value===""?null:Number(t.value));return t.addEventListener("blur",r),t.addEventListener("keydown",n=>{n.key==="Enter"&&r(),n.key==="Escape"&&e.cancel()}),t}}function D(){return s=>{const e=document.createElement("input");return e.type="checkbox",e.checked=!!s.value,e.addEventListener("change",()=>s.commit(e.checked)),e}}function I(s){return e=>{const i=s.editorParams,t=document.createElement("input");return t.type="date",e.value instanceof Date&&(t.valueAsDate=e.value),i?.min&&(t.min=i.min),i?.max&&(t.max=i.max),i?.placeholder&&(t.placeholder=i.placeholder),t.addEventListener("change",()=>e.commit(t.valueAsDate)),t.addEventListener("keydown",r=>{r.key==="Escape"&&e.cancel()}),t}}function G(s){return e=>{const i=s.editorParams,t=document.createElement("select");if(s.multi&&(t.multiple=!0),i?.includeEmpty){const o=document.createElement("option");o.value="",o.textContent=i.emptyLabel??"",t.appendChild(o)}q(s).forEach(o=>{const a=document.createElement("option");a.value=String(o.value),a.textContent=o.label,(s.multi&&Array.isArray(e.value)&&e.value.includes(o.value)||!s.multi&&e.value===o.value)&&(a.selected=!0),t.appendChild(a)});const n=()=>{if(s.multi){const o=Array.from(t.selectedOptions).map(a=>a.value);e.commit(o)}else e.commit(t.value)};return t.addEventListener("change",n),t.addEventListener("blur",n),t.addEventListener("keydown",o=>{o.key==="Escape"&&e.cancel()}),t}}function M(s){return e=>{const i=s.editorParams,t=document.createElement("input");return t.type="text",t.value=e.value!=null?String(e.value):"",i?.maxLength!==void 0&&(t.maxLength=i.maxLength),i?.pattern&&(t.pattern=i.pattern),i?.placeholder&&(t.placeholder=i.placeholder),t.addEventListener("blur",()=>e.commit(t.value)),t.addEventListener("keydown",r=>{r.key==="Enter"&&e.commit(t.value),r.key==="Escape"&&e.cancel()}),t}}function k(s){switch(s.type){case"number":return O(s);case"boolean":return D();case"date":return I(s);case"select":return G(s);default:return M(s)}}const _='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function x(s,e){if(e.editor)return e.editor;if(e.__editorTemplate)return"template";if(!e.type)return;const t=s.effectiveConfig?.typeDefaults;if(t?.[e.type]?.editor)return t[e.type].editor;const r=s.__frameworkAdapter;if(r?.getTypeDefault){const n=r.getTypeDefault(e.type);if(n?.editor)return n.editor}}function y(s){return!(typeof s!="string"||s==="__proto__"||s==="constructor"||s==="prototype")}function H(s){const e=(s.__editingCellCount??0)+1;s.__editingCellCount=e,s.setAttribute("data-has-editing","")}function N(s){s.__editingCellCount=0,s.removeAttribute("data-has-editing")}function C(s,e){return s instanceof HTMLInputElement?s.type==="checkbox"?s.checked:s.type==="number"?s.value===""?null:Number(s.value):s.type==="date"?s.valueAsDate:s.value:e?.type==="number"&&s.value!==""?Number(s.value):s.value}function L(s){}function $(s,e,i){const t=s.querySelector("input,textarea,select");t&&(t.addEventListener("blur",()=>{i(C(t,e))}),t instanceof HTMLInputElement&&t.type==="checkbox"?t.addEventListener("change",()=>i(t.checked)):t instanceof HTMLSelectElement&&t.addEventListener("change",()=>i(C(t,e))))}class j extends P.BaseGridPlugin{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>e===!0},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'}]};name="editing";styles=A;get defaultConfig(){return{editOn:"click"}}#e=-1;#s=-1;#r=new Map;#t=new Set;#n=new Set;#o=!1;attach(e){super.attach(e);const i=this.disconnectSignal,t=e;t._activeEditRows=-1,t._rowEditSnapshots=new Map,Object.defineProperty(e,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(e,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),e.resetChangedRows=r=>this.resetChangedRows(r),e.beginBulkEdit=(r,n)=>{n&&this.beginCellEdit(r,n)},document.addEventListener("keydown",r=>{r.key==="Escape"&&this.#e!==-1&&this.#i(this.#e,!0)},{capture:!0,signal:i}),document.addEventListener("mousedown",r=>{if(this.#e===-1)return;const n=t.findRenderedRowElement?.(this.#e);!n||(r.composedPath&&r.composedPath()||[]).includes(n)||queueMicrotask(()=>{this.#e!==-1&&this.#i(this.#e,!1)})},{signal:i})}detach(){this.#e=-1,this.#s=-1,this.#r.clear(),this.#t.clear(),this.#n.clear(),super.detach()}onCellClick(e){const i=this.grid,t=this.config.editOn??i.effectiveConfig?.editOn;if(t===!1||t==="manual"||t!=="click"&&t!=="dblclick")return!1;const r=e.originalEvent.type==="dblclick";if(t==="click"&&r||t==="dblclick"&&!r)return!1;const{rowIndex:n}=e;return i._columns?.some(a=>a.editable)?(e.originalEvent.stopPropagation(),this.beginBulkEdit(n),!0):!1}onKeyDown(e){const i=this.grid;if(e.key==="Escape"&&this.#e!==-1)return this.#i(this.#e,!0),!0;if(e.key===" "||e.key==="Spacebar"){const t=i._focusRow,r=i._focusCol;if(t>=0&&r>=0){const n=i._visibleColumns[r],o=i._rows[t];if(n?.editable&&n.type==="boolean"&&o){const a=n.field;if(y(a)){const c=!o[a];return this.#l(t,n,c,o),e.preventDefault(),this.requestRender(),!0}}}return!1}if(e.key==="Enter"&&!e.shiftKey){if(this.#e!==-1)return!1;const t=this.config.editOn??i.effectiveConfig?.editOn;if(t===!1||t==="manual")return!1;const r=i._focusRow,n=i._focusCol;if(r>=0&&i._columns?.some(a=>a.editable)){const a=i._visibleColumns[n],l=i._rows[r],c=a?.field??"",f=c&&l?l[c]:void 0,p=this.gridElement.querySelector(`[data-row="${r}"][data-col="${n}"]`),d=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:r,colIndex:n,field:c,value:f,row:l,cellEl:p,trigger:"keyboard",originalEvent:e}});this.gridElement.dispatchEvent(d);const h=new CustomEvent("activate-cell",{cancelable:!0,bubbles:!0,detail:{row:r,col:n}});return this.gridElement.dispatchEvent(h),d.defaultPrevented||h.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(r),!0)}return!1}return!1}processColumns(e){const i=this.grid,t=i.effectiveConfig?.typeDefaults,r=i.__frameworkAdapter;return!t&&!r?.getTypeDefault?e:e.map(n=>{if(!n.type)return n;let o;if(t?.[n.type]?.editorParams&&(o=t[n.type].editorParams),!o&&r?.getTypeDefault){const a=r.getTypeDefault(n.type);a?.editorParams&&(o=a.editorParams)}return o?{...n,editorParams:{...o,...n.editorParams}}:n})}afterRender(){const e=this.grid;if(this.#o&&(this.#o=!1,this.#u(e)),this.#n.size!==0)for(const i of this.#n){const[t,r]=i.split(":"),n=parseInt(t,10),o=parseInt(r,10),a=e.findRenderedRowElement?.(n);if(!a)continue;const l=a.querySelector(`.cell[data-col="${o}"]`);if(!l||l.classList.contains("editing"))continue;const c=e._rows[n],f=e._visibleColumns[o];c&&f&&this.#d(c,n,f,o,l,!0)}}onScrollRender(){this.afterRender()}get changedRows(){const e=[];for(const i of this.#t){const t=this.grid.getRow(i);t&&e.push(t)}return e}get changedRowIds(){return Array.from(this.#t)}get activeEditRow(){return this.#e}get activeEditCol(){return this.#s}isRowEditing(e){return this.#e===e}isCellEditing(e,i){return this.#n.has(`${e}:${i}`)}isRowChanged(e){const i=this.grid,t=i._rows[e];if(!t)return!1;try{const r=i.getRowId?.(t);return r?this.#t.has(r):!1}catch{return!1}}isRowChangedById(e){return this.#t.has(e)}resetChangedRows(e){const i=this.changedRows,t=this.changedRowIds;this.#t.clear(),this.#a(),e||this.emit("changed-rows-reset",{rows:i,ids:t}),this.grid._rowPool?.forEach(n=>n.classList.remove("changed"))}beginCellEdit(e,i){const t=this.grid,r=t._visibleColumns.findIndex(l=>l.field===i);if(r===-1||!t._visibleColumns[r]?.editable)return;const a=t.findRenderedRowElement?.(e)?.querySelector(`.cell[data-col="${r}"]`);a&&this.#f(e,r,a)}beginBulkEdit(e){const i=this.grid;if((this.config.editOn??i.effectiveConfig?.editOn)===!1||!i._columns?.some(a=>a.editable))return;const n=i.findRenderedRowElement?.(e);if(!n)return;const o=i._rows[e];this.#c(e,o),Array.from(n.children).forEach((a,l)=>{const c=i._visibleColumns[l];if(c?.editable){const f=a;f.classList.contains("editing")||this.#d(o,e,c,l,f,!0)}}),setTimeout(()=>{let a=n.querySelector(`.cell[data-col="${i._focusCol}"]`);if(a?.classList.contains("editing")||(a=n.querySelector(".cell.editing")),a?.classList.contains("editing")){const l=a.querySelector(_);try{l?.focus({preventScroll:!0})}catch{}}},0)}commitActiveRowEdit(){this.#e!==-1&&this.#i(this.#e,!1)}cancelActiveRowEdit(){this.#e!==-1&&this.#i(this.#e,!0)}#f(e,i,t){const r=this.grid,n=r._rows[e],o=r._visibleColumns[i];!n||!o?.editable||t.classList.contains("editing")||(this.#e!==e&&this.#c(e,n),this.#s=i,this.#d(n,e,o,i,t,!1))}#a(){const e=this.grid;e._activeEditRows=this.#e,e._rowEditSnapshots=this.#r}#c(e,i){this.#e!==e&&(this.#r.set(e,{...i}),this.#e=e,this.#a())}#i(e,i){if(this.#e!==e)return;const t=this.grid,r=this.#r.get(e),n=t._rows[e],o=t.findRenderedRowElement?.(e);let a;if(n)try{a=t.getRowId?.(n)}catch{}if(!i&&o&&n&&o.querySelectorAll(".cell.editing").forEach(c=>{const f=Number(c.getAttribute("data-col"));if(isNaN(f))return;const p=t._visibleColumns[f];if(!p)return;const d=c.querySelector("input,textarea,select");if(d){const h=C(d,p);n[p.field]!==h&&this.#l(e,p,h,n)}}),i&&r&&n)Object.keys(r).forEach(l=>{n[l]=r[l]}),a&&this.#t.delete(a);else if(!i&&n){const l=a?this.#t.has(a):!1;this.emit("row-commit",{rowIndex:e,rowId:a??"",row:n,changed:l,changedRows:this.changedRows,changedRowIds:this.changedRowIds}),l&&this.isAnimationEnabled&&t.animateRow?.(e,"change")}this.#r.delete(e),this.#e=-1,this.#s=-1,this.#a();for(const l of this.#n)l.startsWith(`${e}:`)&&this.#n.delete(l);o&&(o.querySelectorAll(".cell.editing").forEach(l=>{l.classList.remove("editing"),N(l.parentElement)}),this.requestRender()),this.#o=!0,o||(this.#u(t),this.#o=!1)}#l(e,i,t,r){const n=i.field;if(!y(n))return;const o=r[n];if(o===t)return;const a=this.grid;let l;try{l=this.grid.getRowId(r)}catch{}const c=l?!this.#t.has(l):!0,f=l?h=>this.grid.updateRow(l,h,"cascade"):L;if(this.emitCancelable("cell-commit",{row:r,rowId:l??"",field:n,oldValue:o,value:t,rowIndex:e,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:c,updateRow:f}))return;r[n]=t,l&&this.#t.add(l),this.#a();const d=a.findRenderedRowElement?.(e);d&&(d.classList.add("changed"),v.animateRowElement(d,"change"))}#d(e,i,t,r,n,o){if(!t.editable||n.classList.contains("editing"))return;let a;try{a=this.grid.getRowId(e)}catch{}const l=a?u=>this.grid.updateRow(a,u,"cascade"):L,c=y(t.field)?e[t.field]:void 0;n.classList.add("editing"),this.#n.add(`${i}:${r}`);const f=n.parentElement;f&&H(f);let p=!1;const d=u=>{p||this.#e===-1||this.#l(i,t,u,e)},h=()=>{p=!0,y(t.field)&&(e[t.field]=c)},g=document.createElement("div");g.className="tbw-editor-host",n.innerHTML="",n.appendChild(g),g.addEventListener("keydown",u=>{u.key==="Enter"&&(u.stopPropagation(),u.preventDefault(),p=!0,this.#i(i,!1)),u.key==="Escape"&&(u.stopPropagation(),u.preventDefault(),h(),this.#i(i,!0))});const m=t,R=m.__editorTemplate,w=x(this.grid,m)??k(t),S=c;if(w==="template"&&R)this.#h(g,m,e,c,d,h,o,i);else if(typeof w=="string"){const u=document.createElement(w);u.value=S,u.addEventListener("change",()=>d(u.value)),g.appendChild(u),o||queueMicrotask(()=>{g.querySelector(_)?.focus({preventScroll:!0})})}else if(typeof w=="function"){const u={row:e,rowId:a??"",value:S,field:t.field,column:t,commit:d,cancel:h,updateRow:l},b=w(u);typeof b=="string"?(g.innerHTML=b,$(g,t,d)):b instanceof Node&&g.appendChild(b),o||queueMicrotask(()=>{g.querySelector(_)?.focus({preventScroll:!0})})}else if(w&&typeof w=="object"){const u=document.createElement("div");u.setAttribute("data-external-editor",""),u.setAttribute("data-field",t.field),g.appendChild(u);const b={row:e,rowId:a??"",value:S,field:t.field,column:t,commit:d,cancel:h,updateRow:l};if(w.mount)try{w.mount({placeholder:u,context:b,spec:w})}catch(T){console.warn(`[tbw-grid] External editor mount error for column '${t.field}':`,T)}else this.grid.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:u,spec:w,context:b}}))}}#h(e,i,t,r,n,o,a,l){const c=i.__editorTemplate;if(!c)return;const f=c.cloneNode(!0),p=i.__compiledEditor;p?f.innerHTML=p({row:t,value:r,field:i.field,column:i,commit:n,cancel:o}):f.querySelectorAll("*").forEach(h=>{h.childNodes.length===1&&h.firstChild?.nodeType===Node.TEXT_NODE&&(h.textContent=h.textContent?.replace(/{{\s*value\s*}}/g,r==null?"":String(r)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(g,m)=>{if(!y(m))return"";const R=t[m];return R==null?"":String(R)})||"")});const d=f.querySelector("input,textarea,select");if(d){d instanceof HTMLInputElement&&d.type==="checkbox"?d.checked=!!r:d.value=String(r??"");let h=!1;d.addEventListener("blur",()=>{h||n(C(d,i))}),d.addEventListener("keydown",g=>{const m=g;m.key==="Enter"&&(m.stopPropagation(),m.preventDefault(),h=!0,n(C(d,i)),this.#i(l,!1)),m.key==="Escape"&&(m.stopPropagation(),m.preventDefault(),o(),this.#i(l,!0))}),d instanceof HTMLInputElement&&d.type==="checkbox"&&d.addEventListener("change",()=>n(d.checked)),a||setTimeout(()=>d.focus({preventScroll:!0}),0)}e.appendChild(f)}#u(e){queueMicrotask(()=>{try{const i=e._focusRow,t=e._focusCol,r=e.findRenderedRowElement?.(i);if(r){Array.from(e._bodyEl.querySelectorAll(".cell-focus")).forEach(o=>o.classList.remove("cell-focus"));const n=r.querySelector(`.cell[data-row="${i}"][data-col="${t}"]`);n&&(n.classList.add("cell-focus"),n.setAttribute("aria-selected","true"),n.hasAttribute("tabindex")||n.setAttribute("tabindex","-1"),n.focus({preventScroll:!0}))}}catch{}})}}E.EditingPlugin=j,E.defaultEditorFor=k,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(E,v){typeof exports=="object"&&typeof module<"u"?v(exports,require("../../core/internal/row-animation"),require("../../core/plugin/base-plugin")):typeof define=="function"&&define.amd?define(["exports","../../core/internal/row-animation","../../core/plugin/base-plugin"],v):(E=typeof globalThis<"u"?globalThis:E||self,v(E.TbwGridPlugin_editing={},E.TbwGrid,E.TbwGrid))})(this,(function(E,v,P){"use strict";const A="@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-grid .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:calc(var(--tbw-row-height) + 2px);align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}}";function q(s){const e=s.options;return e?typeof e=="function"?e():e:[]}function O(s){return e=>{const i=s.editorParams,t=document.createElement("input");t.type="number",t.value=e.value!=null?String(e.value):"",i?.min!==void 0&&(t.min=String(i.min)),i?.max!==void 0&&(t.max=String(i.max)),i?.step!==void 0&&(t.step=String(i.step)),i?.placeholder&&(t.placeholder=i.placeholder);const r=()=>e.commit(t.value===""?null:Number(t.value));return t.addEventListener("blur",r),t.addEventListener("keydown",n=>{n.key==="Enter"&&r(),n.key==="Escape"&&e.cancel()}),t}}function D(){return s=>{const e=document.createElement("input");return e.type="checkbox",e.checked=!!s.value,e.addEventListener("change",()=>s.commit(e.checked)),e}}function G(s){return e=>{const i=s.editorParams,t=document.createElement("input");return t.type="date",e.value instanceof Date&&(t.valueAsDate=e.value),i?.min&&(t.min=i.min),i?.max&&(t.max=i.max),i?.placeholder&&(t.placeholder=i.placeholder),t.addEventListener("change",()=>e.commit(t.valueAsDate)),t.addEventListener("keydown",r=>{r.key==="Escape"&&e.cancel()}),t}}function I(s){return e=>{const i=s.editorParams,t=document.createElement("select");if(s.multi&&(t.multiple=!0),i?.includeEmpty){const o=document.createElement("option");o.value="",o.textContent=i.emptyLabel??"",t.appendChild(o)}q(s).forEach(o=>{const a=document.createElement("option");a.value=String(o.value),a.textContent=o.label,(s.multi&&Array.isArray(e.value)&&e.value.includes(o.value)||!s.multi&&e.value===o.value)&&(a.selected=!0),t.appendChild(a)});const n=()=>{if(s.multi){const o=Array.from(t.selectedOptions).map(a=>a.value);e.commit(o)}else e.commit(t.value)};return t.addEventListener("change",n),t.addEventListener("blur",n),t.addEventListener("keydown",o=>{o.key==="Escape"&&e.cancel()}),t}}function M(s){return e=>{const i=s.editorParams,t=document.createElement("input");return t.type="text",t.value=e.value!=null?String(e.value):"",i?.maxLength!==void 0&&(t.maxLength=i.maxLength),i?.pattern&&(t.pattern=i.pattern),i?.placeholder&&(t.placeholder=i.placeholder),t.addEventListener("blur",()=>e.commit(t.value)),t.addEventListener("keydown",r=>{r.key==="Enter"&&e.commit(t.value),r.key==="Escape"&&e.cancel()}),t}}function k(s){switch(s.type){case"number":return O(s);case"boolean":return D();case"date":return G(s);case"select":return I(s);default:return M(s)}}const _='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function x(s,e){if(e.editor)return e.editor;if(e.__editorTemplate)return"template";if(!e.type)return;const t=s.effectiveConfig?.typeDefaults;if(t?.[e.type]?.editor)return t[e.type].editor;const r=s.__frameworkAdapter;if(r?.getTypeDefault){const n=r.getTypeDefault(e.type);if(n?.editor)return n.editor}}function y(s){return!(typeof s!="string"||s==="__proto__"||s==="constructor"||s==="prototype")}function H(s){const e=(s.__editingCellCount??0)+1;s.__editingCellCount=e,s.setAttribute("data-has-editing","")}function N(s){s.__editingCellCount=0,s.removeAttribute("data-has-editing")}function C(s,e){return s instanceof HTMLInputElement?s.type==="checkbox"?s.checked:s.type==="number"?s.value===""?null:Number(s.value):s.type==="date"?s.valueAsDate:s.value:e?.type==="number"&&s.value!==""?Number(s.value):s.value}function L(s){}function $(s,e,i){const t=s.querySelector("input,textarea,select");t&&(t.addEventListener("blur",()=>{i(C(t,e))}),t instanceof HTMLInputElement&&t.type==="checkbox"?t.addEventListener("change",()=>i(t.checked)):t instanceof HTMLSelectElement&&t.addEventListener("change",()=>i(C(t,e))))}class j extends P.BaseGridPlugin{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>e===!0},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'}],events:[{type:"cell-edit-committed",description:"Emitted when a cell edit is committed (for plugin-to-plugin coordination)"}],queries:[{type:"isEditing",description:"Returns whether any cell is currently being edited"}]};name="editing";styles=A;get defaultConfig(){return{editOn:"click"}}#e=-1;#s=-1;#r=new Map;#t=new Set;#n=new Set;#o=!1;attach(e){super.attach(e);const i=this.disconnectSignal,t=e;t._activeEditRows=-1,t._rowEditSnapshots=new Map,Object.defineProperty(e,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(e,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),e.resetChangedRows=r=>this.resetChangedRows(r),e.beginBulkEdit=(r,n)=>{n&&this.beginCellEdit(r,n)},document.addEventListener("keydown",r=>{r.key==="Escape"&&this.#e!==-1&&this.#i(this.#e,!0)},{capture:!0,signal:i}),document.addEventListener("mousedown",r=>{if(this.#e===-1)return;const n=t.findRenderedRowElement?.(this.#e);!n||(r.composedPath&&r.composedPath()||[]).includes(n)||queueMicrotask(()=>{this.#e!==-1&&this.#i(this.#e,!1)})},{signal:i})}detach(){this.#e=-1,this.#s=-1,this.#r.clear(),this.#t.clear(),this.#n.clear(),super.detach()}handleQuery(e){if(e.type==="isEditing")return this.#e!==-1}onCellClick(e){const i=this.grid,t=this.config.editOn??i.effectiveConfig?.editOn;if(t===!1||t==="manual"||t!=="click"&&t!=="dblclick")return!1;const r=e.originalEvent.type==="dblclick";if(t==="click"&&r||t==="dblclick"&&!r)return!1;const{rowIndex:n}=e;return i._columns?.some(a=>a.editable)?(e.originalEvent.stopPropagation(),this.beginBulkEdit(n),!0):!1}onKeyDown(e){const i=this.grid;if(e.key==="Escape"&&this.#e!==-1)return this.#i(this.#e,!0),!0;if(e.key===" "||e.key==="Spacebar"){const t=i._focusRow,r=i._focusCol;if(t>=0&&r>=0){const n=i._visibleColumns[r],o=i._rows[t];if(n?.editable&&n.type==="boolean"&&o){const a=n.field;if(y(a)){const c=!o[a];return this.#l(t,n,c,o),e.preventDefault(),this.requestRender(),!0}}}return!1}if(e.key==="Enter"&&!e.shiftKey){if(this.#e!==-1)return!1;const t=this.config.editOn??i.effectiveConfig?.editOn;if(t===!1||t==="manual")return!1;const r=i._focusRow,n=i._focusCol;if(r>=0&&i._columns?.some(a=>a.editable)){const a=i._visibleColumns[n],l=i._rows[r],c=a?.field??"",f=c&&l?l[c]:void 0,p=this.gridElement.querySelector(`[data-row="${r}"][data-col="${n}"]`),d=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:r,colIndex:n,field:c,value:f,row:l,cellEl:p,trigger:"keyboard",originalEvent:e}});this.gridElement.dispatchEvent(d);const h=new CustomEvent("activate-cell",{cancelable:!0,bubbles:!0,detail:{row:r,col:n}});return this.gridElement.dispatchEvent(h),d.defaultPrevented||h.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(r),!0)}return!1}return!1}processColumns(e){const i=this.grid,t=i.effectiveConfig?.typeDefaults,r=i.__frameworkAdapter;return!t&&!r?.getTypeDefault?e:e.map(n=>{if(!n.type)return n;let o;if(t?.[n.type]?.editorParams&&(o=t[n.type].editorParams),!o&&r?.getTypeDefault){const a=r.getTypeDefault(n.type);a?.editorParams&&(o=a.editorParams)}return o?{...n,editorParams:{...o,...n.editorParams}}:n})}afterRender(){const e=this.grid;if(this.#o&&(this.#o=!1,this.#u(e)),this.#n.size!==0)for(const i of this.#n){const[t,r]=i.split(":"),n=parseInt(t,10),o=parseInt(r,10),a=e.findRenderedRowElement?.(n);if(!a)continue;const l=a.querySelector(`.cell[data-col="${o}"]`);if(!l||l.classList.contains("editing"))continue;const c=e._rows[n],f=e._visibleColumns[o];c&&f&&this.#d(c,n,f,o,l,!0)}}onScrollRender(){this.afterRender()}get changedRows(){const e=[];for(const i of this.#t){const t=this.grid.getRow(i);t&&e.push(t)}return e}get changedRowIds(){return Array.from(this.#t)}get activeEditRow(){return this.#e}get activeEditCol(){return this.#s}isRowEditing(e){return this.#e===e}isCellEditing(e,i){return this.#n.has(`${e}:${i}`)}isRowChanged(e){const i=this.grid,t=i._rows[e];if(!t)return!1;try{const r=i.getRowId?.(t);return r?this.#t.has(r):!1}catch{return!1}}isRowChangedById(e){return this.#t.has(e)}resetChangedRows(e){const i=this.changedRows,t=this.changedRowIds;this.#t.clear(),this.#a(),e||this.emit("changed-rows-reset",{rows:i,ids:t}),this.grid._rowPool?.forEach(n=>n.classList.remove("changed"))}beginCellEdit(e,i){const t=this.grid,r=t._visibleColumns.findIndex(l=>l.field===i);if(r===-1||!t._visibleColumns[r]?.editable)return;const a=t.findRenderedRowElement?.(e)?.querySelector(`.cell[data-col="${r}"]`);a&&this.#f(e,r,a)}beginBulkEdit(e){const i=this.grid;if((this.config.editOn??i.effectiveConfig?.editOn)===!1||!i._columns?.some(a=>a.editable))return;const n=i.findRenderedRowElement?.(e);if(!n)return;const o=i._rows[e];this.#c(e,o),Array.from(n.children).forEach((a,l)=>{const c=i._visibleColumns[l];if(c?.editable){const f=a;f.classList.contains("editing")||this.#d(o,e,c,l,f,!0)}}),setTimeout(()=>{let a=n.querySelector(`.cell[data-col="${i._focusCol}"]`);if(a?.classList.contains("editing")||(a=n.querySelector(".cell.editing")),a?.classList.contains("editing")){const l=a.querySelector(_);try{l?.focus({preventScroll:!0})}catch{}}},0)}commitActiveRowEdit(){this.#e!==-1&&this.#i(this.#e,!1)}cancelActiveRowEdit(){this.#e!==-1&&this.#i(this.#e,!0)}#f(e,i,t){const r=this.grid,n=r._rows[e],o=r._visibleColumns[i];!n||!o?.editable||t.classList.contains("editing")||(this.#e!==e&&this.#c(e,n),this.#s=i,this.#d(n,e,o,i,t,!1))}#a(){const e=this.grid;e._activeEditRows=this.#e,e._rowEditSnapshots=this.#r}#c(e,i){this.#e!==e&&(this.#r.set(e,{...i}),this.#e=e,this.#a())}#i(e,i){if(this.#e!==e)return;const t=this.grid,r=this.#r.get(e),n=t._rows[e],o=t.findRenderedRowElement?.(e);let a;if(n)try{a=t.getRowId?.(n)}catch{}if(!i&&o&&n&&o.querySelectorAll(".cell.editing").forEach(c=>{const f=Number(c.getAttribute("data-col"));if(isNaN(f))return;const p=t._visibleColumns[f];if(!p)return;const d=c.querySelector("input,textarea,select");if(d){const h=C(d,p);n[p.field]!==h&&this.#l(e,p,h,n)}}),i&&r&&n)Object.keys(r).forEach(l=>{n[l]=r[l]}),a&&this.#t.delete(a);else if(!i&&n){const l=a?this.#t.has(a):!1;this.emit("row-commit",{rowIndex:e,rowId:a??"",row:n,changed:l,changedRows:this.changedRows,changedRowIds:this.changedRowIds}),l&&this.isAnimationEnabled&&t.animateRow?.(e,"change")}this.#r.delete(e),this.#e=-1,this.#s=-1,this.#a();for(const l of this.#n)l.startsWith(`${e}:`)&&this.#n.delete(l);o&&(o.querySelectorAll(".cell.editing").forEach(l=>{l.classList.remove("editing"),N(l.parentElement)}),this.requestRender()),this.#o=!0,o||(this.#u(t),this.#o=!1)}#l(e,i,t,r){const n=i.field;if(!y(n))return;const o=r[n];if(o===t)return;const a=this.grid;let l;try{l=this.grid.getRowId(r)}catch{}const c=l?!this.#t.has(l):!0,f=l?h=>this.grid.updateRow(l,h,"cascade"):L;if(this.emitCancelable("cell-commit",{row:r,rowId:l??"",field:n,oldValue:o,value:t,rowIndex:e,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:c,updateRow:f}))return;r[n]=t,l&&this.#t.add(l),this.#a(),this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:n,oldValue:o,newValue:t});const d=a.findRenderedRowElement?.(e);d&&(d.classList.add("changed"),v.animateRowElement(d,"change"))}#d(e,i,t,r,n,o){if(!t.editable||n.classList.contains("editing"))return;let a;try{a=this.grid.getRowId(e)}catch{}const l=a?u=>this.grid.updateRow(a,u,"cascade"):L,c=y(t.field)?e[t.field]:void 0;n.classList.add("editing"),this.#n.add(`${i}:${r}`);const f=n.parentElement;f&&H(f);let p=!1;const d=u=>{p||this.#e===-1||this.#l(i,t,u,e)},h=()=>{p=!0,y(t.field)&&(e[t.field]=c)},g=document.createElement("div");g.className="tbw-editor-host",n.innerHTML="",n.appendChild(g),g.addEventListener("keydown",u=>{u.key==="Enter"&&(u.stopPropagation(),u.preventDefault(),p=!0,this.#i(i,!1)),u.key==="Escape"&&(u.stopPropagation(),u.preventDefault(),h(),this.#i(i,!0))});const m=t,R=m.__editorTemplate,w=x(this.grid,m)??k(t),S=c;if(w==="template"&&R)this.#h(g,m,e,c,d,h,o,i);else if(typeof w=="string"){const u=document.createElement(w);u.value=S,u.addEventListener("change",()=>d(u.value)),g.appendChild(u),o||queueMicrotask(()=>{g.querySelector(_)?.focus({preventScroll:!0})})}else if(typeof w=="function"){const u={row:e,rowId:a??"",value:S,field:t.field,column:t,commit:d,cancel:h,updateRow:l},b=w(u);typeof b=="string"?(g.innerHTML=b,$(g,t,d)):b instanceof Node&&g.appendChild(b),o||queueMicrotask(()=>{g.querySelector(_)?.focus({preventScroll:!0})})}else if(w&&typeof w=="object"){const u=document.createElement("div");u.setAttribute("data-external-editor",""),u.setAttribute("data-field",t.field),g.appendChild(u);const b={row:e,rowId:a??"",value:S,field:t.field,column:t,commit:d,cancel:h,updateRow:l};if(w.mount)try{w.mount({placeholder:u,context:b,spec:w})}catch(T){console.warn(`[tbw-grid] External editor mount error for column '${t.field}':`,T)}else this.grid.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:u,spec:w,context:b}}))}}#h(e,i,t,r,n,o,a,l){const c=i.__editorTemplate;if(!c)return;const f=c.cloneNode(!0),p=i.__compiledEditor;p?f.innerHTML=p({row:t,value:r,field:i.field,column:i,commit:n,cancel:o}):f.querySelectorAll("*").forEach(h=>{h.childNodes.length===1&&h.firstChild?.nodeType===Node.TEXT_NODE&&(h.textContent=h.textContent?.replace(/{{\s*value\s*}}/g,r==null?"":String(r)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(g,m)=>{if(!y(m))return"";const R=t[m];return R==null?"":String(R)})||"")});const d=f.querySelector("input,textarea,select");if(d){d instanceof HTMLInputElement&&d.type==="checkbox"?d.checked=!!r:d.value=String(r??"");let h=!1;d.addEventListener("blur",()=>{h||n(C(d,i))}),d.addEventListener("keydown",g=>{const m=g;m.key==="Enter"&&(m.stopPropagation(),m.preventDefault(),h=!0,n(C(d,i)),this.#i(l,!1)),m.key==="Escape"&&(m.stopPropagation(),m.preventDefault(),o(),this.#i(l,!0))}),d instanceof HTMLInputElement&&d.type==="checkbox"&&d.addEventListener("change",()=>n(d.checked)),a||setTimeout(()=>d.focus({preventScroll:!0}),0)}e.appendChild(f)}#u(e){queueMicrotask(()=>{try{const i=e._focusRow,t=e._focusCol,r=e.findRenderedRowElement?.(i);if(r){Array.from(e._bodyEl.querySelectorAll(".cell-focus")).forEach(o=>o.classList.remove("cell-focus"));const n=r.querySelector(`.cell[data-row="${i}"][data-col="${t}"]`);n&&(n.classList.add("cell-focus"),n.setAttribute("aria-selected","true"),n.hasAttribute("tabindex")||n.setAttribute("tabindex","-1"),n.focus({preventScroll:!0}))}}catch{}})}}E.EditingPlugin=j,E.defaultEditorFor=k,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})}));
2
2
  //# sourceMappingURL=editing.umd.js.map