@toolbox-web/grid 1.2.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +80 -22
  2. package/all.js +619 -571
  3. package/all.js.map +1 -1
  4. package/index.js +362 -302
  5. package/index.js.map +1 -1
  6. package/lib/core/grid.d.ts +64 -1
  7. package/lib/core/grid.d.ts.map +1 -1
  8. package/lib/core/internal/row-animation.d.ts +37 -0
  9. package/lib/core/internal/row-animation.d.ts.map +1 -0
  10. package/lib/core/types.d.ts +17 -0
  11. package/lib/core/types.d.ts.map +1 -1
  12. package/lib/plugins/clipboard/index.js +82 -76
  13. package/lib/plugins/clipboard/index.js.map +1 -1
  14. package/lib/plugins/clipboard/types.d.ts +1 -0
  15. package/lib/plugins/clipboard/types.d.ts.map +1 -1
  16. package/lib/plugins/column-virtualization/index.js +43 -41
  17. package/lib/plugins/column-virtualization/index.js.map +1 -1
  18. package/lib/plugins/context-menu/index.js +24 -22
  19. package/lib/plugins/context-menu/index.js.map +1 -1
  20. package/lib/plugins/editing/EditingPlugin.d.ts.map +1 -1
  21. package/lib/plugins/editing/index.js +83 -52
  22. package/lib/plugins/editing/index.js.map +1 -1
  23. package/lib/plugins/export/index.js +22 -20
  24. package/lib/plugins/export/index.js.map +1 -1
  25. package/lib/plugins/filtering/FilteringPlugin.d.ts +11 -1
  26. package/lib/plugins/filtering/FilteringPlugin.d.ts.map +1 -1
  27. package/lib/plugins/filtering/index.js +160 -125
  28. package/lib/plugins/filtering/index.js.map +1 -1
  29. package/lib/plugins/grouping-columns/index.js +20 -18
  30. package/lib/plugins/grouping-columns/index.js.map +1 -1
  31. package/lib/plugins/grouping-rows/index.js +66 -64
  32. package/lib/plugins/grouping-rows/index.js.map +1 -1
  33. package/lib/plugins/master-detail/index.js +51 -49
  34. package/lib/plugins/master-detail/index.js.map +1 -1
  35. package/lib/plugins/multi-sort/index.js +17 -15
  36. package/lib/plugins/multi-sort/index.js.map +1 -1
  37. package/lib/plugins/pinned-columns/index.js +24 -22
  38. package/lib/plugins/pinned-columns/index.js.map +1 -1
  39. package/lib/plugins/pinned-rows/index.js +25 -23
  40. package/lib/plugins/pinned-rows/index.js.map +1 -1
  41. package/lib/plugins/pivot/index.js +49 -47
  42. package/lib/plugins/pivot/index.js.map +1 -1
  43. package/lib/plugins/reorder/index.js +24 -22
  44. package/lib/plugins/reorder/index.js.map +1 -1
  45. package/lib/plugins/responsive/index.js +19 -17
  46. package/lib/plugins/responsive/index.js.map +1 -1
  47. package/lib/plugins/row-reorder/index.js +38 -36
  48. package/lib/plugins/row-reorder/index.js.map +1 -1
  49. package/lib/plugins/selection/SelectionPlugin.d.ts +13 -0
  50. package/lib/plugins/selection/SelectionPlugin.d.ts.map +1 -1
  51. package/lib/plugins/selection/index.d.ts +1 -1
  52. package/lib/plugins/selection/index.d.ts.map +1 -1
  53. package/lib/plugins/selection/index.js +118 -85
  54. package/lib/plugins/selection/index.js.map +1 -1
  55. package/lib/plugins/selection/types.d.ts +50 -6
  56. package/lib/plugins/selection/types.d.ts.map +1 -1
  57. package/lib/plugins/server-side/index.js +34 -32
  58. package/lib/plugins/server-side/index.js.map +1 -1
  59. package/lib/plugins/tree/index.js +25 -23
  60. package/lib/plugins/tree/index.js.map +1 -1
  61. package/lib/plugins/undo-redo/index.js +22 -20
  62. package/lib/plugins/undo-redo/index.js.map +1 -1
  63. package/lib/plugins/visibility/index.js +21 -19
  64. package/lib/plugins/visibility/index.js.map +1 -1
  65. package/package.json +21 -4
  66. package/public.d.ts +1 -1
  67. package/public.d.ts.map +1 -1
  68. package/umd/grid.all.umd.js +19 -19
  69. package/umd/grid.all.umd.js.map +1 -1
  70. package/umd/grid.umd.js +9 -9
  71. package/umd/grid.umd.js.map +1 -1
  72. package/umd/plugins/clipboard.umd.js +5 -5
  73. package/umd/plugins/clipboard.umd.js.map +1 -1
  74. package/umd/plugins/editing.umd.js +1 -1
  75. package/umd/plugins/editing.umd.js.map +1 -1
  76. package/umd/plugins/filtering.umd.js +1 -1
  77. package/umd/plugins/filtering.umd.js.map +1 -1
  78. package/umd/plugins/selection.umd.js +2 -2
  79. package/umd/plugins/selection.umd.js.map +1 -1
