@toolbox-web/grid 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/all.js +2 -2
  2. package/all.js.map +1 -1
  3. package/custom-elements.json +21 -2
  4. package/index.js +1 -1
  5. package/index.js.map +1 -1
  6. package/lib/core/adapter-conformance.d.ts +23 -0
  7. package/lib/core/grid.d.ts +13 -15
  8. package/lib/core/types.d.ts +72 -12
  9. package/lib/plugins/clipboard/index.js +1 -1
  10. package/lib/plugins/clipboard/index.js.map +1 -1
  11. package/lib/plugins/column-virtualization/index.js.map +1 -1
  12. package/lib/plugins/context-menu/index.js.map +1 -1
  13. package/lib/plugins/editing/index.js.map +1 -1
  14. package/lib/plugins/export/index.js +1 -1
  15. package/lib/plugins/export/index.js.map +1 -1
  16. package/lib/plugins/filtering/index.js +1 -1
  17. package/lib/plugins/filtering/index.js.map +1 -1
  18. package/lib/plugins/grouping-columns/index.js.map +1 -1
  19. package/lib/plugins/grouping-rows/index.js.map +1 -1
  20. package/lib/plugins/master-detail/index.js +1 -1
  21. package/lib/plugins/master-detail/index.js.map +1 -1
  22. package/lib/plugins/multi-sort/index.js +1 -1
  23. package/lib/plugins/multi-sort/index.js.map +1 -1
  24. package/lib/plugins/pinned-columns/PinnedColumnsPlugin.d.ts +1 -1
  25. package/lib/plugins/pinned-columns/index.js +1 -1
  26. package/lib/plugins/pinned-columns/index.js.map +1 -1
  27. package/lib/plugins/pinned-columns/types.d.ts +7 -0
  28. package/lib/plugins/pinned-rows/index.js.map +1 -1
  29. package/lib/plugins/pivot/index.js.map +1 -1
  30. package/lib/plugins/print/index.js +1 -1
  31. package/lib/plugins/print/index.js.map +1 -1
  32. package/lib/plugins/reorder-columns/ReorderPlugin.d.ts +13 -1
  33. package/lib/plugins/reorder-columns/column-drag.d.ts +7 -1
  34. package/lib/plugins/reorder-columns/index.js +1 -1
  35. package/lib/plugins/reorder-columns/index.js.map +1 -1
  36. package/lib/plugins/reorder-columns/types.d.ts +12 -0
  37. package/lib/plugins/reorder-rows/index.js +1 -1
  38. package/lib/plugins/reorder-rows/index.js.map +1 -1
  39. package/lib/plugins/responsive/index.js.map +1 -1
  40. package/lib/plugins/selection/index.js +1 -1
  41. package/lib/plugins/selection/index.js.map +1 -1
  42. package/lib/plugins/selection/types.d.ts +8 -0
  43. package/lib/plugins/server-side/index.js.map +1 -1
  44. package/lib/plugins/tooltip/index.js.map +1 -1
  45. package/lib/plugins/tree/index.js.map +1 -1
  46. package/lib/plugins/undo-redo/index.js.map +1 -1
  47. package/lib/plugins/visibility/VisibilityPlugin.d.ts +11 -1
  48. package/lib/plugins/visibility/index.js +1 -1
  49. package/lib/plugins/visibility/index.js.map +1 -1
  50. package/package.json +1 -1
  51. package/public.d.ts +1 -0
  52. package/umd/grid.all.umd.js +1 -1
  53. package/umd/grid.all.umd.js.map +1 -1
  54. package/umd/grid.umd.js +1 -1
  55. package/umd/grid.umd.js.map +1 -1
  56. package/umd/plugins/clipboard.umd.js +1 -1
  57. package/umd/plugins/clipboard.umd.js.map +1 -1
  58. package/umd/plugins/export.umd.js +1 -1
  59. package/umd/plugins/export.umd.js.map +1 -1
  60. package/umd/plugins/multi-sort.umd.js +1 -1
  61. package/umd/plugins/multi-sort.umd.js.map +1 -1
  62. package/umd/plugins/pinned-columns.umd.js +1 -1
  63. package/umd/plugins/pinned-columns.umd.js.map +1 -1
  64. package/umd/plugins/print.umd.js +1 -1
  65. package/umd/plugins/print.umd.js.map +1 -1
  66. package/umd/plugins/reorder-columns.umd.js +1 -1
  67. package/umd/plugins/reorder-columns.umd.js.map +1 -1
  68. package/umd/plugins/reorder-rows.umd.js +1 -1
  69. package/umd/plugins/reorder-rows.umd.js.map +1 -1
  70. package/umd/plugins/selection.umd.js +1 -1
  71. package/umd/plugins/selection.umd.js.map +1 -1
  72. package/umd/plugins/visibility.umd.js +1 -1
  73. package/umd/plugins/visibility.umd.js.map +1 -1
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/value-accessor"),require("../../core/plugin/base-plugin"),require("../../core/internal/diagnostics")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/value-accessor","../../core/plugin/base-plugin","../../core/internal/diagnostics"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_clipboard={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,n,o){"use strict";function i(e,t,n=!0){let o=e;if(n&&(o=o.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.meta?.utility)),t?.length){const e=new Set(t);o=o.filter(t=>e.has(t.field))}return o}function r(e,t){const n=t.delimiter??"\t",o=t.newline??"\n",i=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=[];let s=[],l="",a=!1;for(let c=0;c<i.length;c++){const e=i[c];'"'!==e||a?'"'===e&&a?'"'===i[c+1]?(l+='"',c++):a=!1:e!==n||a?e!==o||a?l+=e:(s.push(l),l="",(s.length>1||s.some(e=>""!==e.trim()))&&r.push(s),s=[]):(s.push(l),l=""):a=!0}return s.push(l),(s.length>1||s.some(e=>""!==e.trim()))&&r.push(s),r}function s(e,t){const{rows:n,target:o,fields:i}=e;if(!o)return;const r=t.rows,s=t.effectiveConfig.columns??[],l=s.map(e=>e.field),a=new Map;s.forEach(e=>{a.set(e.field,!0===e.editable)});const c=[...r],u=o.bounds?o.bounds.endRow:1/0;n.forEach((e,t)=>{const n=o.row+t;if(!(n>u)){if(o.bounds){if(n>=c.length)return}else for(;n>=c.length;){const e={};l.forEach(t=>e[t]=""),c.push(e)}c[n]={...c[n]},e.forEach((e,t)=>{const o=i[t];o&&a.get(o)&&(c[n][o]=e)})}}),t.rows=c}class l extends n.BaseGridPlugin{static manifest={queries:[{type:"clipboard:copy",description:"Triggers a copy operation and returns the copied text"}]};static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:"\t",newline:"\n",quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e),e.addEventListener("paste",e=>this.#e(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}handleQuery(e){if("clipboard:copy"===e.type)return this.copy(),!0}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#t(e.target),!0)}#t(e){const t=this.#n();if(t&&0===t.ranges.length){const t=this.#o(e);if(!t)return;const n=this.columns[t.col];if(!n)return;return void this.copy({rowIndices:[t.row],columns:[n.field]})}this.copy()}#e(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const n=r(t,this.config),o=this.#n(),i=o?.ranges?.[0],s=i?.from.row??0,l=i?.from.col??0,a=i&&("range"===o?.mode||"row"===o?.mode)&&(i.from.row!==i.to.row||i.from.col!==i.to.col)?{endRow:i.to.row,endCol:i.to.col}:null,c=a?.endCol??this.visibleColumns.length-1,u=this.visibleColumns[l],d=u?{row:s,col:l,field:u.field,bounds:a}:null,f=[],h=n[0]?.length??0;for(let r=0;r<h&&l+r<=c;r++){const e=this.visibleColumns[l+r];e&&f.push(e.field)}const p={rows:n,text:t,target:d,fields:f};this.emit("paste",p),this.#i(p)}#i(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??s)(e,this.grid)}#n(){const e=this.grid?.query("getSelection");return e?.[0]}#r(e){const t=this.#n();let n,o;if(e?.columns)n=i(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],o=Math.min(e.from.col,e.to.col),r=Math.max(e.from.col,e.to.col);n=i(this.visibleColumns.slice(o,r+1))}else n=i(this.columns);if(e?.rowIndices)o=function(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}(this.rows,e.rowIndices);else if(t?.ranges.length){const e=t.ranges[t.ranges.length-1],n=Math.min(e.from.row,e.to.row),i=Math.max(e.from.row,e.to.row);o=[];for(let t=n;t<=i;t++){const e=this.rows[t];e&&o.push(e)}}else o=this.rows;return{columns:n,rows:o}}#s(e,n,o){const i=o?.delimiter??this.config.delimiter??"\t",r=o?.newline??this.config.newline??"\n",s=o?.includeHeaders??this.config.includeHeaders??!1,l=o?.processCell??this.config.processCell,a=[];s&&a.push(e.map(e=>e.header||e.field).join(i));for(const c of n){const n=e.map(e=>{const n=t.resolveCellValue(c,e);return l?l(n,e.field,c):this.#l(e,n,c)});a.push(n.join(i))}return a.join(r)}#l(e,t,n){if(e.format)try{const o=e.format(t,n);return null==o?"":String(o)}catch{}if(e.renderer||e.viewRenderer){const t=this.#a(e.field,n);if(null!=t)return t}return function(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}(t)}#a(e,t){const n=this.gridElement;if(!n)return null;const o=this.rows.indexOf(t);if(-1===o)return null;const i=n.querySelector(`.cell[data-row="${o}"][data-field="${e}"]`);return i?i.textContent?.trim()??null:null}#o(e){const t=e.closest("[data-field-cache]");if(!t)return null;const n=t.dataset.fieldCache,o=t.dataset.row;if(!n||!o)return null;const i=parseInt(o,10);if(isNaN(i))return null;const r=this.columns.findIndex(e=>e.field===n);return-1===r?null:{row:i,col:r}}getSelectionAsText(e){const{columns:t,rows:n}=this.#r(e);return 0===t.length||0===n.length?"":this.#s(t,n,e)}async copy(e){const{columns:t,rows:n}=this.#r(e);if(0===t.length||0===n.length)return"";const i=this.#s(t,n,e);return await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){o.warnDiagnostic(o.CLIPBOARD_FAILED,`Clipboard API failed: ${t}`);const n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",n.style.pointerEvents="none",document.body.appendChild(n),n.select();const i=document.execCommand("copy");return document.body.removeChild(n),i}}(i),this.lastCopied={text:i,timestamp:Date.now()},this.emit("copy",{text:i,rowCount:n.length,columnCount:t.length}),i}async copyRows(e,t){return 0===e.length?"":this.copy({...t,rowIndices:e})}async paste(){const e=await async function(){try{return await navigator.clipboard.readText()}catch{return""}}();return e?r(e,this.config):null}getLastCopied(){return this.lastCopied}}e.ClipboardPlugin=l,e.defaultPasteHandler=s,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/value-accessor"),require("../../core/plugin/base-plugin"),require("../../core/internal/diagnostics")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/value-accessor","../../core/plugin/base-plugin","../../core/internal/diagnostics"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_clipboard={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,n,o){"use strict";function i(e,t,n=!0){let o=e;if(n&&(o=o.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.utility)),t?.length){const e=new Set(t);o=o.filter(t=>e.has(t.field))}return o}function r(e,t){const n=t.delimiter??"\t",o=t.newline??"\n",i=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=[];let s=[],l="",a=!1;for(let c=0;c<i.length;c++){const e=i[c];'"'!==e||a?'"'===e&&a?'"'===i[c+1]?(l+='"',c++):a=!1:e!==n||a?e!==o||a?l+=e:(s.push(l),l="",(s.length>1||s.some(e=>""!==e.trim()))&&r.push(s),s=[]):(s.push(l),l=""):a=!0}return s.push(l),(s.length>1||s.some(e=>""!==e.trim()))&&r.push(s),r}function s(e,t){const{rows:n,target:o,fields:i}=e;if(!o)return;const r=t.rows,s=t.effectiveConfig.columns??[],l=s.map(e=>e.field),a=new Map;s.forEach(e=>{a.set(e.field,!0===e.editable)});const c=[...r],u=o.bounds?o.bounds.endRow:1/0;n.forEach((e,t)=>{const n=o.row+t;if(!(n>u)){if(o.bounds){if(n>=c.length)return}else for(;n>=c.length;){const e={};l.forEach(t=>e[t]=""),c.push(e)}c[n]={...c[n]},e.forEach((e,t)=>{const o=i[t];o&&a.get(o)&&(c[n][o]=e)})}}),t.rows=c}class l extends n.BaseGridPlugin{static manifest={queries:[{type:"clipboard:copy",description:"Triggers a copy operation and returns the copied text"}]};static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:"\t",newline:"\n",quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e),e.addEventListener("paste",e=>this.#e(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}handleQuery(e){if("clipboard:copy"===e.type)return this.copy(),!0}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#t(e.target),!0)}#t(e){const t=this.#n();if(t&&0===t.ranges.length){const t=this.#o(e);if(!t)return;const n=this.columns[t.col];if(!n)return;return void this.copy({rowIndices:[t.row],columns:[n.field]})}this.copy()}#e(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const n=r(t,this.config),o=this.#n(),i=o?.ranges?.[0],s=i?.from.row??0,l=i?.from.col??0,a=i&&("range"===o?.mode||"row"===o?.mode)&&(i.from.row!==i.to.row||i.from.col!==i.to.col)?{endRow:i.to.row,endCol:i.to.col}:null,c=a?.endCol??this.visibleColumns.length-1,u=this.visibleColumns[l],d=u?{row:s,col:l,field:u.field,bounds:a}:null,f=[],h=n[0]?.length??0;for(let r=0;r<h&&l+r<=c;r++){const e=this.visibleColumns[l+r];e&&f.push(e.field)}const p={rows:n,text:t,target:d,fields:f};this.emit("paste",p),this.#i(p)}#i(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??s)(e,this.grid)}#n(){const e=this.grid?.query("getSelection");return e?.[0]}#r(e){const t=this.#n();let n,o;if(e?.columns)n=i(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],o=Math.min(e.from.col,e.to.col),r=Math.max(e.from.col,e.to.col);n=i(this.visibleColumns.slice(o,r+1))}else n=i(this.columns);if(e?.rowIndices)o=function(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}(this.rows,e.rowIndices);else if(t?.ranges.length){const e=t.ranges[t.ranges.length-1],n=Math.min(e.from.row,e.to.row),i=Math.max(e.from.row,e.to.row);o=[];for(let t=n;t<=i;t++){const e=this.rows[t];e&&o.push(e)}}else o=this.rows;return{columns:n,rows:o}}#s(e,n,o){const i=o?.delimiter??this.config.delimiter??"\t",r=o?.newline??this.config.newline??"\n",s=o?.includeHeaders??this.config.includeHeaders??!1,l=o?.processCell??this.config.processCell,a=[];s&&a.push(e.map(e=>e.header||e.field).join(i));for(const c of n){const n=e.map(e=>{const n=t.resolveCellValue(c,e);return l?l(n,e.field,c):this.#l(e,n,c)});a.push(n.join(i))}return a.join(r)}#l(e,t,n){if(e.format)try{const o=e.format(t,n);return null==o?"":String(o)}catch{}if(e.renderer||e.viewRenderer){const t=this.#a(e.field,n);if(null!=t)return t}return function(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}(t)}#a(e,t){const n=this.gridElement;if(!n)return null;const o=this.rows.indexOf(t);if(-1===o)return null;const i=n.querySelector(`.cell[data-row="${o}"][data-field="${e}"]`);return i?i.textContent?.trim()??null:null}#o(e){const t=e.closest("[data-field-cache]");if(!t)return null;const n=t.dataset.fieldCache,o=t.dataset.row;if(!n||!o)return null;const i=parseInt(o,10);if(isNaN(i))return null;const r=this.columns.findIndex(e=>e.field===n);return-1===r?null:{row:i,col:r}}getSelectionAsText(e){const{columns:t,rows:n}=this.#r(e);return 0===t.length||0===n.length?"":this.#s(t,n,e)}async copy(e){const{columns:t,rows:n}=this.#r(e);if(0===t.length||0===n.length)return"";const i=this.#s(t,n,e);return await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){o.warnDiagnostic(o.CLIPBOARD_FAILED,`Clipboard API failed: ${t}`);const n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",n.style.pointerEvents="none",document.body.appendChild(n),n.select();const i=document.execCommand("copy");return document.body.removeChild(n),i}}(i),this.lastCopied={text:i,timestamp:Date.now()},this.emit("copy",{text:i,rowCount:n.length,columnCount:t.length}),i}async copyRows(e,t){return 0===e.length?"":this.copy({...t,rowIndices:e})}async paste(){const e=await async function(){try{return await navigator.clipboard.readText()}catch{return""}}();return e?r(e,this.config):null}getLastCopied(){return this.lastCopied}}e.ClipboardPlugin=l,e.defaultPasteHandler=s,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=clipboard.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.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","../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts"],"sourcesContent":["/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.meta?.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\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/**\n * Options for programmatic copy operations.\n *\n * Allows callers to control exactly which columns and rows are included\n * in a copy, independently of the current selection state.\n *\n * @example Copy specific columns from selected rows\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * // User selected rows 0, 2, 4 via a dialog, chose columns to include\n * const text = await clipboard.copy({\n * rowIndices: [0, 2, 4],\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * ```\n */\nexport interface CopyOptions {\n /** Specific column fields to include. If omitted, uses current selection or all visible columns. */\n columns?: string[];\n /** Specific row indices to copy. If omitted, uses current selection or all rows. */\n rowIndices?: number[];\n /** Include column headers in copied text. Defaults to the plugin config value. */\n includeHeaders?: boolean;\n /** Column delimiter override. Defaults to the plugin config value. */\n delimiter?: string;\n /** Row delimiter override. Defaults to the plugin config value. */\n newline?: string;\n /** Custom cell value processor for this operation. Overrides the plugin config's `processCell`. */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n}\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// Module Augmentation - Register plugin name for type-safe getPluginByName()\ndeclare module '../../core/types' {\n interface DataGridEventMap {\n /** Fired after a successful copy operation. Provides the copied text, row count, and column count. @group Clipboard Events */\n 'copy': CopyDetail;\n /** Fired after a paste operation. Provides parsed rows, target cell, and column fields. @group Clipboard Events */\n 'paste': PasteDetail;\n }\n\n interface PluginNameMap {\n clipboard: import('./ClipboardPlugin').ClipboardPlugin;\n }\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 { resolveCellValue } from '../../core/internal/value-accessor';\nimport {\n BaseGridPlugin,\n type GridElement,\n type PluginDependency,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatValueAsText, resolveColumns, resolveRows } from '../shared/data-collection';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type CopyOptions,\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 * ## 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 * @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 SelectionPlugin for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin manifest — declares queries for inter-plugin communication.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [{ type: 'clipboard:copy', description: 'Triggers a copy operation and returns the copied text' }],\n };\n\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 grid.addEventListener('paste', (e) => this.#handleNativePaste(e), {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'clipboard:copy') {\n this.copy();\n return true;\n }\n return undefined;\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 // Prevent the browser's default copy action so it doesn't overwrite\n // our clipboard write with whatever text is selected in the DOM.\n event.preventDefault();\n this.#handleCopy(event.target as HTMLElement);\n return true;\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 from keyboard shortcut.\n *\n * For keyboard-triggered copies, respects the current selection or\n * falls back to the focused cell from the DOM.\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n\n // Selection plugin exists but nothing selected → try focused cell from DOM\n if (selection && selection.ranges.length === 0) {\n const focused = this.#getFocusedCellFromDOM(target);\n if (!focused) return;\n const col = this.columns[focused.col];\n if (!col) return;\n this.copy({ rowIndices: [focused.row], columns: [col.field] });\n return;\n }\n\n // Delegate to the public copy() method (selection or full grid)\n this.copy();\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection via query\n const selection = this.#getSelection();\n const firstRange = selection?.ranges?.[0];\n\n // Determine target cell and bounds\n const targetRow = firstRange?.from.row ?? 0;\n const targetCol = firstRange?.from.col ?? 0;\n\n // Check if multi-cell selection (range with different start/end)\n const isMultiCell =\n firstRange &&\n (selection?.mode === 'range' || selection?.mode === 'row') &&\n (firstRange.from.row !== firstRange.to.row || firstRange.from.col !== firstRange.to.col);\n\n const bounds = isMultiCell ? { endRow: firstRange.to.row, endCol: firstRange.to.col } : null;\n // Selection range indices are visible-column indices (from data-col)\n const maxCol = bounds?.endCol ?? this.visibleColumns.length - 1;\n\n // Build target info\n const column = this.visibleColumns[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.visibleColumns[targetCol + i];\n if (col) {\n fields.push(col.field);\n }\n }\n\n const detail: PasteDetail = { rows: parsed, text, target, fields };\n\n // Emit the event for any listeners\n this.emit<PasteDetail>('paste', detail);\n\n // Apply paste data using the configured handler (or default)\n this.#applyPasteHandler(detail);\n }\n\n /**\n * Apply the paste handler to update grid data.\n *\n * Uses the configured `pasteHandler`, or the default handler if not specified.\n * Set `pasteHandler: null` in config to disable auto-paste.\n */\n #applyPasteHandler(detail: PasteDetail): void {\n if (!this.grid) return;\n\n const { pasteHandler } = this.config;\n\n // pasteHandler: null means explicitly disabled\n if (pasteHandler === null) return;\n\n // Use custom handler or default\n const handler = pasteHandler ?? defaultPasteHandler;\n handler(detail, this.grid);\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection');\n return responses?.[0];\n }\n\n /**\n * Resolve columns and rows to include based on options and/or current selection.\n *\n * Priority for columns:\n * 1. `options.columns` (explicit field list)\n * 2. Selection range column bounds (range/cell mode only)\n * 3. All visible non-utility columns\n *\n * Priority for rows:\n * 1. `options.rowIndices` (explicit indices)\n * 2. Selection range row bounds\n * 3. All rows\n */\n #resolveData(options?: CopyOptions): { columns: ColumnConfig[]; rows: Record<string, unknown>[] } {\n const selection = this.#getSelection();\n\n // --- Columns ---\n let columns: ColumnConfig[];\n if (options?.columns) {\n // Caller specified exact fields\n columns = resolveColumns(this.columns, options.columns);\n } else if (selection?.ranges.length && selection.mode !== 'row') {\n // Range/cell selection: restrict to selection column bounds\n // Selection indices are visible-column indices (from data-col)\n const range = selection.ranges[selection.ranges.length - 1];\n const minCol = Math.min(range.from.col, range.to.col);\n const maxCol = Math.max(range.from.col, range.to.col);\n columns = resolveColumns(this.visibleColumns.slice(minCol, maxCol + 1));\n } else {\n // Row selection or no selection: all visible columns\n columns = resolveColumns(this.columns);\n }\n\n // --- Rows ---\n let rows: Record<string, unknown>[];\n if (options?.rowIndices) {\n // Caller specified exact row indices\n rows = resolveRows(this.rows as Record<string, unknown>[], options.rowIndices);\n } else if (selection?.ranges.length) {\n // Selection range: extract contiguous row range\n const range = selection.ranges[selection.ranges.length - 1];\n const minRow = Math.min(range.from.row, range.to.row);\n const maxRow = Math.max(range.from.row, range.to.row);\n rows = [];\n for (let r = minRow; r <= maxRow; r++) {\n const row = this.rows[r] as Record<string, unknown> | undefined;\n if (row) rows.push(row);\n }\n } else {\n // No selection: all rows\n rows = this.rows as Record<string, unknown>[];\n }\n\n return { columns, rows };\n }\n\n /**\n * Build delimited text from resolved columns and rows.\n *\n * When no `processCell` callback is configured, uses \"copy what you see\" logic:\n * 1. Column `format` function (includes typeDefaults merged at config time)\n * 2. DOM cell textContent for columns with custom renderers (visible rows only)\n * 3. Raw value via `formatValueAsText` as final fallback\n */\n #buildText(columns: ColumnConfig[], rows: Record<string, unknown>[], options?: CopyOptions): string {\n const delimiter = options?.delimiter ?? this.config.delimiter ?? '\\t';\n const newline = options?.newline ?? this.config.newline ?? '\\n';\n const includeHeaders = options?.includeHeaders ?? this.config.includeHeaders ?? false;\n const processCell = options?.processCell ?? this.config.processCell;\n\n const lines: string[] = [];\n\n // Header row\n if (includeHeaders) {\n lines.push(columns.map((c) => c.header || c.field).join(delimiter));\n }\n\n // Data rows\n for (const row of rows) {\n const cells = columns.map((col) => {\n const value = resolveCellValue(row, col);\n if (processCell) return processCell(value, col.field, row);\n return this.#formatCellAsDisplayed(col, value, row);\n });\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n }\n\n /**\n * Format a cell value the way the grid displays it.\n *\n * Priority:\n * 1. Column `format` function (includes typeDefaults applied at config merge time)\n * 2. DOM textContent for columns with a custom renderer (virtualized rows only)\n * 3. Raw value via `formatValueAsText`\n */\n #formatCellAsDisplayed(col: ColumnConfig, value: unknown, row: Record<string, unknown>): string {\n // 1. Column format function (covers col.format and typeDefaults)\n if (col.format) {\n try {\n const formatted = col.format(value, row);\n return formatted == null ? '' : String(formatted);\n } catch {\n // Format failed — fall through to next strategy\n }\n }\n\n // 2. DOM textContent for columns with custom renderers\n if (col.renderer || col.viewRenderer) {\n const text = this.#readCellTextFromDOM(col.field, row);\n if (text != null) return text;\n }\n\n // 3. Fallback to raw value formatting\n return formatValueAsText(value);\n }\n\n /**\n * Try to read a cell's displayed text from the DOM.\n *\n * Only works for rows currently rendered in the virtualized viewport.\n * Returns `null` if the row is not in the DOM (caller should fall back).\n */\n #readCellTextFromDOM(field: string, row: Record<string, unknown>): string | null {\n const host = this.gridElement;\n if (!host) return null;\n\n // Find the row index in the grid's current row array\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex === -1) return null;\n\n // Query the rendered cell by row index and field name\n const cell = host.querySelector<HTMLElement>(`.cell[data-row=\"${rowIndex}\"][data-field=\"${field}\"]`);\n if (!cell) return null;\n\n return cell.textContent?.trim() ?? null;\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 * Get the text representation of the current selection (or specified data)\n * without writing to the system clipboard.\n *\n * Useful for previewing what would be copied, or for feeding the text into\n * a custom UI (e.g., a \"copy with column picker\" dialog).\n *\n * @param options - Control which columns/rows to include\n * @returns Delimited text, or empty string if nothing to copy\n *\n * @example Get text for specific columns\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * const text = clipboard.getSelectionAsText({\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * console.log(text);\n * // \"Name\\tEmail\\nAlice\\talice@example.com\\n...\"\n * ```\n */\n getSelectionAsText(options?: CopyOptions): string {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) return '';\n return this.#buildText(columns, rows, options);\n }\n\n /**\n * Copy data to the system clipboard.\n *\n * Without options, copies the current selection (or entire grid if no selection).\n * With options, copies exactly the specified columns and/or rows — ideal for\n * \"copy with column picker\" workflows where the user selects rows first,\n * then chooses which columns to include via a dialog.\n *\n * @param options - Control which columns/rows to include\n * @returns The copied text\n *\n * @example Copy current selection (default)\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * await clipboard.copy();\n * ```\n *\n * @example Copy specific columns from specific rows\n * ```ts\n * // User selected rows in the grid, then picked columns in a dialog\n * const selectedRowIndices = [0, 3, 7];\n * const chosenColumns = ['name', 'department', 'salary'];\n * await clipboard.copy({\n * rowIndices: selectedRowIndices,\n * columns: chosenColumns,\n * includeHeaders: true,\n * });\n * ```\n */\n async copy(options?: CopyOptions): Promise<string> {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) {\n return '';\n }\n\n const text = this.#buildText(columns, rows, options);\n await copyToClipboard(text);\n this.lastCopied = { text, timestamp: Date.now() };\n this.emit<CopyDetail>('copy', {\n text,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n return text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n *\n * Convenience wrapper around {@link copy} for row-based workflows.\n * Supports non-contiguous row indices (e.g., `[0, 3, 7]`).\n *\n * @param indices - Array of row indices to copy\n * @param options - Additional copy options (columns, headers, etc.)\n * @returns The copied text\n *\n * @example\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * // Copy only rows 0 and 5, including just name and email columns\n * await clipboard.copyRows([0, 5], { columns: ['name', 'email'] });\n * ```\n */\n async copyRows(indices: number[], options?: Omit<CopyOptions, 'rowIndices'>): Promise<string> {\n if (indices.length === 0) return '';\n return this.copy({ ...options, rowIndices: indices });\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, CopyOptions, PasteDetail } from './types';\n","/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport { CLIPBOARD_FAILED, warnDiagnostic } from '../../core/internal/diagnostics';\nimport { resolveCellValue } from '../../core/internal/value-accessor';\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) => formatCellValue(resolveCellValue(row, col), col.field, row, config));\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 (err) {\n warnDiagnostic(CLIPBOARD_FAILED, `Clipboard API failed: ${err}`);\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"],"names":["resolveColumns","columns","fields","onlyVisible","result","filter","c","hidden","field","startsWith","meta","utility","length","fieldSet","Set","has","parseClipboardText","text","config","delimiter","newline","normalizedText","replace","rows","currentRow","currentCell","inQuotes","i","char","push","some","trim","defaultPasteHandler","detail","grid","pastedRows","target","currentRows","effectiveConfig","allFields","map","col","editableMap","Map","forEach","set","editable","newRows","maxPasteRow","bounds","endRow","Infinity","rowData","rowOffset","targetRowIndex","row","emptyRow","cellValue","colOffset","get","ClipboardPlugin","BaseGridPlugin","static","queries","type","description","name","required","reason","defaultConfig","includeHeaders","quoteStrings","lastCopied","attach","super","addEventListener","e","this","handleNativePaste","signal","disconnectSignal","detach","handleQuery","query","copy","onKeyDown","event","ctrlKey","metaKey","key","preventDefault","handleCopy","selection","getSelection","ranges","focused","getFocusedCellFromDOM","rowIndices","clipboardData","getData","parsed","firstRange","targetRow","from","targetCol","mode","to","endCol","maxCol","visibleColumns","column","pasteWidth","emit","applyPasteHandler","pasteHandler","responses","resolveData","options","range","minCol","Math","min","max","slice","indices","sort","a","b","r","resolveRows","minRow","maxRow","buildText","processCell","lines","header","join","cells","value","resolveCellValue","formatCellAsDisplayed","format","formatted","String","renderer","viewRenderer","readCellTextFromDOM","Date","toISOString","JSON","stringify","formatValueAsText","host","gridElement","rowIndex","indexOf","cell","querySelector","textContent","closest","dataset","fieldCache","rowIndexStr","parseInt","isNaN","findIndex","getSelectionAsText","async","navigator","clipboard","writeText","err","warnDiagnostic","CLIPBOARD_FAILED","textarea","document","createElement","style","position","opacity","pointerEvents","body","appendChild","select","success","execCommand","removeChild","copyToClipboard","timestamp","now","rowCount","columnCount","copyRows","paste","readText","readFromClipboard","getLastCopied"],"mappings":"2gBAwBO,SAASA,EACdC,EACAC,EACAC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aAAAkL,GACE,OAAOvH,KAAKL,UACd"}
1
+ {"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.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","../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts"],"sourcesContent":["/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\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/**\n * Options for programmatic copy operations.\n *\n * Allows callers to control exactly which columns and rows are included\n * in a copy, independently of the current selection state.\n *\n * @example Copy specific columns from selected rows\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * // User selected rows 0, 2, 4 via a dialog, chose columns to include\n * const text = await clipboard.copy({\n * rowIndices: [0, 2, 4],\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * ```\n */\nexport interface CopyOptions {\n /** Specific column fields to include. If omitted, uses current selection or all visible columns. */\n columns?: string[];\n /** Specific row indices to copy. If omitted, uses current selection or all rows. */\n rowIndices?: number[];\n /** Include column headers in copied text. Defaults to the plugin config value. */\n includeHeaders?: boolean;\n /** Column delimiter override. Defaults to the plugin config value. */\n delimiter?: string;\n /** Row delimiter override. Defaults to the plugin config value. */\n newline?: string;\n /** Custom cell value processor for this operation. Overrides the plugin config's `processCell`. */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n}\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// Module Augmentation - Register plugin name for type-safe getPluginByName()\ndeclare module '../../core/types' {\n interface DataGridEventMap {\n /** Fired after a successful copy operation. Provides the copied text, row count, and column count. @group Clipboard Events */\n 'copy': CopyDetail;\n /** Fired after a paste operation. Provides parsed rows, target cell, and column fields. @group Clipboard Events */\n 'paste': PasteDetail;\n }\n\n interface PluginNameMap {\n clipboard: import('./ClipboardPlugin').ClipboardPlugin;\n }\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 { resolveCellValue } from '../../core/internal/value-accessor';\nimport {\n BaseGridPlugin,\n type GridElement,\n type PluginDependency,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatValueAsText, resolveColumns, resolveRows } from '../shared/data-collection';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type CopyOptions,\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 * ## 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 * @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 SelectionPlugin for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin manifest — declares queries for inter-plugin communication.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [{ type: 'clipboard:copy', description: 'Triggers a copy operation and returns the copied text' }],\n };\n\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 grid.addEventListener('paste', (e) => this.#handleNativePaste(e), {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'clipboard:copy') {\n this.copy();\n return true;\n }\n return undefined;\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 // Prevent the browser's default copy action so it doesn't overwrite\n // our clipboard write with whatever text is selected in the DOM.\n event.preventDefault();\n this.#handleCopy(event.target as HTMLElement);\n return true;\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 from keyboard shortcut.\n *\n * For keyboard-triggered copies, respects the current selection or\n * falls back to the focused cell from the DOM.\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n\n // Selection plugin exists but nothing selected → try focused cell from DOM\n if (selection && selection.ranges.length === 0) {\n const focused = this.#getFocusedCellFromDOM(target);\n if (!focused) return;\n const col = this.columns[focused.col];\n if (!col) return;\n this.copy({ rowIndices: [focused.row], columns: [col.field] });\n return;\n }\n\n // Delegate to the public copy() method (selection or full grid)\n this.copy();\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection via query\n const selection = this.#getSelection();\n const firstRange = selection?.ranges?.[0];\n\n // Determine target cell and bounds\n const targetRow = firstRange?.from.row ?? 0;\n const targetCol = firstRange?.from.col ?? 0;\n\n // Check if multi-cell selection (range with different start/end)\n const isMultiCell =\n firstRange &&\n (selection?.mode === 'range' || selection?.mode === 'row') &&\n (firstRange.from.row !== firstRange.to.row || firstRange.from.col !== firstRange.to.col);\n\n const bounds = isMultiCell ? { endRow: firstRange.to.row, endCol: firstRange.to.col } : null;\n // Selection range indices are visible-column indices (from data-col)\n const maxCol = bounds?.endCol ?? this.visibleColumns.length - 1;\n\n // Build target info\n const column = this.visibleColumns[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.visibleColumns[targetCol + i];\n if (col) {\n fields.push(col.field);\n }\n }\n\n const detail: PasteDetail = { rows: parsed, text, target, fields };\n\n // Emit the event for any listeners\n this.emit<PasteDetail>('paste', detail);\n\n // Apply paste data using the configured handler (or default)\n this.#applyPasteHandler(detail);\n }\n\n /**\n * Apply the paste handler to update grid data.\n *\n * Uses the configured `pasteHandler`, or the default handler if not specified.\n * Set `pasteHandler: null` in config to disable auto-paste.\n */\n #applyPasteHandler(detail: PasteDetail): void {\n if (!this.grid) return;\n\n const { pasteHandler } = this.config;\n\n // pasteHandler: null means explicitly disabled\n if (pasteHandler === null) return;\n\n // Use custom handler or default\n const handler = pasteHandler ?? defaultPasteHandler;\n handler(detail, this.grid);\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection');\n return responses?.[0];\n }\n\n /**\n * Resolve columns and rows to include based on options and/or current selection.\n *\n * Priority for columns:\n * 1. `options.columns` (explicit field list)\n * 2. Selection range column bounds (range/cell mode only)\n * 3. All visible non-utility columns\n *\n * Priority for rows:\n * 1. `options.rowIndices` (explicit indices)\n * 2. Selection range row bounds\n * 3. All rows\n */\n #resolveData(options?: CopyOptions): { columns: ColumnConfig[]; rows: Record<string, unknown>[] } {\n const selection = this.#getSelection();\n\n // --- Columns ---\n let columns: ColumnConfig[];\n if (options?.columns) {\n // Caller specified exact fields\n columns = resolveColumns(this.columns, options.columns);\n } else if (selection?.ranges.length && selection.mode !== 'row') {\n // Range/cell selection: restrict to selection column bounds\n // Selection indices are visible-column indices (from data-col)\n const range = selection.ranges[selection.ranges.length - 1];\n const minCol = Math.min(range.from.col, range.to.col);\n const maxCol = Math.max(range.from.col, range.to.col);\n columns = resolveColumns(this.visibleColumns.slice(minCol, maxCol + 1));\n } else {\n // Row selection or no selection: all visible columns\n columns = resolveColumns(this.columns);\n }\n\n // --- Rows ---\n let rows: Record<string, unknown>[];\n if (options?.rowIndices) {\n // Caller specified exact row indices\n rows = resolveRows(this.rows as Record<string, unknown>[], options.rowIndices);\n } else if (selection?.ranges.length) {\n // Selection range: extract contiguous row range\n const range = selection.ranges[selection.ranges.length - 1];\n const minRow = Math.min(range.from.row, range.to.row);\n const maxRow = Math.max(range.from.row, range.to.row);\n rows = [];\n for (let r = minRow; r <= maxRow; r++) {\n const row = this.rows[r] as Record<string, unknown> | undefined;\n if (row) rows.push(row);\n }\n } else {\n // No selection: all rows\n rows = this.rows as Record<string, unknown>[];\n }\n\n return { columns, rows };\n }\n\n /**\n * Build delimited text from resolved columns and rows.\n *\n * When no `processCell` callback is configured, uses \"copy what you see\" logic:\n * 1. Column `format` function (includes typeDefaults merged at config time)\n * 2. DOM cell textContent for columns with custom renderers (visible rows only)\n * 3. Raw value via `formatValueAsText` as final fallback\n */\n #buildText(columns: ColumnConfig[], rows: Record<string, unknown>[], options?: CopyOptions): string {\n const delimiter = options?.delimiter ?? this.config.delimiter ?? '\\t';\n const newline = options?.newline ?? this.config.newline ?? '\\n';\n const includeHeaders = options?.includeHeaders ?? this.config.includeHeaders ?? false;\n const processCell = options?.processCell ?? this.config.processCell;\n\n const lines: string[] = [];\n\n // Header row\n if (includeHeaders) {\n lines.push(columns.map((c) => c.header || c.field).join(delimiter));\n }\n\n // Data rows\n for (const row of rows) {\n const cells = columns.map((col) => {\n const value = resolveCellValue(row, col);\n if (processCell) return processCell(value, col.field, row);\n return this.#formatCellAsDisplayed(col, value, row);\n });\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n }\n\n /**\n * Format a cell value the way the grid displays it.\n *\n * Priority:\n * 1. Column `format` function (includes typeDefaults applied at config merge time)\n * 2. DOM textContent for columns with a custom renderer (virtualized rows only)\n * 3. Raw value via `formatValueAsText`\n */\n #formatCellAsDisplayed(col: ColumnConfig, value: unknown, row: Record<string, unknown>): string {\n // 1. Column format function (covers col.format and typeDefaults)\n if (col.format) {\n try {\n const formatted = col.format(value, row);\n return formatted == null ? '' : String(formatted);\n } catch {\n // Format failed — fall through to next strategy\n }\n }\n\n // 2. DOM textContent for columns with custom renderers\n if (col.renderer || col.viewRenderer) {\n const text = this.#readCellTextFromDOM(col.field, row);\n if (text != null) return text;\n }\n\n // 3. Fallback to raw value formatting\n return formatValueAsText(value);\n }\n\n /**\n * Try to read a cell's displayed text from the DOM.\n *\n * Only works for rows currently rendered in the virtualized viewport.\n * Returns `null` if the row is not in the DOM (caller should fall back).\n */\n #readCellTextFromDOM(field: string, row: Record<string, unknown>): string | null {\n const host = this.gridElement;\n if (!host) return null;\n\n // Find the row index in the grid's current row array\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex === -1) return null;\n\n // Query the rendered cell by row index and field name\n const cell = host.querySelector<HTMLElement>(`.cell[data-row=\"${rowIndex}\"][data-field=\"${field}\"]`);\n if (!cell) return null;\n\n return cell.textContent?.trim() ?? null;\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 * Get the text representation of the current selection (or specified data)\n * without writing to the system clipboard.\n *\n * Useful for previewing what would be copied, or for feeding the text into\n * a custom UI (e.g., a \"copy with column picker\" dialog).\n *\n * @param options - Control which columns/rows to include\n * @returns Delimited text, or empty string if nothing to copy\n *\n * @example Get text for specific columns\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * const text = clipboard.getSelectionAsText({\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * console.log(text);\n * // \"Name\\tEmail\\nAlice\\talice@example.com\\n...\"\n * ```\n */\n getSelectionAsText(options?: CopyOptions): string {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) return '';\n return this.#buildText(columns, rows, options);\n }\n\n /**\n * Copy data to the system clipboard.\n *\n * Without options, copies the current selection (or entire grid if no selection).\n * With options, copies exactly the specified columns and/or rows — ideal for\n * \"copy with column picker\" workflows where the user selects rows first,\n * then chooses which columns to include via a dialog.\n *\n * @param options - Control which columns/rows to include\n * @returns The copied text\n *\n * @example Copy current selection (default)\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * await clipboard.copy();\n * ```\n *\n * @example Copy specific columns from specific rows\n * ```ts\n * // User selected rows in the grid, then picked columns in a dialog\n * const selectedRowIndices = [0, 3, 7];\n * const chosenColumns = ['name', 'department', 'salary'];\n * await clipboard.copy({\n * rowIndices: selectedRowIndices,\n * columns: chosenColumns,\n * includeHeaders: true,\n * });\n * ```\n */\n async copy(options?: CopyOptions): Promise<string> {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) {\n return '';\n }\n\n const text = this.#buildText(columns, rows, options);\n await copyToClipboard(text);\n this.lastCopied = { text, timestamp: Date.now() };\n this.emit<CopyDetail>('copy', {\n text,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n return text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n *\n * Convenience wrapper around {@link copy} for row-based workflows.\n * Supports non-contiguous row indices (e.g., `[0, 3, 7]`).\n *\n * @param indices - Array of row indices to copy\n * @param options - Additional copy options (columns, headers, etc.)\n * @returns The copied text\n *\n * @example\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * // Copy only rows 0 and 5, including just name and email columns\n * await clipboard.copyRows([0, 5], { columns: ['name', 'email'] });\n * ```\n */\n async copyRows(indices: number[], options?: Omit<CopyOptions, 'rowIndices'>): Promise<string> {\n if (indices.length === 0) return '';\n return this.copy({ ...options, rowIndices: indices });\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, CopyOptions, PasteDetail } from './types';\n","/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport { CLIPBOARD_FAILED, warnDiagnostic } from '../../core/internal/diagnostics';\nimport { resolveCellValue } from '../../core/internal/value-accessor';\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) => formatCellValue(resolveCellValue(row, col), col.field, row, config));\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 (err) {\n warnDiagnostic(CLIPBOARD_FAILED, `Clipboard API failed: ${err}`);\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"],"names":["resolveColumns","columns","fields","onlyVisible","result","filter","c","hidden","field","startsWith","utility","length","fieldSet","Set","has","parseClipboardText","text","config","delimiter","newline","normalizedText","replace","rows","currentRow","currentCell","inQuotes","i","char","push","some","trim","defaultPasteHandler","detail","grid","pastedRows","target","currentRows","effectiveConfig","allFields","map","col","editableMap","Map","forEach","set","editable","newRows","maxPasteRow","bounds","endRow","Infinity","rowData","rowOffset","targetRowIndex","row","emptyRow","cellValue","colOffset","get","ClipboardPlugin","BaseGridPlugin","static","queries","type","description","name","required","reason","defaultConfig","includeHeaders","quoteStrings","lastCopied","attach","super","addEventListener","e","this","handleNativePaste","signal","disconnectSignal","detach","handleQuery","query","copy","onKeyDown","event","ctrlKey","metaKey","key","preventDefault","handleCopy","selection","getSelection","ranges","focused","getFocusedCellFromDOM","rowIndices","clipboardData","getData","parsed","firstRange","targetRow","from","targetCol","mode","to","endCol","maxCol","visibleColumns","column","pasteWidth","emit","applyPasteHandler","pasteHandler","responses","resolveData","options","range","minCol","Math","min","max","slice","indices","sort","a","b","r","resolveRows","minRow","maxRow","buildText","processCell","lines","header","join","cells","value","resolveCellValue","formatCellAsDisplayed","format","formatted","String","renderer","viewRenderer","readCellTextFromDOM","Date","toISOString","JSON","stringify","formatValueAsText","host","gridElement","rowIndex","indexOf","cell","querySelector","textContent","closest","dataset","fieldCache","rowIndexStr","parseInt","isNaN","findIndex","getSelectionAsText","async","navigator","clipboard","writeText","err","warnDiagnostic","CLIPBOARD_FAILED","textarea","document","createElement","style","position","opacity","pointerEvents","body","appendChild","select","success","execCommand","removeChild","copyToClipboard","timestamp","now","rowCount","columnCount","copyRows","paste","readText","readFromClipboard","getLastCopied"],"mappings":"2gBAwBO,SAASA,EACdC,EACAC,EACAC,GAAc,GAEd,IAAIC,EAASH,EAMb,GAJIE,IACFC,EAASA,EAAOC,OAAQC,IAAOA,EAAEC,SAAWD,EAAEE,MAAMC,WAAW,QAAuB,IAAdH,EAAEI,UAGxER,GAAQS,OAAQ,CAClB,MAAMC,EAAW,IAAIC,IAAIX,GACzBE,EAASA,EAAOC,OAAQC,GAAMM,EAASE,IAAIR,EAAEE,OAC/C,CAEA,OAAOJ,CACT,CCpBO,SAASW,EAAmBC,EAAcC,GAC/C,MAAMC,EAAYD,EAAOC,WAAa,KAChCC,EA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8F,GAQ5C,aC1aJkD,eAAsCtJ,GACpC,IAEE,aADMuJ,UAAUC,UAAUC,UAAUzJ,IAC7B,CACT,OAAS0J,GACPC,EAAAA,eAAeC,EAAAA,iBAAkB,yBAAyBF,KAE1D,MAAMG,EAAWC,SAASC,cAAc,YACxCF,EAASpC,MAAQzH,EACjB6J,EAASG,MAAMC,SAAW,QAC1BJ,EAASG,MAAME,QAAU,IACzBL,EAASG,MAAMG,cAAgB,OAC/BL,SAASM,KAAKC,YAAYR,GAC1BA,EAASS,SACT,MAAMC,EAAUT,SAASU,YAAY,QAErC,OADAV,SAASM,KAAKK,YAAYZ,GACnBU,CACT,CACF,CDiZUG,CAAgB1K,GACtB4D,KAAKL,WAAa,CAAEvD,OAAM2K,UAAWzC,KAAK0C,OAC1ChH,KAAKmC,KAAiB,OAAQ,CAC5B/F,OACA6K,SAAUvK,EAAKX,OACfmL,YAAa7L,EAAQU,SAEhBK,CACT,CAmBA,cAAM+K,CAASpE,EAAmBP,GAChC,OAAuB,IAAnBO,EAAQhH,OAAqB,GAC1BiE,KAAKO,KAAK,IAAKiC,EAASpB,WAAY2B,GAC7C,CAMA,WAAMqE,GACJ,MAAMhL,QFreVsJ,iBACE,IACE,aAAaC,UAAUC,UAAUyB,UACnC,CAAA,MAEE,MAAO,EACT,CACF,CE8duBC,GACnB,OAAKlL,EACED,EAAmBC,EAAM4D,KAAK3D,QADnB,IAEpB,CAMA,aAAAkL,GACE,OAAOvH,KAAKL,UACd"}
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/value-accessor"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/value-accessor","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_export={},e.TbwGrid,e.TbwGrid)}(this,function(e,t,n){"use strict";function o(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}function r(e,t=!0){if(null==e)return"";if(e instanceof Date)return e.toISOString();if("object"==typeof e)return JSON.stringify(e);const n=String(e);return t&&(n.includes(",")||n.includes('"')||n.includes("\n")||n.includes("\r"))?`"${n.replace(/"/g,'""')}"`:n}function s(e,t){const n=URL.createObjectURL(e),o=document.createElement("a");o.href=n,o.download=t,o.style.display="none",document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(n)}function l(e){return JSON.stringify(i(e))}function i(e){if(null==e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(i);const t={};for(const n of Object.keys(e).sort())t[n]=i(e[n]);return t}class c{#e=new Map;#t=0;register(e){const t=l(e),n=this.#e.get(t);if(n)return n.id;this.#t++;const o=`s${this.#t}`;return this.#e.set(t,{id:o,style:e}),o}getStyleId(e){return this.#e.get(l(e))?.id}get size(){return this.#e.size}toXml(){if(0===this.#e.size)return"";let e="\n<Styles>";for(const{id:t,style:n}of this.#e.values())e+=a(t,n);return e+="\n</Styles>",e}}function a(e,t){let n=`\n<Style ss:ID="${e}">`;if(t.font&&(n+="<Font",t.font.name&&(n+=` ss:FontName="${t.font.name}"`),t.font.size&&(n+=` ss:Size="${t.font.size}"`),t.font.bold&&(n+=' ss:Bold="1"'),t.font.italic&&(n+=' ss:Italic="1"'),t.font.color&&(n+=` ss:Color="${t.font.color}"`),n+="/>"),t.fill){const e=t.fill.pattern??"Solid";n+=`<Interior ss:Color="${t.fill.color}" ss:Pattern="${e}"/>`}return t.numberFormat&&(n+=`<NumberFormat ss:Format="${t.numberFormat}"/>`),t.alignment&&(n+="<Alignment",t.alignment.horizontal&&(n+=` ss:Horizontal="${t.alignment.horizontal}"`),t.alignment.vertical&&(n+=` ss:Vertical="${t.alignment.vertical}"`),t.alignment.wrapText&&(n+=' ss:WrapText="1"'),n+="/>"),t.borders&&(n+="<Borders>",t.borders.top&&(n+=f("Top",t.borders.top)),t.borders.bottom&&(n+=f("Bottom",t.borders.bottom)),t.borders.left&&(n+=f("Left",t.borders.left)),t.borders.right&&(n+=f("Right",t.borders.right)),n+="</Borders>"),n+="</Style>",n}function f(e,t){let n=`<Border ss:Position="${e}" ss:LineStyle="Continuous" ss:Weight="${function(e){switch(e){case"Thin":return 1;case"Medium":return 2;case"Thick":return 3}}(t.style)}"`;return t.color&&(n+=` ss:Color="${t.color}"`),n+="/>",n}function u(e,t,n,o,r){if(t.cellStyle){const s=t.cellStyle(n,o,r);if(s)return e.register(s)}const s=t.columnStyles?.[o];return s?e.getStyleId(s):t.defaultStyle?e.getStyleId(t.defaultStyle):void 0}function d(e,t){const n=Math.min(t.length,50);let o=(e.header??e.field).length;for(let r=0;r<n;r++){const n=t[r][e.field],s=null==n?0:String(n).length;s>o&&(o=s)}return o+2}function p(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function m(e,n,o){const r=o.excelStyles,s=r?function(e){const t=new c;if(e.headerStyle&&t.register(e.headerStyle),e.defaultStyle&&t.register(e.defaultStyle),e.columnStyles)for(const n of Object.values(e.columnStyles))t.register(n);return t}(r):void 0;let l='<?xml version="1.0" encoding="UTF-8"?>\n<?mso-application progid="Excel.Sheet"?>\n<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"\n xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">';if(s){if(r.cellStyle)for(const o of e)for(const e of n){const n=t.resolveCellValue(o,e),l=r.cellStyle(n,e.field,o);l&&s.register(l)}l+=s.toXml()}l+='\n<Worksheet ss:Name="Sheet1">\n<Table>',r&&(l+=function(e,t,n){const o=n.columnWidths,r=n.autoFitColumns;if(!o&&!r)return"";let s="";for(const l of e){let e=o?.[l.field];null==e&&r&&(e=d(l,t)),s+=null!=e?`\n<Column ss:Width="${7*e}"/>`:"\n<Column/>"}return s}(n,e,r));const i=r?.headerStyle&&s?s.getStyleId(r.headerStyle):void 0;if(!1!==o.includeHeaders){l+="\n<Row>";for(const e of n){const t=e.header||e.field;l+=`<Cell${i?` ss:StyleID="${i}"`:""}><Data ss:Type="String">${p(o.processHeader?o.processHeader(t,e.field):t)}</Data></Cell>`}l+="</Row>"}for(const c of e){l+="\n<Row>";for(const e of n){let n=t.resolveCellValue(c,e);o.processCell&&(n=o.processCell(n,e.field,c));let i="String",a="";null==n?a="":"number"!=typeof n||isNaN(n)?n instanceof Date?(i="DateTime",a=n.toISOString()):a=p(String(n)):(i="Number",a=String(n));const f=s&&r?u(s,r,n,e.field,c):void 0;l+=`<Cell${f?` ss:StyleID="${f}"`:""}><Data ss:Type="${i}">${a}</Data></Cell>`}l+="</Row>"}return l+="\n</Table>\n</Worksheet>\n</Workbook>",l}class g extends n.BaseGridPlugin{static manifest={queries:[{type:"export:csv",description:"Triggers a CSV export"}]};name="export";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;handleQuery(e){if("export:csv"===e.type)return this.exportCsv(),!0}performExport(e,n){const l=this.config,i={format:e,fileName:n?.fileName??l.fileName??"export",includeHeaders:n?.includeHeaders??l.includeHeaders,processCell:n?.processCell,processHeader:n?.processHeader,columns:n?.columns,rowIndices:n?.rowIndices,excelStyles:n?.excelStyles,fileExtension:n?.fileExtension},c=function(e,t,n=!0){let o=e;if(n&&(o=o.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.meta?.utility)),t?.length){const e=new Set(t);o=o.filter(t=>e.has(t.field))}return o}(this.columns,n?.columns,l.onlyVisible);let a;if(n?.rowIndices)a=o(this.rows,n.rowIndices);else if(l.onlySelected){const e=this.getSelectionState();a=e?.selected?.size?o(this.rows,[...e.selected]):[...this.rows]}else a=[...this.rows];this.isExportingFlag=!0;let f=i.fileName;try{switch(e){case"csv":{const e=function(e,n,o,s={}){const l=s.delimiter??",",i=s.newline??"\n",c=[],a=s.bom?"\ufeff":"";if(!1!==o.includeHeaders){const e=n.map(e=>{const t=e.header||e.field;return r(o.processHeader?o.processHeader(t,e.field):t)});c.push(e.join(l))}for(const f of e){const e=n.map(e=>{let n=t.resolveCellValue(f,e);return o.processCell&&(n=o.processCell(n,e.field,f)),r(n)});c.push(e.join(l))}return a+c.join(i)}(a,c,i,{bom:!0});f=f.endsWith(".csv")?f:`${f}.csv`,function(e,t){s(new Blob([e],{type:"text/csv;charset=utf-8;"}),t)}(e,f);break}case"excel":{const e=m(a,c,i),t=i.fileExtension??".xls",n=t.startsWith(".")?t:`.${t}`;f=f.endsWith(n)?f:`${f}${n}`,function(e,t){s(new Blob([e],{type:"application/vnd.ms-excel;charset=utf-8;"}),t)}(e,f);break}case"json":{const e=a.map(e=>{const n={};for(const o of c){let r=t.resolveCellValue(e,o);i.processCell&&(r=i.processCell(r,o.field,e)),n[o.field]=r}return n}),n=JSON.stringify(e,null,2);f=f.endsWith(".json")?f:`${f}.json`;s(new Blob([n],{type:"application/json"}),f);break}}this.lastExportInfo={format:e,timestamp:new Date},this.emit("export-complete",{format:e,fileName:f,rowCount:a.length,columnCount:c.length})}finally{this.isExportingFlag=!1}}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}exportCsv(e){this.performExport("csv",e)}exportExcel(e){this.performExport("excel",e)}exportJson(e){this.performExport("json",e)}isExporting(){return this.isExportingFlag}getLastExport(){return this.lastExportInfo}}e.ExportPlugin=g,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/value-accessor"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/value-accessor","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_export={},e.TbwGrid,e.TbwGrid)}(this,function(e,t,n){"use strict";function o(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}function r(e,t=!0){if(null==e)return"";if(e instanceof Date)return e.toISOString();if("object"==typeof e)return JSON.stringify(e);const n=String(e);return t&&(n.includes(",")||n.includes('"')||n.includes("\n")||n.includes("\r"))?`"${n.replace(/"/g,'""')}"`:n}function s(e,t){const n=URL.createObjectURL(e),o=document.createElement("a");o.href=n,o.download=t,o.style.display="none",document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(n)}function l(e){return JSON.stringify(i(e))}function i(e){if(null==e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(i);const t={};for(const n of Object.keys(e).sort())t[n]=i(e[n]);return t}class c{#e=new Map;#t=0;register(e){const t=l(e),n=this.#e.get(t);if(n)return n.id;this.#t++;const o=`s${this.#t}`;return this.#e.set(t,{id:o,style:e}),o}getStyleId(e){return this.#e.get(l(e))?.id}get size(){return this.#e.size}toXml(){if(0===this.#e.size)return"";let e="\n<Styles>";for(const{id:t,style:n}of this.#e.values())e+=a(t,n);return e+="\n</Styles>",e}}function a(e,t){let n=`\n<Style ss:ID="${e}">`;if(t.font&&(n+="<Font",t.font.name&&(n+=` ss:FontName="${t.font.name}"`),t.font.size&&(n+=` ss:Size="${t.font.size}"`),t.font.bold&&(n+=' ss:Bold="1"'),t.font.italic&&(n+=' ss:Italic="1"'),t.font.color&&(n+=` ss:Color="${t.font.color}"`),n+="/>"),t.fill){const e=t.fill.pattern??"Solid";n+=`<Interior ss:Color="${t.fill.color}" ss:Pattern="${e}"/>`}return t.numberFormat&&(n+=`<NumberFormat ss:Format="${t.numberFormat}"/>`),t.alignment&&(n+="<Alignment",t.alignment.horizontal&&(n+=` ss:Horizontal="${t.alignment.horizontal}"`),t.alignment.vertical&&(n+=` ss:Vertical="${t.alignment.vertical}"`),t.alignment.wrapText&&(n+=' ss:WrapText="1"'),n+="/>"),t.borders&&(n+="<Borders>",t.borders.top&&(n+=f("Top",t.borders.top)),t.borders.bottom&&(n+=f("Bottom",t.borders.bottom)),t.borders.left&&(n+=f("Left",t.borders.left)),t.borders.right&&(n+=f("Right",t.borders.right)),n+="</Borders>"),n+="</Style>",n}function f(e,t){let n=`<Border ss:Position="${e}" ss:LineStyle="Continuous" ss:Weight="${function(e){switch(e){case"Thin":return 1;case"Medium":return 2;case"Thick":return 3}}(t.style)}"`;return t.color&&(n+=` ss:Color="${t.color}"`),n+="/>",n}function u(e,t,n,o,r){if(t.cellStyle){const s=t.cellStyle(n,o,r);if(s)return e.register(s)}const s=t.columnStyles?.[o];return s?e.getStyleId(s):t.defaultStyle?e.getStyleId(t.defaultStyle):void 0}function d(e,t){const n=Math.min(t.length,50);let o=(e.header??e.field).length;for(let r=0;r<n;r++){const n=t[r][e.field],s=null==n?0:String(n).length;s>o&&(o=s)}return o+2}function p(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function m(e,n,o){const r=o.excelStyles,s=r?function(e){const t=new c;if(e.headerStyle&&t.register(e.headerStyle),e.defaultStyle&&t.register(e.defaultStyle),e.columnStyles)for(const n of Object.values(e.columnStyles))t.register(n);return t}(r):void 0;let l='<?xml version="1.0" encoding="UTF-8"?>\n<?mso-application progid="Excel.Sheet"?>\n<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"\n xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">';if(s){if(r.cellStyle)for(const o of e)for(const e of n){const n=t.resolveCellValue(o,e),l=r.cellStyle(n,e.field,o);l&&s.register(l)}l+=s.toXml()}l+='\n<Worksheet ss:Name="Sheet1">\n<Table>',r&&(l+=function(e,t,n){const o=n.columnWidths,r=n.autoFitColumns;if(!o&&!r)return"";let s="";for(const l of e){let e=o?.[l.field];null==e&&r&&(e=d(l,t)),s+=null!=e?`\n<Column ss:Width="${7*e}"/>`:"\n<Column/>"}return s}(n,e,r));const i=r?.headerStyle&&s?s.getStyleId(r.headerStyle):void 0;if(!1!==o.includeHeaders){l+="\n<Row>";for(const e of n){const t=e.header||e.field;l+=`<Cell${i?` ss:StyleID="${i}"`:""}><Data ss:Type="String">${p(o.processHeader?o.processHeader(t,e.field):t)}</Data></Cell>`}l+="</Row>"}for(const c of e){l+="\n<Row>";for(const e of n){let n=t.resolveCellValue(c,e);o.processCell&&(n=o.processCell(n,e.field,c));let i="String",a="";null==n?a="":"number"!=typeof n||isNaN(n)?n instanceof Date?(i="DateTime",a=n.toISOString()):a=p(String(n)):(i="Number",a=String(n));const f=s&&r?u(s,r,n,e.field,c):void 0;l+=`<Cell${f?` ss:StyleID="${f}"`:""}><Data ss:Type="${i}">${a}</Data></Cell>`}l+="</Row>"}return l+="\n</Table>\n</Worksheet>\n</Workbook>",l}class g extends n.BaseGridPlugin{static manifest={queries:[{type:"export:csv",description:"Triggers a CSV export"}]};name="export";get defaultConfig(){return{fileName:"export",includeHeaders:!0,onlyVisible:!0,onlySelected:!1}}isExportingFlag=!1;lastExportInfo=null;handleQuery(e){if("export:csv"===e.type)return this.exportCsv(),!0}performExport(e,n){const l=this.config,i={format:e,fileName:n?.fileName??l.fileName??"export",includeHeaders:n?.includeHeaders??l.includeHeaders,processCell:n?.processCell,processHeader:n?.processHeader,columns:n?.columns,rowIndices:n?.rowIndices,excelStyles:n?.excelStyles,fileExtension:n?.fileExtension},c=function(e,t,n=!0){let o=e;if(n&&(o=o.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.utility)),t?.length){const e=new Set(t);o=o.filter(t=>e.has(t.field))}return o}(this.columns,n?.columns,l.onlyVisible);let a;if(n?.rowIndices)a=o(this.rows,n.rowIndices);else if(l.onlySelected){const e=this.getSelectionState();a=e?.selected?.size?o(this.rows,[...e.selected]):[...this.rows]}else a=[...this.rows];this.isExportingFlag=!0;let f=i.fileName;try{switch(e){case"csv":{const e=function(e,n,o,s={}){const l=s.delimiter??",",i=s.newline??"\n",c=[],a=s.bom?"\ufeff":"";if(!1!==o.includeHeaders){const e=n.map(e=>{const t=e.header||e.field;return r(o.processHeader?o.processHeader(t,e.field):t)});c.push(e.join(l))}for(const f of e){const e=n.map(e=>{let n=t.resolveCellValue(f,e);return o.processCell&&(n=o.processCell(n,e.field,f)),r(n)});c.push(e.join(l))}return a+c.join(i)}(a,c,i,{bom:!0});f=f.endsWith(".csv")?f:`${f}.csv`,function(e,t){s(new Blob([e],{type:"text/csv;charset=utf-8;"}),t)}(e,f);break}case"excel":{const e=m(a,c,i),t=i.fileExtension??".xls",n=t.startsWith(".")?t:`.${t}`;f=f.endsWith(n)?f:`${f}${n}`,function(e,t){s(new Blob([e],{type:"application/vnd.ms-excel;charset=utf-8;"}),t)}(e,f);break}case"json":{const e=a.map(e=>{const n={};for(const o of c){let r=t.resolveCellValue(e,o);i.processCell&&(r=i.processCell(r,o.field,e)),n[o.field]=r}return n}),n=JSON.stringify(e,null,2);f=f.endsWith(".json")?f:`${f}.json`;s(new Blob([n],{type:"application/json"}),f);break}}this.lastExportInfo={format:e,timestamp:new Date},this.emit("export-complete",{format:e,fileName:f,rowCount:a.length,columnCount:c.length})}finally{this.isExportingFlag=!1}}getSelectionState(){try{return this.grid?.getPluginState?.("selection")??null}catch{return null}}exportCsv(e){this.performExport("csv",e)}exportExcel(e){this.performExport("excel",e)}exportJson(e){this.performExport("json",e)}isExporting(){return this.isExportingFlag}getLastExport(){return this.lastExportInfo}}e.ExportPlugin=g,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=export.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"export.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../libs/grid/src/lib/plugins/export/csv.ts","../../../../../libs/grid/src/lib/plugins/export/excel-styles.ts","../../../../../libs/grid/src/lib/plugins/export/excel.ts","../../../../../libs/grid/src/lib/plugins/export/ExportPlugin.ts"],"sourcesContent":["/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.meta?.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n","/**\n * CSV Export Utilities\n *\n * Functions for building and downloading CSV content.\n */\n\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport type { ColumnConfig } from '../../core/types';\nimport type { ExportParams } from './types';\n\n/** CSV export options */\nexport interface CsvOptions {\n /** Field delimiter (default: ',') */\n delimiter?: string;\n /** Line separator (default: '\\n') */\n newline?: string;\n /** Whether to quote strings containing special characters (default: true) */\n quoteStrings?: boolean;\n /** Add UTF-8 BOM for Excel compatibility (default: false) */\n bom?: boolean;\n}\n\n/**\n * Format a value for CSV output.\n * Handles null, Date, objects, and strings with special characters.\n */\nexport function formatCsvValue(value: any, quote = true): string {\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\n // Quote if contains special characters (comma, quote, newline)\n if (quote && (str.includes(',') || str.includes('\"') || str.includes('\\n') || str.includes('\\r'))) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build CSV content from rows and columns.\n */\nexport function buildCsv(rows: any[], columns: ColumnConfig[], params: ExportParams, options: CsvOptions = {}): string {\n const delimiter = options.delimiter ?? ',';\n const newline = options.newline ?? '\\n';\n const lines: string[] = [];\n\n // UTF-8 BOM for Excel compatibility\n const bom = options.bom ? '\\uFEFF' : '';\n\n // Build header row\n if (params.includeHeaders !== false) {\n const headerRow = columns.map((col) => {\n const header = col.header || col.field;\n const processed = params.processHeader ? params.processHeader(header, col.field) : header;\n return formatCsvValue(processed);\n });\n lines.push(headerRow.join(delimiter));\n }\n\n // Build data rows\n for (const row of rows) {\n const cells = columns.map((col) => {\n let value = resolveCellValue(row, col);\n if (params.processCell) {\n value = params.processCell(value, col.field, row);\n }\n return formatCsvValue(value);\n });\n lines.push(cells.join(delimiter));\n }\n\n return bom + lines.join(newline);\n}\n\n/**\n * Download a Blob as a file.\n */\nexport function downloadBlob(blob: Blob, fileName: string): void {\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = fileName;\n link.style.display = 'none';\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n\n/**\n * Download CSV content as a file.\n */\nexport function downloadCsv(content: string, fileName: string): void {\n const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });\n downloadBlob(blob, fileName);\n}\n","/**\n * Excel Style Engine\n *\n * Builds a deduplicated `<Styles>` block for XML Spreadsheet 2003.\n * Collects unique ExcelCellStyle objects, assigns ss:StyleID values,\n * and generates the corresponding XML.\n */\n\nimport type { ExcelBorder, ExcelCellStyle, ExcelStyleConfig } from './types';\n\n// #region Style Hashing\n\n/**\n * Produce a deterministic string key for a style object.\n * Two structurally identical styles produce the same hash.\n * Recursively sorts object keys for order-independent comparison.\n */\nfunction hashStyle(style: ExcelCellStyle): string {\n return JSON.stringify(sortKeys(style));\n}\n\n/** Recursively sort object keys for deterministic serialization. */\nfunction sortKeys(obj: unknown): unknown {\n if (obj == null || typeof obj !== 'object') return obj;\n if (Array.isArray(obj)) return obj.map(sortKeys);\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = sortKeys((obj as Record<string, unknown>)[key]);\n }\n return sorted;\n}\n\n// #endregion\n\n// #region Style Registry\n\n/** Maps a hash → style ID and the original style. */\nexport interface StyleEntry {\n id: string;\n style: ExcelCellStyle;\n}\n\n/**\n * Collects unique styles and assigns each an `ss:StyleID`.\n * Register styles via `register()`, then call `getStyleId()` to look up\n * the ID for a given style, and `toXml()` to emit the `<Styles>` block.\n */\nexport class StyleRegistry {\n /** hash → StyleEntry */\n #entries = new Map<string, StyleEntry>();\n #counter = 0;\n\n /**\n * Register a style and return its assigned ID.\n * If an identical style was already registered, returns the existing ID.\n */\n register(style: ExcelCellStyle): string {\n const hash = hashStyle(style);\n const existing = this.#entries.get(hash);\n if (existing) return existing.id;\n\n this.#counter++;\n const id = `s${this.#counter}`;\n this.#entries.set(hash, { id, style });\n return id;\n }\n\n /** Look up the ID previously assigned to a style (or undefined). */\n getStyleId(style: ExcelCellStyle): string | undefined {\n return this.#entries.get(hashStyle(style))?.id;\n }\n\n /** Number of unique styles registered so far. */\n get size(): number {\n return this.#entries.size;\n }\n\n /** Emit the full `<Styles>…</Styles>` XML fragment, or empty string if no styles. */\n toXml(): string {\n if (this.#entries.size === 0) return '';\n\n let xml = '\\n<Styles>';\n for (const { id, style } of this.#entries.values()) {\n xml += buildStyleElement(id, style);\n }\n xml += '\\n</Styles>';\n return xml;\n }\n}\n\n// #endregion\n\n// #region XML Builders\n\nfunction buildStyleElement(id: string, style: ExcelCellStyle): string {\n let xml = `\\n<Style ss:ID=\"${id}\">`;\n\n if (style.font) {\n xml += '<Font';\n if (style.font.name) xml += ` ss:FontName=\"${style.font.name}\"`;\n if (style.font.size) xml += ` ss:Size=\"${style.font.size}\"`;\n if (style.font.bold) xml += ' ss:Bold=\"1\"';\n if (style.font.italic) xml += ' ss:Italic=\"1\"';\n if (style.font.color) xml += ` ss:Color=\"${style.font.color}\"`;\n xml += '/>';\n }\n\n if (style.fill) {\n const pattern = style.fill.pattern ?? 'Solid';\n xml += `<Interior ss:Color=\"${style.fill.color}\" ss:Pattern=\"${pattern}\"/>`;\n }\n\n if (style.numberFormat) {\n xml += `<NumberFormat ss:Format=\"${style.numberFormat}\"/>`;\n }\n\n if (style.alignment) {\n xml += '<Alignment';\n if (style.alignment.horizontal) xml += ` ss:Horizontal=\"${style.alignment.horizontal}\"`;\n if (style.alignment.vertical) xml += ` ss:Vertical=\"${style.alignment.vertical}\"`;\n if (style.alignment.wrapText) xml += ' ss:WrapText=\"1\"';\n xml += '/>';\n }\n\n if (style.borders) {\n xml += '<Borders>';\n if (style.borders.top) xml += buildBorderElement('Top', style.borders.top);\n if (style.borders.bottom) xml += buildBorderElement('Bottom', style.borders.bottom);\n if (style.borders.left) xml += buildBorderElement('Left', style.borders.left);\n if (style.borders.right) xml += buildBorderElement('Right', style.borders.right);\n xml += '</Borders>';\n }\n\n xml += '</Style>';\n return xml;\n}\n\nfunction buildBorderElement(position: string, border: ExcelBorder): string {\n let xml = `<Border ss:Position=\"${position}\" ss:LineStyle=\"Continuous\" ss:Weight=\"${borderWeight(border.style)}\"`;\n if (border.color) xml += ` ss:Color=\"${border.color}\"`;\n xml += '/>';\n return xml;\n}\n\nfunction borderWeight(style: ExcelBorder['style']): number {\n switch (style) {\n case 'Thin':\n return 1;\n case 'Medium':\n return 2;\n case 'Thick':\n return 3;\n }\n}\n\n// #endregion\n\n// #region Style Resolution\n\n/**\n * Build a StyleRegistry pre-populated with all styles declared in the config.\n * This covers headerStyle, defaultStyle, and columnStyles.\n * (cellStyle callbacks are resolved per-cell at render time.)\n */\nexport function buildStyleRegistry(config: ExcelStyleConfig): StyleRegistry {\n const registry = new StyleRegistry();\n\n if (config.headerStyle) registry.register(config.headerStyle);\n\n if (config.defaultStyle) registry.register(config.defaultStyle);\n\n if (config.columnStyles) {\n for (const style of Object.values(config.columnStyles)) {\n registry.register(style);\n }\n }\n\n return registry;\n}\n\n/**\n * Resolve the style ID for a data cell. Precedence (highest → lowest):\n * 1. cellStyle callback return value\n * 2. columnStyles[field]\n * 3. defaultStyle\n */\nexport function resolveDataStyleId(\n registry: StyleRegistry,\n config: ExcelStyleConfig,\n value: unknown,\n field: string,\n row: unknown,\n): string | undefined {\n // 1. Dynamic cell callback\n if (config.cellStyle) {\n const dynamic = config.cellStyle(value, field, row);\n if (dynamic) {\n // Register on-the-fly (dedup handles repeats)\n return registry.register(dynamic);\n }\n }\n\n // 2. Per-column override\n const colStyle = config.columnStyles?.[field];\n if (colStyle) return registry.getStyleId(colStyle);\n\n // 3. Default\n if (config.defaultStyle) return registry.getStyleId(config.defaultStyle);\n\n return undefined;\n}\n\n// #endregion\n\n// #region Column Widths\n\n/** Character width → Excel column width approximation (px ≈ chars × 7) */\nconst CHAR_WIDTH = 7;\n\n/**\n * Build `<Column>` elements for explicit or auto-fit widths.\n */\nexport function buildColumnWidthsXml(\n columns: { field: string; header?: string }[],\n rows: Record<string, unknown>[],\n config: ExcelStyleConfig,\n): string {\n const widths = config.columnWidths;\n const autoFit = config.autoFitColumns;\n\n if (!widths && !autoFit) return '';\n\n let xml = '';\n for (const col of columns) {\n let width: number | undefined = widths?.[col.field];\n\n if (width == null && autoFit) {\n width = autoFitWidth(col, rows);\n }\n\n if (width != null) {\n xml += `\\n<Column ss:Width=\"${width * CHAR_WIDTH}\"/>`;\n } else {\n // Emit an empty column entry to keep ordinal alignment\n xml += '\\n<Column/>';\n }\n }\n\n return xml;\n}\n\n/** Estimate width from header + first N data rows (capped at 50). */\nfunction autoFitWidth(col: { field: string; header?: string }, rows: Record<string, unknown>[]): number {\n const sampleSize = Math.min(rows.length, 50);\n let maxLen = (col.header ?? col.field).length;\n\n for (let i = 0; i < sampleSize; i++) {\n const val = rows[i][col.field];\n const len = val == null ? 0 : String(val).length;\n if (len > maxLen) maxLen = len;\n }\n\n // Add a small padding\n return maxLen + 2;\n}\n\n// #endregion\n","/**\n * Excel Export Utilities\n *\n * Simple Excel XML format export (no external dependencies).\n * Produces XML Spreadsheet 2003 format which opens in Excel.\n */\n\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport type { ColumnConfig } from '../../core/types';\nimport { downloadBlob } from './csv';\nimport { buildColumnWidthsXml, buildStyleRegistry, resolveDataStyleId } from './excel-styles';\nimport type { ExportParams } from './types';\n\n/**\n * Escape XML special characters.\n */\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n}\n\n/**\n * Build Excel XML content from rows and columns.\n * Uses XML Spreadsheet 2003 format for broad compatibility.\n */\nexport function buildExcelXml(rows: any[], columns: ColumnConfig[], params: ExportParams): string {\n const styles = params.excelStyles;\n const registry = styles ? buildStyleRegistry(styles) : undefined;\n\n let xml = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?mso-application progid=\"Excel.Sheet\"?>\n<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\n xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">`;\n\n // Emit <Styles> block (only when styles are configured)\n if (registry) {\n // Pre-register dynamic cellStyle entries so they appear in <Styles>\n if (styles!.cellStyle) {\n for (const row of rows) {\n for (const col of columns) {\n const value = resolveCellValue(row, col);\n const dynamic = styles!.cellStyle(value, col.field, row);\n if (dynamic) registry.register(dynamic);\n }\n }\n }\n xml += registry.toXml();\n }\n\n xml += '\\n<Worksheet ss:Name=\"Sheet1\">\\n<Table>';\n\n // Column widths\n if (styles) {\n xml += buildColumnWidthsXml(columns, rows as Record<string, unknown>[], styles);\n }\n\n // Header style ID\n const headerStyleId = styles?.headerStyle && registry ? registry.getStyleId(styles.headerStyle) : undefined;\n\n // Build header row\n if (params.includeHeaders !== false) {\n xml += '\\n<Row>';\n for (const col of columns) {\n const header = col.header || col.field;\n const processed = params.processHeader ? params.processHeader(header, col.field) : header;\n const styleAttr = headerStyleId ? ` ss:StyleID=\"${headerStyleId}\"` : '';\n xml += `<Cell${styleAttr}><Data ss:Type=\"String\">${escapeXml(processed)}</Data></Cell>`;\n }\n xml += '</Row>';\n }\n\n // Build data rows\n for (const row of rows) {\n xml += '\\n<Row>';\n for (const col of columns) {\n let value = resolveCellValue(row, col);\n if (params.processCell) {\n value = params.processCell(value, col.field, row);\n }\n\n // Determine cell type based on value\n let type: 'Number' | 'String' | 'DateTime' = 'String';\n let displayValue = '';\n\n if (value == null) {\n displayValue = '';\n } else if (typeof value === 'number' && !isNaN(value)) {\n type = 'Number';\n displayValue = String(value);\n } else if (value instanceof Date) {\n type = 'DateTime';\n displayValue = value.toISOString();\n } else {\n displayValue = escapeXml(String(value));\n }\n\n // Resolve data cell style\n const dataStyleId = registry && styles ? resolveDataStyleId(registry, styles, value, col.field, row) : undefined;\n const styleAttr = dataStyleId ? ` ss:StyleID=\"${dataStyleId}\"` : '';\n\n xml += `<Cell${styleAttr}><Data ss:Type=\"${type}\">${displayValue}</Data></Cell>`;\n }\n xml += '</Row>';\n }\n\n xml += '\\n</Table>\\n</Worksheet>\\n</Workbook>';\n return xml;\n}\n\n/**\n * Download Excel XML content as a file.\n */\nexport function downloadExcel(content: string, fileName: string): void {\n const blob = new Blob([content], {\n type: 'application/vnd.ms-excel;charset=utf-8;',\n });\n downloadBlob(blob, fileName);\n}\n","/**\n * Export Plugin (Class-based)\n *\n * Provides data export functionality for tbw-grid.\n * Supports CSV, Excel (XML), and JSON formats.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport { BaseGridPlugin, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { resolveColumns, resolveRows } from '../shared/data-collection';\nimport { buildCsv, downloadBlob, downloadCsv } from './csv';\nimport { buildExcelXml, downloadExcel } from './excel';\nimport type { ExportCompleteDetail, ExportConfig, ExportFormat, ExportParams } from './types';\n\n/** Selection plugin state interface for type safety */\ninterface SelectionPluginState {\n selected: Set<number>;\n}\n\n/**\n * Export Plugin for tbw-grid\n *\n * Lets users download grid data as CSV, Excel (XML), or JSON with a single click\n * or API call. Great for reporting, data backup, or letting users work with data\n * in Excel. Integrates with SelectionPlugin to export only selected rows.\n *\n * ## Installation\n *\n * ```ts\n * import { ExportPlugin } from '@toolbox-web/grid/plugins/export';\n * ```\n *\n * ## Supported Formats\n *\n * | Format | Method | Description |\n * |--------|--------|-------------|\n * | CSV | `exportToCSV()` | Comma-separated values |\n * | Excel | `exportToExcel()` | Excel XML format (.xlsx) |\n * | JSON | `exportToJSON()` | JSON array of objects |\n *\n * @example Basic Export with Button\n * ```ts\n * import { queryGrid } from '@toolbox-web/grid';\n * import { ExportPlugin } from '@toolbox-web/grid/plugins/export';\n *\n * const grid = queryGrid('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [new ExportPlugin({ fileName: 'employees', includeHeaders: true })],\n * };\n *\n * // Trigger export via button\n * document.getElementById('export-btn').addEventListener('click', () => {\n * grid.getPluginByName('export').exportToCSV();\n * });\n * ```\n *\n * @example Export Selected Rows Only\n * ```ts\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * plugins: [\n * new SelectionPlugin({ mode: 'row' }),\n * new ExportPlugin({ onlySelected: true }),\n * ],\n * };\n * ```\n *\n * @see {@link ExportConfig} for all configuration options\n * @see {@link ExportParams} for method parameters\n * @see SelectionPlugin for exporting selected rows\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ExportPlugin extends BaseGridPlugin<ExportConfig> {\n /**\n * Plugin manifest — declares queries for inter-plugin communication.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [{ type: 'export:csv', description: 'Triggers a CSV export' }],\n };\n\n /** @internal */\n readonly name = 'export';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ExportConfig> {\n return {\n fileName: 'export',\n includeHeaders: true,\n onlyVisible: true,\n onlySelected: false,\n };\n }\n\n // #region Internal State\n private isExportingFlag = false;\n private lastExportInfo: { format: ExportFormat; timestamp: Date } | null = null;\n // #endregion\n\n // #region Query System\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'export:csv') {\n this.exportCsv();\n return true;\n }\n return undefined;\n }\n // #endregion\n\n // #region Private Methods\n\n private performExport(format: ExportFormat, params?: Partial<ExportParams>): void {\n const config = this.config;\n\n // Build full params with defaults\n const fullParams: ExportParams = {\n format,\n fileName: params?.fileName ?? config.fileName ?? 'export',\n includeHeaders: params?.includeHeaders ?? config.includeHeaders,\n processCell: params?.processCell,\n processHeader: params?.processHeader,\n columns: params?.columns,\n rowIndices: params?.rowIndices,\n excelStyles: params?.excelStyles,\n fileExtension: params?.fileExtension,\n };\n\n // Get columns to export (shared utility handles hidden/utility filtering)\n const columns = resolveColumns(this.columns, params?.columns, config.onlyVisible) as ColumnConfig[];\n\n // Get rows to export\n let rows: Record<string, unknown>[];\n if (params?.rowIndices) {\n rows = resolveRows(this.rows as Record<string, unknown>[], params.rowIndices);\n } else if (config.onlySelected) {\n const selectionState = this.getSelectionState();\n if (selectionState?.selected?.size) {\n rows = resolveRows(this.rows as Record<string, unknown>[], [...selectionState.selected]);\n } else {\n rows = [...this.rows] as Record<string, unknown>[];\n }\n } else {\n rows = [...this.rows] as Record<string, unknown>[];\n }\n\n this.isExportingFlag = true;\n let fileName = fullParams.fileName!;\n\n try {\n switch (format) {\n case 'csv': {\n const content = buildCsv(rows, columns, fullParams, { bom: true });\n fileName = fileName.endsWith('.csv') ? fileName : `${fileName}.csv`;\n downloadCsv(content, fileName);\n break;\n }\n\n case 'excel': {\n const content = buildExcelXml(rows, columns, fullParams);\n const ext = fullParams.fileExtension ?? '.xls';\n const normalizedExt = ext.startsWith('.') ? ext : `.${ext}`;\n fileName = fileName.endsWith(normalizedExt) ? fileName : `${fileName}${normalizedExt}`;\n downloadExcel(content, fileName);\n break;\n }\n\n case 'json': {\n const jsonData = rows.map((row) => {\n const obj: Record<string, any> = {};\n for (const col of columns) {\n let value = resolveCellValue(row, col);\n if (fullParams.processCell) {\n value = fullParams.processCell(value, col.field, row);\n }\n obj[col.field] = value;\n }\n return obj;\n });\n const content = JSON.stringify(jsonData, null, 2);\n fileName = fileName.endsWith('.json') ? fileName : `${fileName}.json`;\n const blob = new Blob([content], { type: 'application/json' });\n downloadBlob(blob, fileName);\n break;\n }\n }\n\n this.lastExportInfo = { format, timestamp: new Date() };\n\n this.emit<ExportCompleteDetail>('export-complete', {\n format,\n fileName,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n } finally {\n this.isExportingFlag = false;\n }\n }\n\n private getSelectionState(): SelectionPluginState | null {\n try {\n return (this.grid?.getPluginState?.('selection') as SelectionPluginState | null) ?? null;\n } catch {\n return null;\n }\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Export data to CSV format.\n * @param params - Optional export parameters\n */\n exportCsv(params?: Partial<ExportParams>): void {\n this.performExport('csv', params);\n }\n\n /**\n * Export data to Excel format (XML Spreadsheet).\n * @param params - Optional export parameters\n */\n exportExcel(params?: Partial<ExportParams>): void {\n this.performExport('excel', params);\n }\n\n /**\n * Export data to JSON format.\n * @param params - Optional export parameters\n */\n exportJson(params?: Partial<ExportParams>): void {\n this.performExport('json', params);\n }\n\n /**\n * Check if an export is currently in progress.\n * @returns Whether export is in progress\n */\n isExporting(): boolean {\n return this.isExportingFlag;\n }\n\n /**\n * Get information about the last export.\n * @returns Export info or null if no export has occurred\n */\n getLastExport(): { format: ExportFormat; timestamp: Date } | null {\n return this.lastExportInfo;\n }\n // #endregion\n}\n"],"names":["resolveRows","rows","indices","length","sort","a","b","map","i","filter","r","formatCsvValue","value","quote","Date","toISOString","JSON","stringify","str","String","includes","replace","downloadBlob","blob","fileName","url","URL","createObjectURL","link","document","createElement","href","download","style","display","body","appendChild","click","removeChild","revokeObjectURL","hashStyle","sortKeys","obj","Array","isArray","sorted","key","Object","keys","StyleRegistry","entries","Map","counter","register","hash","existing","this","get","id","set","getStyleId","size","toXml","xml","values","buildStyleElement","font","name","bold","italic","color","fill","pattern","numberFormat","alignment","horizontal","vertical","wrapText","borders","top","buildBorderElement","bottom","left","right","position","border","borderWeight","resolveDataStyleId","registry","config","field","row","cellStyle","dynamic","colStyle","columnStyles","defaultStyle","autoFitWidth","col","sampleSize","Math","min","maxLen","header","val","len","escapeXml","buildExcelXml","columns","params","styles","excelStyles","headerStyle","buildStyleRegistry","resolveCellValue","widths","columnWidths","autoFit","autoFitColumns","width","buildColumnWidthsXml","headerStyleId","includeHeaders","processHeader","processCell","type","displayValue","isNaN","dataStyleId","ExportPlugin","BaseGridPlugin","static","queries","description","defaultConfig","onlyVisible","onlySelected","isExportingFlag","lastExportInfo","handleQuery","query","exportCsv","performExport","format","fullParams","rowIndices","fileExtension","fields","result","c","hidden","startsWith","meta","utility","fieldSet","Set","has","resolveColumns","selectionState","getSelectionState","selected","content","options","delimiter","newline","lines","bom","headerRow","push","join","cells","buildCsv","endsWith","Blob","downloadCsv","ext","normalizedExt","downloadExcel","jsonData","timestamp","emit","rowCount","columnCount","grid","getPluginState","exportExcel","exportJson","isExporting","getLastExport"],"mappings":"+aAkDO,SAASA,EAAeC,EAAoBC,GACjD,OAAKA,GAASC,OAEP,IAAID,GACRE,KAAK,CAACC,EAAGC,IAAMD,EA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EAAKO,GAC9B8C,EAAWpB,cACbhH,EAAQoI,EAAWpB,YAAYhH,EAAOsF,EAAIR,MAAOC,IAEnDjD,EAAIwD,EAAIR,OAAS9E,CACnB,CACA,OAAO8B,IAEHuH,EAAUjJ,KAAKC,UAAUiK,EAAU,KAAM,GAC/C1J,EAAWA,EAASoJ,SAAS,SAAWpJ,EAAW,GAAGA,SAEtDF,EADa,IAAIuJ,KAAK,CAACZ,GAAU,CAAEpC,KAAM,qBACtBrG,GACnB,KACF,EAGFgC,KAAKkF,eAAiB,CAAEK,SAAQoC,UAAW,IAAIrK,MAE/C0C,KAAK4H,KAA2B,kBAAmB,CACjDrC,SACAvH,WACA6J,SAAUpL,EAAKE,OACfmL,YAAa1E,EAAQzG,QAEzB,CAAA,QACEqD,KAAKiF,iBAAkB,CACzB,CACF,CAEQ,iBAAAsB,GACN,IACE,OAAQvG,KAAK+H,MAAMC,iBAAiB,cAAgD,IACtF,CAAA,MACE,OAAO,IACT,CACF,CASA,SAAA3C,CAAUhC,GACRrD,KAAKsF,cAAc,MAAOjC,EAC5B,CAMA,WAAA4E,CAAY5E,GACVrD,KAAKsF,cAAc,QAASjC,EAC9B,CAMA,UAAA6E,CAAW7E,GACTrD,KAAKsF,cAAc,OAAQjC,EAC7B,CAMA,WAAA8E,GACE,OAAOnI,KAAKiF,eACd,CAMA,aAAAmD,GACE,OAAOpI,KAAKkF,cACd"}
1
+ {"version":3,"file":"export.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../libs/grid/src/lib/plugins/export/csv.ts","../../../../../libs/grid/src/lib/plugins/export/excel-styles.ts","../../../../../libs/grid/src/lib/plugins/export/excel.ts","../../../../../libs/grid/src/lib/plugins/export/ExportPlugin.ts"],"sourcesContent":["/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n","/**\n * CSV Export Utilities\n *\n * Functions for building and downloading CSV content.\n */\n\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport type { ColumnConfig } from '../../core/types';\nimport type { ExportParams } from './types';\n\n/** CSV export options */\nexport interface CsvOptions {\n /** Field delimiter (default: ',') */\n delimiter?: string;\n /** Line separator (default: '\\n') */\n newline?: string;\n /** Whether to quote strings containing special characters (default: true) */\n quoteStrings?: boolean;\n /** Add UTF-8 BOM for Excel compatibility (default: false) */\n bom?: boolean;\n}\n\n/**\n * Format a value for CSV output.\n * Handles null, Date, objects, and strings with special characters.\n */\nexport function formatCsvValue(value: any, quote = true): string {\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\n // Quote if contains special characters (comma, quote, newline)\n if (quote && (str.includes(',') || str.includes('\"') || str.includes('\\n') || str.includes('\\r'))) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build CSV content from rows and columns.\n */\nexport function buildCsv(rows: any[], columns: ColumnConfig[], params: ExportParams, options: CsvOptions = {}): string {\n const delimiter = options.delimiter ?? ',';\n const newline = options.newline ?? '\\n';\n const lines: string[] = [];\n\n // UTF-8 BOM for Excel compatibility\n const bom = options.bom ? '\\uFEFF' : '';\n\n // Build header row\n if (params.includeHeaders !== false) {\n const headerRow = columns.map((col) => {\n const header = col.header || col.field;\n const processed = params.processHeader ? params.processHeader(header, col.field) : header;\n return formatCsvValue(processed);\n });\n lines.push(headerRow.join(delimiter));\n }\n\n // Build data rows\n for (const row of rows) {\n const cells = columns.map((col) => {\n let value = resolveCellValue(row, col);\n if (params.processCell) {\n value = params.processCell(value, col.field, row);\n }\n return formatCsvValue(value);\n });\n lines.push(cells.join(delimiter));\n }\n\n return bom + lines.join(newline);\n}\n\n/**\n * Download a Blob as a file.\n */\nexport function downloadBlob(blob: Blob, fileName: string): void {\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = fileName;\n link.style.display = 'none';\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n\n/**\n * Download CSV content as a file.\n */\nexport function downloadCsv(content: string, fileName: string): void {\n const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });\n downloadBlob(blob, fileName);\n}\n","/**\n * Excel Style Engine\n *\n * Builds a deduplicated `<Styles>` block for XML Spreadsheet 2003.\n * Collects unique ExcelCellStyle objects, assigns ss:StyleID values,\n * and generates the corresponding XML.\n */\n\nimport type { ExcelBorder, ExcelCellStyle, ExcelStyleConfig } from './types';\n\n// #region Style Hashing\n\n/**\n * Produce a deterministic string key for a style object.\n * Two structurally identical styles produce the same hash.\n * Recursively sorts object keys for order-independent comparison.\n */\nfunction hashStyle(style: ExcelCellStyle): string {\n return JSON.stringify(sortKeys(style));\n}\n\n/** Recursively sort object keys for deterministic serialization. */\nfunction sortKeys(obj: unknown): unknown {\n if (obj == null || typeof obj !== 'object') return obj;\n if (Array.isArray(obj)) return obj.map(sortKeys);\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = sortKeys((obj as Record<string, unknown>)[key]);\n }\n return sorted;\n}\n\n// #endregion\n\n// #region Style Registry\n\n/** Maps a hash → style ID and the original style. */\nexport interface StyleEntry {\n id: string;\n style: ExcelCellStyle;\n}\n\n/**\n * Collects unique styles and assigns each an `ss:StyleID`.\n * Register styles via `register()`, then call `getStyleId()` to look up\n * the ID for a given style, and `toXml()` to emit the `<Styles>` block.\n */\nexport class StyleRegistry {\n /** hash → StyleEntry */\n #entries = new Map<string, StyleEntry>();\n #counter = 0;\n\n /**\n * Register a style and return its assigned ID.\n * If an identical style was already registered, returns the existing ID.\n */\n register(style: ExcelCellStyle): string {\n const hash = hashStyle(style);\n const existing = this.#entries.get(hash);\n if (existing) return existing.id;\n\n this.#counter++;\n const id = `s${this.#counter}`;\n this.#entries.set(hash, { id, style });\n return id;\n }\n\n /** Look up the ID previously assigned to a style (or undefined). */\n getStyleId(style: ExcelCellStyle): string | undefined {\n return this.#entries.get(hashStyle(style))?.id;\n }\n\n /** Number of unique styles registered so far. */\n get size(): number {\n return this.#entries.size;\n }\n\n /** Emit the full `<Styles>…</Styles>` XML fragment, or empty string if no styles. */\n toXml(): string {\n if (this.#entries.size === 0) return '';\n\n let xml = '\\n<Styles>';\n for (const { id, style } of this.#entries.values()) {\n xml += buildStyleElement(id, style);\n }\n xml += '\\n</Styles>';\n return xml;\n }\n}\n\n// #endregion\n\n// #region XML Builders\n\nfunction buildStyleElement(id: string, style: ExcelCellStyle): string {\n let xml = `\\n<Style ss:ID=\"${id}\">`;\n\n if (style.font) {\n xml += '<Font';\n if (style.font.name) xml += ` ss:FontName=\"${style.font.name}\"`;\n if (style.font.size) xml += ` ss:Size=\"${style.font.size}\"`;\n if (style.font.bold) xml += ' ss:Bold=\"1\"';\n if (style.font.italic) xml += ' ss:Italic=\"1\"';\n if (style.font.color) xml += ` ss:Color=\"${style.font.color}\"`;\n xml += '/>';\n }\n\n if (style.fill) {\n const pattern = style.fill.pattern ?? 'Solid';\n xml += `<Interior ss:Color=\"${style.fill.color}\" ss:Pattern=\"${pattern}\"/>`;\n }\n\n if (style.numberFormat) {\n xml += `<NumberFormat ss:Format=\"${style.numberFormat}\"/>`;\n }\n\n if (style.alignment) {\n xml += '<Alignment';\n if (style.alignment.horizontal) xml += ` ss:Horizontal=\"${style.alignment.horizontal}\"`;\n if (style.alignment.vertical) xml += ` ss:Vertical=\"${style.alignment.vertical}\"`;\n if (style.alignment.wrapText) xml += ' ss:WrapText=\"1\"';\n xml += '/>';\n }\n\n if (style.borders) {\n xml += '<Borders>';\n if (style.borders.top) xml += buildBorderElement('Top', style.borders.top);\n if (style.borders.bottom) xml += buildBorderElement('Bottom', style.borders.bottom);\n if (style.borders.left) xml += buildBorderElement('Left', style.borders.left);\n if (style.borders.right) xml += buildBorderElement('Right', style.borders.right);\n xml += '</Borders>';\n }\n\n xml += '</Style>';\n return xml;\n}\n\nfunction buildBorderElement(position: string, border: ExcelBorder): string {\n let xml = `<Border ss:Position=\"${position}\" ss:LineStyle=\"Continuous\" ss:Weight=\"${borderWeight(border.style)}\"`;\n if (border.color) xml += ` ss:Color=\"${border.color}\"`;\n xml += '/>';\n return xml;\n}\n\nfunction borderWeight(style: ExcelBorder['style']): number {\n switch (style) {\n case 'Thin':\n return 1;\n case 'Medium':\n return 2;\n case 'Thick':\n return 3;\n }\n}\n\n// #endregion\n\n// #region Style Resolution\n\n/**\n * Build a StyleRegistry pre-populated with all styles declared in the config.\n * This covers headerStyle, defaultStyle, and columnStyles.\n * (cellStyle callbacks are resolved per-cell at render time.)\n */\nexport function buildStyleRegistry(config: ExcelStyleConfig): StyleRegistry {\n const registry = new StyleRegistry();\n\n if (config.headerStyle) registry.register(config.headerStyle);\n\n if (config.defaultStyle) registry.register(config.defaultStyle);\n\n if (config.columnStyles) {\n for (const style of Object.values(config.columnStyles)) {\n registry.register(style);\n }\n }\n\n return registry;\n}\n\n/**\n * Resolve the style ID for a data cell. Precedence (highest → lowest):\n * 1. cellStyle callback return value\n * 2. columnStyles[field]\n * 3. defaultStyle\n */\nexport function resolveDataStyleId(\n registry: StyleRegistry,\n config: ExcelStyleConfig,\n value: unknown,\n field: string,\n row: unknown,\n): string | undefined {\n // 1. Dynamic cell callback\n if (config.cellStyle) {\n const dynamic = config.cellStyle(value, field, row);\n if (dynamic) {\n // Register on-the-fly (dedup handles repeats)\n return registry.register(dynamic);\n }\n }\n\n // 2. Per-column override\n const colStyle = config.columnStyles?.[field];\n if (colStyle) return registry.getStyleId(colStyle);\n\n // 3. Default\n if (config.defaultStyle) return registry.getStyleId(config.defaultStyle);\n\n return undefined;\n}\n\n// #endregion\n\n// #region Column Widths\n\n/** Character width → Excel column width approximation (px ≈ chars × 7) */\nconst CHAR_WIDTH = 7;\n\n/**\n * Build `<Column>` elements for explicit or auto-fit widths.\n */\nexport function buildColumnWidthsXml(\n columns: { field: string; header?: string }[],\n rows: Record<string, unknown>[],\n config: ExcelStyleConfig,\n): string {\n const widths = config.columnWidths;\n const autoFit = config.autoFitColumns;\n\n if (!widths && !autoFit) return '';\n\n let xml = '';\n for (const col of columns) {\n let width: number | undefined = widths?.[col.field];\n\n if (width == null && autoFit) {\n width = autoFitWidth(col, rows);\n }\n\n if (width != null) {\n xml += `\\n<Column ss:Width=\"${width * CHAR_WIDTH}\"/>`;\n } else {\n // Emit an empty column entry to keep ordinal alignment\n xml += '\\n<Column/>';\n }\n }\n\n return xml;\n}\n\n/** Estimate width from header + first N data rows (capped at 50). */\nfunction autoFitWidth(col: { field: string; header?: string }, rows: Record<string, unknown>[]): number {\n const sampleSize = Math.min(rows.length, 50);\n let maxLen = (col.header ?? col.field).length;\n\n for (let i = 0; i < sampleSize; i++) {\n const val = rows[i][col.field];\n const len = val == null ? 0 : String(val).length;\n if (len > maxLen) maxLen = len;\n }\n\n // Add a small padding\n return maxLen + 2;\n}\n\n// #endregion\n","/**\n * Excel Export Utilities\n *\n * Simple Excel XML format export (no external dependencies).\n * Produces XML Spreadsheet 2003 format which opens in Excel.\n */\n\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport type { ColumnConfig } from '../../core/types';\nimport { downloadBlob } from './csv';\nimport { buildColumnWidthsXml, buildStyleRegistry, resolveDataStyleId } from './excel-styles';\nimport type { ExportParams } from './types';\n\n/**\n * Escape XML special characters.\n */\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n}\n\n/**\n * Build Excel XML content from rows and columns.\n * Uses XML Spreadsheet 2003 format for broad compatibility.\n */\nexport function buildExcelXml(rows: any[], columns: ColumnConfig[], params: ExportParams): string {\n const styles = params.excelStyles;\n const registry = styles ? buildStyleRegistry(styles) : undefined;\n\n let xml = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?mso-application progid=\"Excel.Sheet\"?>\n<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\n xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">`;\n\n // Emit <Styles> block (only when styles are configured)\n if (registry) {\n // Pre-register dynamic cellStyle entries so they appear in <Styles>\n if (styles!.cellStyle) {\n for (const row of rows) {\n for (const col of columns) {\n const value = resolveCellValue(row, col);\n const dynamic = styles!.cellStyle(value, col.field, row);\n if (dynamic) registry.register(dynamic);\n }\n }\n }\n xml += registry.toXml();\n }\n\n xml += '\\n<Worksheet ss:Name=\"Sheet1\">\\n<Table>';\n\n // Column widths\n if (styles) {\n xml += buildColumnWidthsXml(columns, rows as Record<string, unknown>[], styles);\n }\n\n // Header style ID\n const headerStyleId = styles?.headerStyle && registry ? registry.getStyleId(styles.headerStyle) : undefined;\n\n // Build header row\n if (params.includeHeaders !== false) {\n xml += '\\n<Row>';\n for (const col of columns) {\n const header = col.header || col.field;\n const processed = params.processHeader ? params.processHeader(header, col.field) : header;\n const styleAttr = headerStyleId ? ` ss:StyleID=\"${headerStyleId}\"` : '';\n xml += `<Cell${styleAttr}><Data ss:Type=\"String\">${escapeXml(processed)}</Data></Cell>`;\n }\n xml += '</Row>';\n }\n\n // Build data rows\n for (const row of rows) {\n xml += '\\n<Row>';\n for (const col of columns) {\n let value = resolveCellValue(row, col);\n if (params.processCell) {\n value = params.processCell(value, col.field, row);\n }\n\n // Determine cell type based on value\n let type: 'Number' | 'String' | 'DateTime' = 'String';\n let displayValue = '';\n\n if (value == null) {\n displayValue = '';\n } else if (typeof value === 'number' && !isNaN(value)) {\n type = 'Number';\n displayValue = String(value);\n } else if (value instanceof Date) {\n type = 'DateTime';\n displayValue = value.toISOString();\n } else {\n displayValue = escapeXml(String(value));\n }\n\n // Resolve data cell style\n const dataStyleId = registry && styles ? resolveDataStyleId(registry, styles, value, col.field, row) : undefined;\n const styleAttr = dataStyleId ? ` ss:StyleID=\"${dataStyleId}\"` : '';\n\n xml += `<Cell${styleAttr}><Data ss:Type=\"${type}\">${displayValue}</Data></Cell>`;\n }\n xml += '</Row>';\n }\n\n xml += '\\n</Table>\\n</Worksheet>\\n</Workbook>';\n return xml;\n}\n\n/**\n * Download Excel XML content as a file.\n */\nexport function downloadExcel(content: string, fileName: string): void {\n const blob = new Blob([content], {\n type: 'application/vnd.ms-excel;charset=utf-8;',\n });\n downloadBlob(blob, fileName);\n}\n","/**\n * Export Plugin (Class-based)\n *\n * Provides data export functionality for tbw-grid.\n * Supports CSV, Excel (XML), and JSON formats.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport { BaseGridPlugin, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { resolveColumns, resolveRows } from '../shared/data-collection';\nimport { buildCsv, downloadBlob, downloadCsv } from './csv';\nimport { buildExcelXml, downloadExcel } from './excel';\nimport type { ExportCompleteDetail, ExportConfig, ExportFormat, ExportParams } from './types';\n\n/** Selection plugin state interface for type safety */\ninterface SelectionPluginState {\n selected: Set<number>;\n}\n\n/**\n * Export Plugin for tbw-grid\n *\n * Lets users download grid data as CSV, Excel (XML), or JSON with a single click\n * or API call. Great for reporting, data backup, or letting users work with data\n * in Excel. Integrates with SelectionPlugin to export only selected rows.\n *\n * ## Installation\n *\n * ```ts\n * import { ExportPlugin } from '@toolbox-web/grid/plugins/export';\n * ```\n *\n * ## Supported Formats\n *\n * | Format | Method | Description |\n * |--------|--------|-------------|\n * | CSV | `exportToCSV()` | Comma-separated values |\n * | Excel | `exportToExcel()` | Excel XML format (.xlsx) |\n * | JSON | `exportToJSON()` | JSON array of objects |\n *\n * @example Basic Export with Button\n * ```ts\n * import { queryGrid } from '@toolbox-web/grid';\n * import { ExportPlugin } from '@toolbox-web/grid/plugins/export';\n *\n * const grid = queryGrid('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [new ExportPlugin({ fileName: 'employees', includeHeaders: true })],\n * };\n *\n * // Trigger export via button\n * document.getElementById('export-btn').addEventListener('click', () => {\n * grid.getPluginByName('export').exportToCSV();\n * });\n * ```\n *\n * @example Export Selected Rows Only\n * ```ts\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * plugins: [\n * new SelectionPlugin({ mode: 'row' }),\n * new ExportPlugin({ onlySelected: true }),\n * ],\n * };\n * ```\n *\n * @see {@link ExportConfig} for all configuration options\n * @see {@link ExportParams} for method parameters\n * @see SelectionPlugin for exporting selected rows\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ExportPlugin extends BaseGridPlugin<ExportConfig> {\n /**\n * Plugin manifest — declares queries for inter-plugin communication.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [{ type: 'export:csv', description: 'Triggers a CSV export' }],\n };\n\n /** @internal */\n readonly name = 'export';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ExportConfig> {\n return {\n fileName: 'export',\n includeHeaders: true,\n onlyVisible: true,\n onlySelected: false,\n };\n }\n\n // #region Internal State\n private isExportingFlag = false;\n private lastExportInfo: { format: ExportFormat; timestamp: Date } | null = null;\n // #endregion\n\n // #region Query System\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'export:csv') {\n this.exportCsv();\n return true;\n }\n return undefined;\n }\n // #endregion\n\n // #region Private Methods\n\n private performExport(format: ExportFormat, params?: Partial<ExportParams>): void {\n const config = this.config;\n\n // Build full params with defaults\n const fullParams: ExportParams = {\n format,\n fileName: params?.fileName ?? config.fileName ?? 'export',\n includeHeaders: params?.includeHeaders ?? config.includeHeaders,\n processCell: params?.processCell,\n processHeader: params?.processHeader,\n columns: params?.columns,\n rowIndices: params?.rowIndices,\n excelStyles: params?.excelStyles,\n fileExtension: params?.fileExtension,\n };\n\n // Get columns to export (shared utility handles hidden/utility filtering)\n const columns = resolveColumns(this.columns, params?.columns, config.onlyVisible) as ColumnConfig[];\n\n // Get rows to export\n let rows: Record<string, unknown>[];\n if (params?.rowIndices) {\n rows = resolveRows(this.rows as Record<string, unknown>[], params.rowIndices);\n } else if (config.onlySelected) {\n const selectionState = this.getSelectionState();\n if (selectionState?.selected?.size) {\n rows = resolveRows(this.rows as Record<string, unknown>[], [...selectionState.selected]);\n } else {\n rows = [...this.rows] as Record<string, unknown>[];\n }\n } else {\n rows = [...this.rows] as Record<string, unknown>[];\n }\n\n this.isExportingFlag = true;\n let fileName = fullParams.fileName!;\n\n try {\n switch (format) {\n case 'csv': {\n const content = buildCsv(rows, columns, fullParams, { bom: true });\n fileName = fileName.endsWith('.csv') ? fileName : `${fileName}.csv`;\n downloadCsv(content, fileName);\n break;\n }\n\n case 'excel': {\n const content = buildExcelXml(rows, columns, fullParams);\n const ext = fullParams.fileExtension ?? '.xls';\n const normalizedExt = ext.startsWith('.') ? ext : `.${ext}`;\n fileName = fileName.endsWith(normalizedExt) ? fileName : `${fileName}${normalizedExt}`;\n downloadExcel(content, fileName);\n break;\n }\n\n case 'json': {\n const jsonData = rows.map((row) => {\n const obj: Record<string, any> = {};\n for (const col of columns) {\n let value = resolveCellValue(row, col);\n if (fullParams.processCell) {\n value = fullParams.processCell(value, col.field, row);\n }\n obj[col.field] = value;\n }\n return obj;\n });\n const content = JSON.stringify(jsonData, null, 2);\n fileName = fileName.endsWith('.json') ? fileName : `${fileName}.json`;\n const blob = new Blob([content], { type: 'application/json' });\n downloadBlob(blob, fileName);\n break;\n }\n }\n\n this.lastExportInfo = { format, timestamp: new Date() };\n\n this.emit<ExportCompleteDetail>('export-complete', {\n format,\n fileName,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n } finally {\n this.isExportingFlag = false;\n }\n }\n\n private getSelectionState(): SelectionPluginState | null {\n try {\n return (this.grid?.getPluginState?.('selection') as SelectionPluginState | null) ?? null;\n } catch {\n return null;\n }\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Export data to CSV format.\n * @param params - Optional export parameters\n */\n exportCsv(params?: Partial<ExportParams>): void {\n this.performExport('csv', params);\n }\n\n /**\n * Export data to Excel format (XML Spreadsheet).\n * @param params - Optional export parameters\n */\n exportExcel(params?: Partial<ExportParams>): void {\n this.performExport('excel', params);\n }\n\n /**\n * Export data to JSON format.\n * @param params - Optional export parameters\n */\n exportJson(params?: Partial<ExportParams>): void {\n this.performExport('json', params);\n }\n\n /**\n * Check if an export is currently in progress.\n * @returns Whether export is in progress\n */\n isExporting(): boolean {\n return this.isExportingFlag;\n }\n\n /**\n * Get information about the last export.\n * @returns Export info or null if no export has occurred\n */\n getLastExport(): { format: ExportFormat; timestamp: Date } | null {\n return this.lastExportInfo;\n }\n // #endregion\n}\n"],"names":["resolveRows","rows","indices","length","sort","a","b","map","i","filter","r","formatCsvValue","value","quote","Date","toISOString","JSON","stringify","str","String","includes","replace","downloadBlob","blob","fileName","url","URL","createObjectURL","link","document","createElement","href","download","style","display","body","appendChild","click","removeChild","revokeObjectURL","hashStyle","sortKeys","obj","Array","isArray","sorted","key","Object","keys","StyleRegistry","entries","Map","counter","register","hash","existing","this","get","id","set","getStyleId","size","toXml","xml","values","buildStyleElement","font","name","bold","italic","color","fill","pattern","numberFormat","alignment","horizontal","vertical","wrapText","borders","top","buildBorderElement","bottom","left","right","position","border","borderWeight","resolveDataStyleId","registry","config","field","row","cellStyle","dynamic","colStyle","columnStyles","defaultStyle","autoFitWidth","col","sampleSize","Math","min","maxLen","header","val","len","escapeXml","buildExcelXml","columns","params","styles","excelStyles","headerStyle","buildStyleRegistry","resolveCellValue","widths","columnWidths","autoFit","autoFitColumns","width","buildColumnWidthsXml","headerStyleId","includeHeaders","processHeader","processCell","type","displayValue","isNaN","dataStyleId","ExportPlugin","BaseGridPlugin","static","queries","description","defaultConfig","onlyVisible","onlySelected","isExportingFlag","lastExportInfo","handleQuery","query","exportCsv","performExport","format","fullParams","rowIndices","fileExtension","fields","result","c","hidden","startsWith","utility","fieldSet","Set","has","resolveColumns","selectionState","getSelectionState","selected","content","options","delimiter","newline","lines","bom","headerRow","push","join","cells","buildCsv","endsWith","Blob","downloadCsv","ext","normalizedExt","downloadExcel","jsonData","timestamp","emit","rowCount","columnCount","grid","getPluginState","exportExcel","exportJson","isExporting","getLastExport"],"mappings":"+aAkDO,SAASA,EAAeC,EAAoBC,GACjD,OAAKA,GAASC,OAEP,IAAID,GACRE,KAAK,CA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AAAA,iBAAiBvB,EAAKO,GAC9B8C,EAAWpB,cACbhH,EAAQoI,EAAWpB,YAAYhH,EAAOsF,EAAIR,MAAOC,IAEnDjD,EAAIwD,EAAIR,OAAS9E,CACnB,CACA,OAAO8B,IAEHsH,EAAUhJ,KAAKC,UAAUgK,EAAU,KAAM,GAC/CzJ,EAAWA,EAASmJ,SAAS,SAAWnJ,EAAW,GAAGA,SAEtDF,EADa,IAAIsJ,KAAK,CAACZ,GAAU,CAAEnC,KAAM,qBACtBrG,GACnB,KACF,EAGFgC,KAAKkF,eAAiB,CAAEK,SAAQmC,UAAW,IAAIpK,MAE/C0C,KAAK2H,KAA2B,kBAAmB,CACjDpC,SACAvH,WACA4J,SAAUnL,EAAKE,OACfkL,YAAazE,EAAQzG,QAEzB,CAAA,QACEqD,KAAKiF,iBAAkB,CACzB,CACF,CAEQ,iBAAAqB,GACN,IACE,OAAQtG,KAAK8H,MAAMC,iBAAiB,cAAgD,IACtF,CAAA,MACE,OAAO,IACT,CACF,CASA,SAAA1C,CAAUhC,GACRrD,KAAKsF,cAAc,MAAOjC,EAC5B,CAMA,WAAA2E,CAAY3E,GACVrD,KAAKsF,cAAc,QAASjC,EAC9B,CAMA,UAAA4E,CAAW5E,GACTrD,KAAKsF,cAAc,OAAQjC,EAC7B,CAMA,WAAA6E,GACE,OAAOlI,KAAKiF,eACd,CAMA,aAAAkD,GACE,OAAOnI,KAAKkF,cACd"}
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/aria"),require("../../core/plugin/base-plugin"),require("../../core/internal/value-accessor")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/aria","../../core/plugin/base-plugin","../../core/internal/value-accessor"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_multiSort={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,r,i){"use strict";function o(e,t){const r=!0===e?.__loading;return r===(!0===t?.__loading)?0:r?1:-1}function s(e,t){return null==e&&null==t?0:null==e?1:null==t?-1:"number"==typeof e&&"number"==typeof t?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():"boolean"==typeof e&&"boolean"==typeof t?e===t?0:e?-1:1:String(e).localeCompare(String(t))}function n(e,t){const r=e.findIndex(e=>e.field===t);return r>=0?r+1:void 0}function l(e,t){return e.find(e=>e.field===t)?.direction}class d extends r.BaseGridPlugin{static manifest={queries:[{type:"sort:get-model",description:"Returns the current multi-sort model as SortModel[]"},{type:"sort:set-model",description:"Sets the multi-sort model from context (SortModel[])"}]};name="multiSort";styles='@layer tbw-plugins{.header-cell[data-sort=asc]:after{content:"↑";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.header-cell[data-sort=desc]:after{content:"↓";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-indicator{margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-index{font-size:var(--tbw-font-size-2xs, .7em);background:var(--tbw-multi-sort-badge-bg, var(--tbw-color-panel-bg));color:var(--tbw-multi-sort-badge-color, var(--tbw-color-fg));border-radius:50%;width:var(--tbw-multi-sort-badge-size, 1em);height:var(--tbw-multi-sort-badge-size, 1em);display:inline-flex;align-items:center;justify-content:center;margin-left:var(--tbw-spacing-xs, .125em);font-weight:600}}';get defaultConfig(){return{maxSortColumns:3,showSortIndex:!0}}sortModel=[];cachedSortResult=null;get#e(){return this.grid}clearCoreSortState(){this.#e._sortState=null}#t(e){const t=this.grid?.query?.("grouping:get-grouped-fields",null);if(!Array.isArray(t)||0===t.length)return e;const r=t[0];if(!Array.isArray(r)||0===r.length)return e;const i=new Set(r),o=e.filter(e=>!i.has(e.field));return o.length===e.length?e:o}detach(){this.sortModel=[],this.cachedSortResult=null}handleQuery(e){switch(e.type){case"sort:get-model":return[...this.sortModel];case"sort:set-model":{const t=e.context;return!!Array.isArray(t)&&(this.sortModel=[...t],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),!0)}default:return}}processRows(e){if(0===this.sortModel.length)return this.cachedSortResult=null,[...e];const t=this.#e;if(!t._isGridEditMode&&"number"==typeof t._activeEditRows&&-1!==t._activeEditRows&&this.cachedSortResult&&this.cachedSortResult.length===e.length)return[...this.cachedSortResult];const r=this.#t(this.sortModel),n=e;return r.length>0&&function(e,t,r){if(!t.length)return;const n=t.map(e=>{const t=r.find(t=>t.field===e.field),i=t?.sortComparator??s;return{field:e.field,asc:"asc"===e.direction,comparator:i,pinPlaceholders:!t?.sortComparator,column:t}}),l=(e,t)=>t.column?.valueAccessor?i.resolveCellValue(e,t.column):e[t.field];if(1===n.length){const t=n[0];e.sort((e,r)=>{if(t.pinPlaceholders){const t=o(e,r);if(0!==t)return t}const i=t.comparator(l(e,t),l(r,t),e,r);return t.asc?i:-i})}else e.sort((e,t)=>{if(n.some(e=>e.pinPlaceholders)){const r=o(e,t);if(0!==r)return r}for(let r=0;r<n.length;r++){const i=n[r],o=i.comparator(l(e,i),l(t,i),e,t);if(0!==o)return i.asc?o:-o}return 0})}(n,r,this.columns),this.cachedSortResult=n,n}onHeaderClick(e){const r=this.columns.find(t=>t.field===e.field);if(!r?.sortable)return!1;const i=e.originalEvent.shiftKey,o=this.config.maxSortColumns??3;if(this.sortModel=function(e,t,r,i){const o=e.find(e=>e.field===t);return r?o?"asc"===o.direction?e.map(e=>e.field===t?{...e,direction:"desc"}:e):e.filter(e=>e.field!==t):e.length<i?[...e,{field:t,direction:"asc"}]:e:"asc"===o?.direction?[{field:t,direction:"desc"}]:"desc"===o?.direction?[]:[{field:t,direction:"asc"}]}(this.sortModel,e.field,i,o),this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),this.grid?.requestStateChange?.(),this.sortModel.length>0){const e=this.sortModel.map(e=>{const t=this.columns.find(t=>t.field===e.field);return`${t?.header??e.field} ${"asc"===e.direction?"ascending":"descending"}`});t.announce(this.gridElement,t.getA11yMessage(this.gridElement,"sortApplied",e.join(", then "),""))}else t.announce(this.gridElement,t.getA11yMessage(this.gridElement,"sortCleared"));return!0}afterRender(){const e=this.gridElement;if(!e)return;const t=!1!==this.config.showSortIndex;e.querySelectorAll(".header-row .cell[data-field]").forEach(e=>{const r=e.getAttribute("data-field");if(!r)return;const i=n(this.sortModel,r),o=l(this.sortModel,r);if(e.querySelector(".sort-index")?.remove(),o){const r=this.updateSortIndicator(e,o);if(t&&this.sortModel.length>1&&void 0!==i){const t=document.createElement("span");t.className="sort-index",t.textContent=String(i),r.nextSibling?e.insertBefore(t,r.nextSibling):e.appendChild(t)}}else e.classList.contains("sortable")&&this.updateSortIndicator(e,null)})}getSortModel(){return[...this.sortModel]}setSortModel(e){if(this.sortModel=[...e],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...e]}),this.requestRender(),this.grid?.requestStateChange?.(),e.length>0){const r=e.map(e=>{const t=this.columns.find(t=>t.field===e.field);return`${t?.header??e.field} ${"asc"===e.direction?"ascending":"descending"}`});t.announce(this.gridElement,t.getA11yMessage(this.gridElement,"sortApplied",r.join(", then "),""))}}clearSort(){this.sortModel=[],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[]}),this.requestRender(),this.grid?.requestStateChange?.(),t.announce(this.gridElement,t.getA11yMessage(this.gridElement,"sortCleared"))}getSortIndex(e){return n(this.sortModel,e)}getSortDirection(e){return l(this.sortModel,e)}getColumnState(e){const t=this.sortModel.findIndex(t=>t.field===e);if(-1===t)return;return{sort:{direction:this.sortModel[t].direction,priority:t}}}applyColumnState(e,t){if(!t.sort)return void(this.sortModel=this.sortModel.filter(t=>t.field!==e));const r=this.sortModel.findIndex(t=>t.field===e),i={field:e,direction:t.sort.direction};-1!==r?this.sortModel[r]=i:this.sortModel.splice(t.sort.priority,0,i),this.clearCoreSortState()}}e.MultiSortPlugin=d,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("../../core/internal/aria"),require("../../core/plugin/base-plugin"),require("../../core/internal/value-accessor")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/aria","../../core/plugin/base-plugin","../../core/internal/value-accessor"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_multiSort={},t.TbwGrid,t.TbwGrid,t.TbwGrid)}(this,function(t,e,r,i){"use strict";function o(t,e){const r=!0===t?.__loading;return r===(!0===e?.__loading)?0:r?1:-1}function s(t,e){return null==t&&null==e?0:null==t?1:null==e?-1:"number"==typeof t&&"number"==typeof e?t-e:t instanceof Date&&e instanceof Date?t.getTime()-e.getTime():"boolean"==typeof t&&"boolean"==typeof e?t===e?0:t?-1:1:String(t).localeCompare(String(e))}function n(t,e){const r=t.findIndex(t=>t.field===e);return r>=0?r+1:void 0}function l(t,e){return t.find(t=>t.field===e)?.direction}class d extends r.BaseGridPlugin{static manifest={queries:[{type:"sort:get-model",description:"Returns the current multi-sort model as SortModel[]"},{type:"sort:set-model",description:"Sets the multi-sort model from context (SortModel[])"}]};name="multiSort";styles='@layer tbw-plugins{.header-cell[data-sort=asc]:after{content:"↑";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.header-cell[data-sort=desc]:after{content:"↓";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-indicator{margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-index{font-size:var(--tbw-font-size-2xs, .7em);background:var(--tbw-multi-sort-badge-bg, var(--tbw-color-panel-bg));color:var(--tbw-multi-sort-badge-color, var(--tbw-color-fg));border-radius:50%;width:var(--tbw-multi-sort-badge-size, 1em);height:var(--tbw-multi-sort-badge-size, 1em);display:inline-flex;align-items:center;justify-content:center;margin-left:var(--tbw-spacing-xs, .125em);font-weight:600}}';get defaultConfig(){return{maxSortColumns:3,showSortIndex:!0}}sortModel=[];cachedSortResult=null;#t=!1;#e=[];get#r(){return this.grid}clearCoreSortState(){this.#r._sortState=null}#i(t){const e=this.grid?.query?.("grouping:get-grouped-fields",null);if(!Array.isArray(e)||0===e.length)return t;const r=e[0];if(!Array.isArray(r)||0===r.length)return t;const i=new Set(r),o=t.filter(t=>!i.has(t.field));return o.length===t.length?t:o}detach(){this.sortModel=[],this.cachedSortResult=null}handleQuery(t){switch(t.type){case"sort:get-model":return[...this.sortModel];case"sort:set-model":{const e=t.context;return!!Array.isArray(e)&&(this.sortModel=[...e],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),!0)}default:return}}processRows(t){if(0===this.sortModel.length)return this.cachedSortResult=null,[...t];const e=this.#r;if(!e._isGridEditMode&&"number"==typeof e._activeEditRows&&-1!==e._activeEditRows&&this.cachedSortResult&&this.cachedSortResult.length===t.length)return[...this.cachedSortResult];const r=this.#i(this.sortModel),n=t;return r.length>0&&function(t,e,r){if(!e.length)return;const n=e.map(t=>{const e=r.find(e=>e.field===t.field),i=e?.sortComparator??s;return{field:t.field,asc:"asc"===t.direction,comparator:i,pinPlaceholders:!e?.sortComparator,column:e}}),l=(t,e)=>e.column?.valueAccessor?i.resolveCellValue(t,e.column):t[e.field];if(1===n.length){const e=n[0];t.sort((t,r)=>{if(e.pinPlaceholders){const e=o(t,r);if(0!==e)return e}const i=e.comparator(l(t,e),l(r,e),t,r);return e.asc?i:-i})}else t.sort((t,e)=>{if(n.some(t=>t.pinPlaceholders)){const r=o(t,e);if(0!==r)return r}for(let r=0;r<n.length;r++){const i=n[r],o=i.comparator(l(t,i),l(e,i),t,e);if(0!==o)return i.asc?o:-o}return 0})}(n,r,this.columns),this.cachedSortResult=n,n}onHeaderClick(t){const r=this.columns.find(e=>e.field===t.field);if(!r?.sortable)return!1;const i=t.originalEvent.shiftKey,o=this.config.maxSortColumns??3;if(this.sortModel=function(t,e,r,i){const o=t.find(t=>t.field===e);return r?o?"asc"===o.direction?t.map(t=>t.field===e?{...t,direction:"desc"}:t):t.filter(t=>t.field!==e):t.length<i?[...t,{field:e,direction:"asc"}]:t:"asc"===o?.direction?[{field:e,direction:"desc"}]:"desc"===o?.direction?[]:[{field:e,direction:"asc"}]}(this.sortModel,t.field,i,o),this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),this.grid?.requestStateChange?.(),this.sortModel.length>0){const t=this.sortModel.map(t=>{const e=this.columns.find(e=>e.field===t.field);return`${e?.header??t.field} ${"asc"===t.direction?"ascending":"descending"}`});e.announce(this.gridElement,e.getA11yMessage(this.gridElement,"sortApplied",t.join(", then "),""))}else e.announce(this.gridElement,e.getA11yMessage(this.gridElement,"sortCleared"));return!0}afterRender(){const t=this.gridElement;if(!t)return;const e=!1!==this.config.showSortIndex;t.querySelectorAll(".header-row .cell[data-field]").forEach(t=>{const r=t.getAttribute("data-field");if(!r)return;const i=n(this.sortModel,r),o=l(this.sortModel,r);if(t.querySelector(".sort-index")?.remove(),o){const r=this.updateSortIndicator(t,o);if(e&&this.sortModel.length>1&&void 0!==i){const e=document.createElement("span");e.className="sort-index",e.textContent=String(i),r.nextSibling?t.insertBefore(e,r.nextSibling):t.appendChild(e)}}else t.classList.contains("sortable")&&this.updateSortIndicator(t,null)})}getSortModel(){return[...this.sortModel]}setSortModel(t){if(this.sortModel=[...t],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...t]}),this.requestRender(),this.grid?.requestStateChange?.(),t.length>0){const r=t.map(t=>{const e=this.columns.find(e=>e.field===t.field);return`${e?.header??t.field} ${"asc"===t.direction?"ascending":"descending"}`});e.announce(this.gridElement,e.getA11yMessage(this.gridElement,"sortApplied",r.join(", then "),""))}}clearSort(){this.sortModel=[],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[]}),this.requestRender(),this.grid?.requestStateChange?.(),e.announce(this.gridElement,e.getA11yMessage(this.gridElement,"sortCleared"))}getSortIndex(t){return n(this.sortModel,t)}getSortDirection(t){return l(this.sortModel,t)}getColumnState(t){const e=this.sortModel.findIndex(e=>e.field===t);if(-1===e)return;return{sort:{direction:this.sortModel[e].direction,priority:e}}}applyColumnState(t,e){if(this.#t||(this.#e=[...this.sortModel]),e.sort){const r=this.sortModel.findIndex(e=>e.field===t),i={field:t,direction:e.sort.direction};-1!==r?this.sortModel[r]=i:this.sortModel.splice(e.sort.priority,0,i)}else this.sortModel=this.sortModel.filter(e=>e.field!==t);this.clearCoreSortState(),this.#t||(this.#t=!0,queueMicrotask(()=>{this.#t=!1;const t=this.#e;this.#e=[],function(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r].field!==e[r].field||t[r].direction!==e[r].direction)return!1;return!0}(t,this.sortModel)||(this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender())}))}}t.MultiSortPlugin=d,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=multi-sort.umd.js.map