@@ -1,7 +1,7 @@
1
- (function(h,x){typeof exports=="object"&&typeof module<"u"?x(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"],x):(h=typeof globalThis<"u"?globalThis:h||self,x(h.TbwGridPlugin_clipboard={},h.TbwGrid,h.TbwGrid))})(this,(function(h,x,S){"use strict";async function R(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??" ",s=t.newline??`
2
- `,a=m.replace(/\r\n/g,`
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,`
3
3
  `).replace(/\r/g,`
4
- `),l=[];let e=[],i="",o=!1;for(let c=0;c<a.length;c++){const r=a[c];r==='"'&&!o?o=!0:r==='"'&&o?a[c+1]==='"'?(i+='"',c++):o=!1:r===n&&!o?(e.push(i),i=""):r===s&&!o?(e.push(i),i="",(e.length>1||e.some(p=>p.trim()!==""))&&l.push(e),e=[]):i+=r}return e.push(i),(e.length>1||e.some(c=>c.trim()!==""))&&l.push(e),l}async function T(){try{return await navigator.clipboard.readText()}catch{return""}}function P(m,t){const{rows:n,target:s,fields:a}=m;if(!s)return;const l=t.rows,i=(t.effectiveConfig.columns??[]).map(r=>r.field),o=[...l],c=s.bounds?s.bounds.endRow:1/0;n.forEach((r,p)=>{const d=s.row+p;if(!(d>c)){if(s.bounds){if(d>=o.length)return}else for(;d>=o.length;){const w={};i.forEach(u=>w[u]=""),o.push(w)}o[d]={...o[d]},r.forEach((w,u)=>{const f=a[u];f&&(o[d][f]=w)})}}),t.rows=o}class v extends x.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(),s=n?.getSelection(),a=this.columns.length-1,l=this.rows.length-1;let e;if(s&&s.ranges.length>0){const{mode:o,ranges:c}=s,r=c[c.length-1];o==="row"?e={startRow:r.from.row,startCol:0,endRow:r.to.row,endCol:a}:e={startRow:r.from.row,startCol:r.from.col,endRow:r.to.row,endCol:r.to.col}}else if(!n)e={startRow:0,startCol:0,endRow:l,endCol:a};else{const o=this.#l(t);if(!o)return;e={startRow:o.row,startCol:o.col,endRow:o.row,endCol:o.col}}const i=this.#e(e);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(t){const n=t.clipboardData?.getData("text/plain");if(!n)return;t.preventDefault();const s=b(n,this.config),l=this.#t()?.getSelection(),e=l?.ranges?.[0],i=e?.from.row??0,o=e?.from.col??0,r=e&&(l?.mode==="range"||l?.mode==="row")&&(e.from.row!==e.to.row||e.from.col!==e.to.col)?{endRow:e.to.row,endCol:e.to.col}:null,p=r?.endCol??this.columns.length-1,d=this.columns[o],w=d?{row:i,col:o,field:d.field,bounds:r}:null,u=[],f=s[0]?.length??0;for(let C=0;C<f&&o+C<=p;C++){const g=this.columns[o+C];g&&!g.hidden&&u.push(g.field)}const y={rows:s,text:n,target:w,fields:u};this.emit("paste",y),this.#s(y)}#s(t){if(!this.grid)return;const{pasteHandler:n}=this.config;if(n===null)return;(n??P)(t,this.grid)}#t(){try{const t=this.grid?.getPluginByName("selection");if(t)return t}catch{}}#e(t){const{startRow:n,startCol:s,endRow:a,endCol:l}=t,e=Math.min(n,a),i=Math.max(n,a),o=Math.min(s,l),c=Math.max(s,l),r=this.config.delimiter??" ",p=this.config.newline??`
6
- `,d=[],w=this.columns.slice(o,c+1).filter(u=>!S.isUtilityColumn(u));if(this.config.includeHeaders){const u=w.map(f=>f.header||f.field);d.push(u.join(r))}for(let u=e;u<=i;u++){const f=this.rows[u];if(!f)continue;const y=w.map(C=>{const g=f[C.field];return g==null?"":g instanceof Date?g.toISOString():String(g)});d.push(y.join(r))}return{text:d.join(p),rowCount:i-e+1,columnCount:c-o+1}}#l(t){const n=t.closest("[data-field-cache]");if(!n)return null;const s=n.dataset.fieldCache,a=n.dataset.row;if(!s||!a)return null;const l=parseInt(a,10);if(isNaN(l))return null;const e=this.columns.findIndex(i=>i.field===s);return e===-1?null:{row:l,col:e}}async copy(){const n=this.#t()?.getSelection(),s=this.columns.length-1;let a={startRow:0,startCol:0,endRow:this.rows.length-1,endCol:s};if(n&&n.ranges.length>0){const e=n.ranges[n.ranges.length-1];n.mode==="row"?a={startRow:e.from.row,startCol:0,endRow:e.to.row,endCol:s}:a={startRow:e.from.row,startCol:e.from.col,endRow:e.to.row,endCol:e.to.col}}const l=this.#e(a);return await R(l.text),this.lastCopied={text:l.text,timestamp:Date.now()},l.text}async copyRows(t){if(t.length===0)return"";const n=[...t].sort((e,i)=>e-i),s=this.columns.length-1,a={startRow:n[0],startCol:0,endRow:n[n.length-1],endCol:s},l=this.#e(a);return await R(l.text),this.lastCopied={text:l.text,timestamp:Date.now()},l.text}async paste(){const t=await T();return t?b(t,this.config):null}getLastCopied(){return this.lastCopied}}h.ClipboardPlugin=v,h.defaultPasteHandler=P,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));
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"})}));
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 *\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 // 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) {\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","allFields","col","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":"kaAi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E,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,aAAM9C,EAAgBoD,EAAO,IAAI,EACjC,KAAK,WAAa,CAAE,KAAMA,EAAO,KAAM,UAAW,KAAK,KAAI,EACpDA,EAAO,IAChB,CAMA,MAAM,OAAoC,CACxC,MAAMnD,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 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,EAA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,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,2 +1,2 @@
1
- (function(E,v){typeof exports=="object"&&typeof module<"u"?v(exports,require("../../core/plugin/base-plugin")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin"],v):(E=typeof globalThis<"u"?globalThis:E||self,v(E.TbwGridPlugin_editing={},E.TbwGrid))})(this,(function(E,v){"use strict";const P="@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 A(s){const e=s.options;return e?typeof e=="function"?e():e:[]}function q(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 O(){return s=>{const e=document.createElement("input");return e.type="checkbox",e.checked=!!s.value,e.addEventListener("change",()=>s.commit(e.checked)),e}}function D(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)}A(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 x(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 q(s);case"boolean":return O();case"date":return D(s);case"select":return I(s);default:return x(s)}}const _='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function G(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 M(s){const e=(s.__editingCellCount??0)+1;s.__editingCellCount=e,s.setAttribute("data-has-editing","")}function H(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 N(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 $ extends v.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=P;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)||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})}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"),H(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")}#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&&M(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=G(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,N(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=$,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 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 x(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 x(s)}}const _='input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])';function M(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)||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=M(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