@toolbox-web/grid 1.19.2 → 1.20.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 (50) hide show
  1. package/all.js +17 -19
  2. package/all.js.map +1 -1
  3. package/index.js +361 -349
  4. package/index.js.map +1 -1
  5. package/lib/core/grid.d.ts +22 -0
  6. package/lib/core/grid.d.ts.map +1 -1
  7. package/lib/core/internal/event-delegation.d.ts.map +1 -1
  8. package/lib/core/internal/sorting.d.ts +6 -0
  9. package/lib/core/internal/sorting.d.ts.map +1 -1
  10. package/lib/core/types.d.ts +6 -0
  11. package/lib/core/types.d.ts.map +1 -1
  12. package/lib/plugins/clipboard/ClipboardPlugin.d.ts.map +1 -1
  13. package/lib/plugins/clipboard/index.js +54 -54
  14. package/lib/plugins/clipboard/index.js.map +1 -1
  15. package/lib/plugins/column-virtualization/index.js.map +1 -1
  16. package/lib/plugins/context-menu/index.js.map +1 -1
  17. package/lib/plugins/editing/index.js.map +1 -1
  18. package/lib/plugins/export/index.js.map +1 -1
  19. package/lib/plugins/filtering/index.js.map +1 -1
  20. package/lib/plugins/grouping-columns/index.js.map +1 -1
  21. package/lib/plugins/grouping-rows/index.js.map +1 -1
  22. package/lib/plugins/master-detail/MasterDetailPlugin.d.ts.map +1 -1
  23. package/lib/plugins/master-detail/index.js +1 -1
  24. package/lib/plugins/master-detail/index.js.map +1 -1
  25. package/lib/plugins/multi-sort/index.js.map +1 -1
  26. package/lib/plugins/pinned-columns/index.js.map +1 -1
  27. package/lib/plugins/pinned-rows/index.js.map +1 -1
  28. package/lib/plugins/pivot/index.js.map +1 -1
  29. package/lib/plugins/print/index.js.map +1 -1
  30. package/lib/plugins/reorder/index.js.map +1 -1
  31. package/lib/plugins/responsive/index.js.map +1 -1
  32. package/lib/plugins/row-reorder/index.js.map +1 -1
  33. package/lib/plugins/selection/SelectionPlugin.d.ts.map +1 -1
  34. package/lib/plugins/selection/index.js +93 -95
  35. package/lib/plugins/selection/index.js.map +1 -1
  36. package/lib/plugins/server-side/index.js.map +1 -1
  37. package/lib/plugins/tree/index.js.map +1 -1
  38. package/lib/plugins/undo-redo/index.js.map +1 -1
  39. package/lib/plugins/visibility/index.js.map +1 -1
  40. package/package.json +11 -1
  41. package/umd/grid.all.umd.js +21 -21
  42. package/umd/grid.all.umd.js.map +1 -1
  43. package/umd/grid.umd.js +11 -11
  44. package/umd/grid.umd.js.map +1 -1
  45. package/umd/plugins/clipboard.umd.js +4 -4
  46. package/umd/plugins/clipboard.umd.js.map +1 -1
  47. package/umd/plugins/master-detail.umd.js +1 -1
  48. package/umd/plugins/master-detail.umd.js.map +1 -1
  49. package/umd/plugins/selection.umd.js +1 -1
  50. package/umd/plugins/selection.umd.js.map +1 -1
@@ -1,7 +1,7 @@
1
- (function(h,y){typeof exports=="object"&&typeof module<"u"?y(exports,require("../../core/plugin/base-plugin")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin"],y):(h=typeof globalThis<"u"?globalThis:h||self,y(h.TbwGridPlugin_clipboard={},h.TbwGrid))})(this,(function(h,y){"use strict";function C(c,t,e=!0){let n=c;if(e&&(n=n.filter(s=>!s.hidden&&!s.field.startsWith("__")&&s.meta?.utility!==!0)),t?.length){const s=new Set(t);n=n.filter(o=>s.has(o.field))}return n}function S(c,t){return t?.length?[...t].sort((e,n)=>e-n).map(e=>c[e]).filter(e=>e!=null):c}function T(c){return c==null?"":c instanceof Date?c.toISOString():typeof c=="object"?JSON.stringify(c):String(c)}async function I(c){try{return await navigator.clipboard.writeText(c),!0}catch(t){console.warn("[copyToClipboard] Clipboard API failed:",t);const e=document.createElement("textarea");e.value=c,e.style.position="fixed",e.style.opacity="0",e.style.pointerEvents="none",document.body.appendChild(e),e.select();const n=document.execCommand("copy");return document.body.removeChild(e),n}}function x(c,t){const e=t.delimiter??" ",n=t.newline??`
1
+ (function(h,y){typeof exports=="object"&&typeof module<"u"?y(exports,require("../../core/plugin/base-plugin")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin"],y):(h=typeof globalThis<"u"?globalThis:h||self,y(h.TbwGridPlugin_clipboard={},h.TbwGrid))})(this,(function(h,y){"use strict";function C(c,t,e=!0){let n=c;if(e&&(n=n.filter(s=>!s.hidden&&!s.field.startsWith("__")&&s.meta?.utility!==!0)),t?.length){const s=new Set(t);n=n.filter(o=>s.has(o.field))}return n}function S(c,t){return t?.length?[...t].sort((e,n)=>e-n).map(e=>c[e]).filter(e=>e!=null):c}function T(c){return c==null?"":c instanceof Date?c.toISOString():typeof c=="object"?JSON.stringify(c):String(c)}async function I(c){try{return await navigator.clipboard.writeText(c),!0}catch(t){console.warn("[copyToClipboard] Clipboard API failed:",t);const e=document.createElement("textarea");e.value=c,e.style.position="fixed",e.style.opacity="0",e.style.pointerEvents="none",document.body.appendChild(e),e.select();const n=document.execCommand("copy");return document.body.removeChild(e),n}}function b(c,t){const e=t.delimiter??" ",n=t.newline??`
2
2
  `,s=c.replace(/\r\n/g,`
3
3
  `).replace(/\r/g,`
4
- `),o=[];let i=[],l="",a=!1;for(let r=0;r<s.length;r++){const d=s[r];d==='"'&&!a?a=!0:d==='"'&&a?s[r+1]==='"'?(l+='"',r++):a=!1:d===e&&!a?(i.push(l),l=""):d===n&&!a?(i.push(l),l="",(i.length>1||i.some(u=>u.trim()!==""))&&o.push(i),i=[]):l+=d}return i.push(l),(i.length>1||i.some(r=>r.trim()!==""))&&o.push(i),o}async function P(){try{return await navigator.clipboard.readText()}catch{return""}}function R(c,t){const{rows:e,target:n,fields:s}=c;if(!n)return;const o=t.rows,i=t.effectiveConfig.columns??[],l=i.map(u=>u.field),a=new Map;i.forEach(u=>{a.set(u.field,u.editable===!0)});const r=[...o],d=n.bounds?n.bounds.endRow:1/0;e.forEach((u,m)=>{const f=n.row+m;if(!(f>d)){if(n.bounds){if(f>=r.length)return}else for(;f>=r.length;){const g={};l.forEach(w=>g[w]=""),r.push(g)}r[f]={...r[f]},u.forEach((g,w)=>{const p=s[w];p&&a.get(p)&&(r[f][p]=g)})}}),t.rows=r}class M extends y.BaseGridPlugin{static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:" ",newline:`
5
- `,quoteStrings:!1}}lastCopied=null;attach(t){super.attach(t),t.addEventListener("paste",n=>this.#o(n),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(t){return(t.ctrlKey||t.metaKey)&&t.key==="c"?(t.preventDefault(),this.#s(t.target),!0):!1}#s(t){const e=this.#e();if(e&&e.ranges.length===0){const n=this.#i(t);if(!n)return;const s=this.columns[n.col];if(!s)return;this.copy({rowIndices:[n.row],columns:[s.field]});return}this.copy()}#o(t){const e=t.clipboardData?.getData("text/plain");if(!e)return;t.preventDefault();const n=x(e,this.config),s=this.#e(),o=s?.ranges?.[0],i=o?.from.row??0,l=o?.from.col??0,r=o&&(s?.mode==="range"||s?.mode==="row")&&(o.from.row!==o.to.row||o.from.col!==o.to.col)?{endRow:o.to.row,endCol:o.to.col}:null,d=r?.endCol??this.columns.length-1,u=this.columns[l],m=u?{row:i,col:l,field:u.field,bounds:r}:null,f=[],g=n[0]?.length??0;for(let p=0;p<g&&l+p<=d;p++){const b=this.columns[l+p];b&&!b.hidden&&f.push(b.field)}const w={rows:n,text:e,target:m,fields:f};this.emit("paste",w),this.#r(w)}#r(t){if(!this.grid)return;const{pasteHandler:e}=this.config;if(e===null)return;(e??R)(t,this.grid)}#e(){return this.grid?.query("getSelection")?.[0]}#t(t){const e=this.#e();let n;if(t?.columns)n=C(this.columns,t.columns);else if(e?.ranges.length&&e.mode!=="row"){const o=e.ranges[e.ranges.length-1],i=Math.min(o.from.col,o.to.col),l=Math.max(o.from.col,o.to.col);n=C(this.columns.slice(i,l+1))}else n=C(this.columns);let s;if(t?.rowIndices)s=S(this.rows,t.rowIndices);else if(e?.ranges.length){const o=e.ranges[e.ranges.length-1],i=Math.min(o.from.row,o.to.row),l=Math.max(o.from.row,o.to.row);s=[];for(let a=i;a<=l;a++){const r=this.rows[a];r&&s.push(r)}}else s=this.rows;return{columns:n,rows:s}}#n(t,e,n){const s=n?.delimiter??this.config.delimiter??" ",o=n?.newline??this.config.newline??`
6
- `,i=n?.includeHeaders??this.config.includeHeaders??!1,l=n?.processCell??this.config.processCell,a=[];i&&a.push(t.map(r=>r.header||r.field).join(s));for(const r of e){const d=t.map(u=>{const m=r[u.field];return l?l(m,u.field,r):T(m)});a.push(d.join(s))}return a.join(o)}#i(t){const e=t.closest("[data-field-cache]");if(!e)return null;const n=e.dataset.fieldCache,s=e.dataset.row;if(!n||!s)return null;const o=parseInt(s,10);if(isNaN(o))return null;const i=this.columns.findIndex(l=>l.field===n);return i===-1?null:{row:o,col:i}}getSelectionAsText(t){const{columns:e,rows:n}=this.#t(t);return e.length===0||n.length===0?"":this.#n(e,n,t)}async copy(t){const{columns:e,rows:n}=this.#t(t);if(e.length===0||n.length===0)return"";const s=this.#n(e,n,t);return await I(s),this.lastCopied={text:s,timestamp:Date.now()},this.emit("copy",{text:s,rowCount:n.length,columnCount:e.length}),s}async copyRows(t,e){return t.length===0?"":this.copy({...e,rowIndices:t})}async paste(){const t=await P();return t?x(t,this.config):null}getLastCopied(){return this.lastCopied}}h.ClipboardPlugin=M,h.defaultPasteHandler=R,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));
4
+ `),o=[];let r=[],l="",a=!1;for(let i=0;i<s.length;i++){const d=s[i];d==='"'&&!a?a=!0:d==='"'&&a?s[i+1]==='"'?(l+='"',i++):a=!1:d===e&&!a?(r.push(l),l=""):d===n&&!a?(r.push(l),l="",(r.length>1||r.some(u=>u.trim()!==""))&&o.push(r),r=[]):l+=d}return r.push(l),(r.length>1||r.some(i=>i.trim()!==""))&&o.push(r),o}async function P(){try{return await navigator.clipboard.readText()}catch{return""}}function x(c,t){const{rows:e,target:n,fields:s}=c;if(!n)return;const o=t.rows,r=t.effectiveConfig.columns??[],l=r.map(u=>u.field),a=new Map;r.forEach(u=>{a.set(u.field,u.editable===!0)});const i=[...o],d=n.bounds?n.bounds.endRow:1/0;e.forEach((u,m)=>{const f=n.row+m;if(!(f>d)){if(n.bounds){if(f>=i.length)return}else for(;f>=i.length;){const g={};l.forEach(w=>g[w]=""),i.push(g)}i[f]={...i[f]},u.forEach((g,w)=>{const p=s[w];p&&a.get(p)&&(i[f][p]=g)})}}),t.rows=i}class M extends y.BaseGridPlugin{static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:" ",newline:`
5
+ `,quoteStrings:!1}}lastCopied=null;attach(t){super.attach(t),t.addEventListener("paste",n=>this.#o(n),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(t){return(t.ctrlKey||t.metaKey)&&t.key==="c"?(t.preventDefault(),this.#s(t.target),!0):!1}#s(t){const e=this.#e();if(e&&e.ranges.length===0){const n=this.#r(t);if(!n)return;const s=this.columns[n.col];if(!s)return;this.copy({rowIndices:[n.row],columns:[s.field]});return}this.copy()}#o(t){const e=t.clipboardData?.getData("text/plain");if(!e)return;t.preventDefault();const n=b(e,this.config),s=this.#e(),o=s?.ranges?.[0],r=o?.from.row??0,l=o?.from.col??0,i=o&&(s?.mode==="range"||s?.mode==="row")&&(o.from.row!==o.to.row||o.from.col!==o.to.col)?{endRow:o.to.row,endCol:o.to.col}:null,d=i?.endCol??this.visibleColumns.length-1,u=this.visibleColumns[l],m=u?{row:r,col:l,field:u.field,bounds:i}:null,f=[],g=n[0]?.length??0;for(let p=0;p<g&&l+p<=d;p++){const R=this.visibleColumns[l+p];R&&f.push(R.field)}const w={rows:n,text:e,target:m,fields:f};this.emit("paste",w),this.#i(w)}#i(t){if(!this.grid)return;const{pasteHandler:e}=this.config;if(e===null)return;(e??x)(t,this.grid)}#e(){return this.grid?.query("getSelection")?.[0]}#t(t){const e=this.#e();let n;if(t?.columns)n=C(this.columns,t.columns);else if(e?.ranges.length&&e.mode!=="row"){const o=e.ranges[e.ranges.length-1],r=Math.min(o.from.col,o.to.col),l=Math.max(o.from.col,o.to.col);n=C(this.visibleColumns.slice(r,l+1))}else n=C(this.columns);let s;if(t?.rowIndices)s=S(this.rows,t.rowIndices);else if(e?.ranges.length){const o=e.ranges[e.ranges.length-1],r=Math.min(o.from.row,o.to.row),l=Math.max(o.from.row,o.to.row);s=[];for(let a=r;a<=l;a++){const i=this.rows[a];i&&s.push(i)}}else s=this.rows;return{columns:n,rows:s}}#n(t,e,n){const s=n?.delimiter??this.config.delimiter??" ",o=n?.newline??this.config.newline??`
6
+ `,r=n?.includeHeaders??this.config.includeHeaders??!1,l=n?.processCell??this.config.processCell,a=[];r&&a.push(t.map(i=>i.header||i.field).join(s));for(const i of e){const d=t.map(u=>{const m=i[u.field];return l?l(m,u.field,i):T(m)});a.push(d.join(s))}return a.join(o)}#r(t){const e=t.closest("[data-field-cache]");if(!e)return null;const n=e.dataset.fieldCache,s=e.dataset.row;if(!n||!s)return null;const o=parseInt(s,10);if(isNaN(o))return null;const r=this.columns.findIndex(l=>l.field===n);return r===-1?null:{row:o,col:r}}getSelectionAsText(t){const{columns:e,rows:n}=this.#t(t);return e.length===0||n.length===0?"":this.#n(e,n,t)}async copy(t){const{columns:e,rows:n}=this.#t(t);if(e.length===0||n.length===0)return"";const s=this.#n(e,n,t);return await I(s),this.lastCopied={text:s,timestamp:Date.now()},this.emit("copy",{text:s,rowCount:n.length,columnCount:e.length}),s}async copyRows(t,e){return t.length===0?"":this.copy({...e,rowIndices:t})}async paste(){const t=await P();return t?b(t,this.config):null}getLastCopied(){return this.lastCopied}}h.ClipboardPlugin=M,h.defaultPasteHandler=x,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));
7
7
  //# sourceMappingURL=clipboard.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts","../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../libs/grid/src/lib/plugins/clipboard/ClipboardPlugin.ts"],"sourcesContent":["/**\n * 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 Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { ClipboardConfig } from './types';\n\n/** Parameters for building clipboard text */\nexport interface CopyParams {\n /** All grid rows */\n rows: unknown[];\n /** Column configurations */\n columns: ColumnConfig[];\n /** Selected row indices */\n selectedIndices: Set<number> | number[];\n /** Clipboard configuration */\n config: ClipboardConfig;\n}\n\n/**\n * Format a cell value for clipboard output.\n *\n * Uses custom processCell if provided, otherwise applies default formatting:\n * - null/undefined → empty string\n * - Date → ISO string\n * - Object → JSON string\n * - Other → String conversion with optional quoting\n *\n * @param value - The cell value to format\n * @param field - The field name\n * @param row - The full row object\n * @param config - Clipboard configuration\n * @returns Formatted string value\n */\nexport function formatCellValue(value: unknown, field: string, row: unknown, config: ClipboardConfig): string {\n if (config.processCell) {\n return config.processCell(value, field, row);\n }\n\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n\n const str = String(value);\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Quote if contains delimiter, newline, or quotes (or if quoteStrings is enabled)\n if (config.quoteStrings || str.includes(delimiter) || str.includes(newline) || str.includes('\"')) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build clipboard text from selected rows and columns.\n *\n * @param params - Copy parameters including rows, columns, selection, and config\n * @returns Tab-separated (or custom delimiter) text ready for clipboard\n */\nexport function buildClipboardText(params: CopyParams): string {\n const { rows, columns, selectedIndices, config } = params;\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Filter to visible columns (not hidden, not internal __ prefixed)\n const visibleColumns = columns.filter((c) => !c.hidden && !c.field.startsWith('__'));\n\n const lines: string[] = [];\n\n // Add header row if configured\n if (config.includeHeaders) {\n const headerCells = visibleColumns.map((c) => {\n const header = c.header || c.field;\n // Quote headers if they contain special characters\n if (header.includes(delimiter) || header.includes(newline) || header.includes('\"')) {\n return `\"${header.replace(/\"/g, '\"\"')}\"`;\n }\n return header;\n });\n lines.push(headerCells.join(delimiter));\n }\n\n // Convert indices to sorted array\n const indices = selectedIndices instanceof Set ? [...selectedIndices] : selectedIndices;\n const sortedIndices = [...indices].sort((a, b) => a - b);\n\n // Build data rows\n for (const idx of sortedIndices) {\n const row = rows[idx];\n if (!row) continue;\n\n const cells = visibleColumns.map((col) =>\n formatCellValue((row as Record<string, unknown>)[col.field], col.field, row, config),\n );\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n}\n\n/**\n * Copy text to the system clipboard.\n *\n * Uses the modern Clipboard API when available, with fallback\n * to execCommand for older browsers.\n *\n * @param text - The text to copy\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch (err) {\n console.warn('[copyToClipboard] 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","/**\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.getPlugin(ClipboardPlugin);\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 * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport 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 * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `includeHeaders` | `boolean` | `false` | Include column headers in copied data |\n * | `delimiter` | `string` | `'\\t'` | Column delimiter (tab for Excel compatibility) |\n * | `newline` | `string` | `'\\n'` | Row delimiter |\n * | `quoteStrings` | `boolean` | `false` | Wrap string values in quotes |\n * | `processCell` | `(value, field, row) => string` | - | Custom cell value processor |\n * | `pasteHandler` | `PasteHandler \\| null` | `defaultPasteHandler` | Custom paste handler |\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `copy` | `(options?: CopyOptions) => Promise<string>` | Copy to clipboard with optional column/row control |\n * | `copyRows` | `(indices, options?) => Promise<string>` | Copy specific rows to clipboard |\n * | `paste` | `() => Promise<string[][] \\| null>` | Read and parse clipboard content |\n * | `getSelectionAsText` | `(options?: CopyOptions) => string` | Get clipboard text without writing to clipboard |\n * | `getLastCopied` | `() => { text, timestamp } \\| null` | Get info about last copy operation |\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see {@link SelectionPlugin} for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n const el = grid as unknown as HTMLElement;\n el.addEventListener('paste', (e: Event) => this.#handleNativePaste(e as ClipboardEvent), {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n // 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 const maxCol = bounds?.endCol ?? this.columns.length - 1;\n\n // Build target info\n const column = this.columns[targetCol];\n const target: PasteTarget | null = column ? { row: targetRow, col: targetCol, field: column.field, bounds } : null;\n\n // Build field list for paste width (constrained by bounds if set)\n const fields: string[] = [];\n const pasteWidth = parsed[0]?.length ?? 0;\n for (let i = 0; i < pasteWidth && targetCol + i <= maxCol; i++) {\n const col = this.columns[targetCol + i];\n if (col && !col.hidden) {\n fields.push(col.field);\n }\n }\n\n const detail: PasteDetail = { rows: parsed, text, target, fields };\n\n // Emit the event for any listeners\n this.emit<PasteDetail>('paste', detail);\n\n // Apply paste data using the configured handler (or default)\n this.#applyPasteHandler(detail);\n }\n\n /**\n * Apply the paste handler to update grid data.\n *\n * Uses the configured `pasteHandler`, or the default handler if not specified.\n * Set `pasteHandler: null` in config to disable auto-paste.\n */\n #applyPasteHandler(detail: PasteDetail): void {\n if (!this.grid) return;\n\n const { pasteHandler } = this.config;\n\n // pasteHandler: null means explicitly disabled\n if (pasteHandler === null) return;\n\n // Use custom handler or default\n const handler = pasteHandler ?? defaultPasteHandler;\n handler(detail, this.grid);\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection');\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 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.columns.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 #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 = row[col.field];\n if (processCell) return processCell(value, col.field, row);\n return formatValueAsText(value);\n });\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\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.getPlugin(ClipboardPlugin);\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.getPlugin(ClipboardPlugin);\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.getPlugin(ClipboardPlugin);\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"],"names":["resolveColumns","columns","fields","onlyVisible","result","c","fieldSet","resolveRows","rows","indices","a","b","i","r","formatValueAsText","value","copyToClipboard","text","err","textarea","success","parseClipboardText","config","delimiter","newline","normalizedText","currentRow","currentCell","inQuotes","char","readFromClipboard","defaultPasteHandler","detail","grid","pastedRows","target","currentRows","allFields","col","editableMap","newRows","maxPasteRow","rowData","rowOffset","targetRowIndex","emptyRow","field","cellValue","colOffset","ClipboardPlugin","BaseGridPlugin","e","#handleNativePaste","event","#handleCopy","selection","#getSelection","focused","#getFocusedCellFromDOM","parsed","firstRange","targetRow","targetCol","bounds","maxCol","column","pasteWidth","#applyPasteHandler","pasteHandler","#resolveData","options","range","minCol","minRow","maxRow","row","#buildText","includeHeaders","processCell","lines","cells","cell","rowIndexStr"],"mappings":"qUAwBO,SAASA,EACdC,EACAC,EACAC,EAAc,GACE,CAChB,IAAIC,EAASH,EAMb,GAJIE,IACFC,EAASA,EAAO,OAAQC,GAAM,CAACA,EAAE,QAAU,CAACA,EAAE,MAAM,WAAW,IAAI,GAAKA,EAAE,MAAM,UAAY,EAAI,GAG9FH,GAAQ,OAAQ,CAClB,MAAMI,EAAW,IAAI,IAAIJ,CAAM,EAC/BE,EAASA,EAAO,OAAQC,GAAMC,EAAS,IAAID,EAAE,KAAK,CAAC,CACrD,CAEA,OAAOD,CACT,CASO,SAASG,EAAeC,EAAoBC,EAAyB,CAC1E,OAAKA,GAAS,OAEP,CAAC,GAAGA,CAAO,EACf,KAAK,CAACC,EAAGC,IAAMD,EAAIC,CAAC,EACpB,IAAKC,GAAMJ,EAAKI,CAAC,CAAC,EAClB,OAAQC,GAAcA,GAAK,IAAI,EALLL,CAM/B,CAWO,SAASM,EAAkBC,EAAwB,CACxD,OAAIA,GAAS,KAAa,GACtBA,aAAiB,KAAaA,EAAM,YAAA,EACpC,OAAOA,GAAU,SAAiB,KAAK,UAAUA,CAAK,EACnD,OAAOA,CAAK,CACrB,CCwCA,eAAsBC,EAAgBC,EAAgC,CACpE,GAAI,CACF,aAAM,UAAU,UAAU,UAAUA,CAAI,EACjC,EACT,OAASC,EAAK,C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D,EAAQ,SAAW,EAAU,GAC1B,KAAK,KAAK,CAAE,GAAG6D,EAAS,WAAY7D,EAAS,CACtD,CAMA,MAAM,OAAoC,CACxC,MAAMQ,EAAO,MAAMa,EAAA,EACnB,OAAKb,EACEI,EAAmBJ,EAAM,KAAK,MAAM,EADzB,IAEpB,CAMA,eAA4D,CAC1D,OAAO,KAAK,UACd,CAEF"}
1
+ {"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts","../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../libs/grid/src/lib/plugins/clipboard/ClipboardPlugin.ts"],"sourcesContent":["/**\n * 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 Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { ClipboardConfig } from './types';\n\n/** Parameters for building clipboard text */\nexport interface CopyParams {\n /** All grid rows */\n rows: unknown[];\n /** Column configurations */\n columns: ColumnConfig[];\n /** Selected row indices */\n selectedIndices: Set<number> | number[];\n /** Clipboard configuration */\n config: ClipboardConfig;\n}\n\n/**\n * Format a cell value for clipboard output.\n *\n * Uses custom processCell if provided, otherwise applies default formatting:\n * - null/undefined → empty string\n * - Date → ISO string\n * - Object → JSON string\n * - Other → String conversion with optional quoting\n *\n * @param value - The cell value to format\n * @param field - The field name\n * @param row - The full row object\n * @param config - Clipboard configuration\n * @returns Formatted string value\n */\nexport function formatCellValue(value: unknown, field: string, row: unknown, config: ClipboardConfig): string {\n if (config.processCell) {\n return config.processCell(value, field, row);\n }\n\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n\n const str = String(value);\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Quote if contains delimiter, newline, or quotes (or if quoteStrings is enabled)\n if (config.quoteStrings || str.includes(delimiter) || str.includes(newline) || str.includes('\"')) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build clipboard text from selected rows and columns.\n *\n * @param params - Copy parameters including rows, columns, selection, and config\n * @returns Tab-separated (or custom delimiter) text ready for clipboard\n */\nexport function buildClipboardText(params: CopyParams): string {\n const { rows, columns, selectedIndices, config } = params;\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Filter to visible columns (not hidden, not internal __ prefixed)\n const visibleColumns = columns.filter((c) => !c.hidden && !c.field.startsWith('__'));\n\n const lines: string[] = [];\n\n // Add header row if configured\n if (config.includeHeaders) {\n const headerCells = visibleColumns.map((c) => {\n const header = c.header || c.field;\n // Quote headers if they contain special characters\n if (header.includes(delimiter) || header.includes(newline) || header.includes('\"')) {\n return `\"${header.replace(/\"/g, '\"\"')}\"`;\n }\n return header;\n });\n lines.push(headerCells.join(delimiter));\n }\n\n // Convert indices to sorted array\n const indices = selectedIndices instanceof Set ? [...selectedIndices] : selectedIndices;\n const sortedIndices = [...indices].sort((a, b) => a - b);\n\n // Build data rows\n for (const idx of sortedIndices) {\n const row = rows[idx];\n if (!row) continue;\n\n const cells = visibleColumns.map((col) =>\n formatCellValue((row as Record<string, unknown>)[col.field], col.field, row, config),\n );\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n}\n\n/**\n * Copy text to the system clipboard.\n *\n * Uses the modern Clipboard API when available, with fallback\n * to execCommand for older browsers.\n *\n * @param text - The text to copy\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch (err) {\n console.warn('[copyToClipboard] 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","/**\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.getPlugin(ClipboardPlugin);\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 * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport 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 * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `includeHeaders` | `boolean` | `false` | Include column headers in copied data |\n * | `delimiter` | `string` | `'\\t'` | Column delimiter (tab for Excel compatibility) |\n * | `newline` | `string` | `'\\n'` | Row delimiter |\n * | `quoteStrings` | `boolean` | `false` | Wrap string values in quotes |\n * | `processCell` | `(value, field, row) => string` | - | Custom cell value processor |\n * | `pasteHandler` | `PasteHandler \\| null` | `defaultPasteHandler` | Custom paste handler |\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `copy` | `(options?: CopyOptions) => Promise<string>` | Copy to clipboard with optional column/row control |\n * | `copyRows` | `(indices, options?) => Promise<string>` | Copy specific rows to clipboard |\n * | `paste` | `() => Promise<string[][] \\| null>` | Read and parse clipboard content |\n * | `getSelectionAsText` | `(options?: CopyOptions) => string` | Get clipboard text without writing to clipboard |\n * | `getLastCopied` | `() => { text, timestamp } \\| null` | Get info about last copy operation |\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see {@link SelectionPlugin} for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n const el = grid as unknown as HTMLElement;\n el.addEventListener('paste', (e: Event) => this.#handleNativePaste(e as ClipboardEvent), {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n // 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 #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 = row[col.field];\n if (processCell) return processCell(value, col.field, row);\n return formatValueAsText(value);\n });\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\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.getPlugin(ClipboardPlugin);\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.getPlugin(ClipboardPlugin);\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.getPlugin(ClipboardPlugin);\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"],"names":["resolveColumns","columns","fields","onlyVisible","result","c","fieldSet","resolveRows","rows","indices","a","b","i","r","formatValueAsText","value","copyToClipboard","text","err","textarea","success","parseClipboardText","config","delimiter","newline","normalizedText","currentRow","currentCell","inQuotes","char","readFromClipboard","defaultPasteHandler","detail","grid","pastedRows","target","currentRows","allFields","col","editableMap","newRows","maxPasteRow","rowData","rowOffset","targetRowIndex","emptyRow","field","cellValue","colOffset","ClipboardPlugin","BaseGridPlugin","e","#handleNativePaste","event","#handleCopy","selection","#getSelection","focused","#getFocusedCellFromDOM","parsed","firstRange","targetRow","targetCol","bounds","maxCol","column","pasteWidth","#applyPasteHandler","pasteHandler","#resolveData","options","range","minCol","minRow","maxRow","row","#buildText","includeHeaders","processCell","lines","cells","cell","rowIndexStr"],"mappings":"qUAwBO,SAASA,EACdC,EACAC,EACAC,EAAc,GACE,CAChB,IAAIC,EAASH,EAMb,GAJIE,IACFC,EAASA,EAAO,OAAQC,GAAM,CAACA,EAAE,QAAU,CAACA,EAAE,MAAM,WAAW,IAAI,GAAKA,EAAE,MAAM,UAAY,EAAI,GAG9FH,GAAQ,OAAQ,CAClB,MAAMI,EAAW,IAAI,IAAIJ,CAAM,EAC/BE,EAASA,EAAO,OAAQC,GAAMC,EAAS,IAAID,EAAE,KAAK,CAAC,CACrD,CAEA,OAAOD,CACT,CASO,SAASG,EAAeC,EAAoBC,EAAyB,CAC1E,OAAKA,GAAS,OAEP,CAAC,GAAGA,CAAO,EACf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O,EACnD,GAAIrE,EAAQ,SAAW,GAAKO,EAAK,SAAW,EAC1C,MAAO,GAGT,MAAMS,EAAO,KAAK2D,GAAW3E,EAASO,EAAM8D,CAAO,EACnD,aAAMtD,EAAgBC,CAAI,EAC1B,KAAK,WAAa,CAAE,KAAAA,EAAM,UAAW,KAAK,KAAI,EAC9C,KAAK,KAAiB,OAAQ,CAC5B,KAAAA,EACA,SAAUT,EAAK,OACf,YAAaP,EAAQ,MAAA,CACtB,EACMgB,CACT,CAmBA,MAAM,SAASR,EAAmB6D,EAA4D,CAC5F,OAAI7D,EAAQ,SAAW,EAAU,GAC1B,KAAK,KAAK,CAAE,GAAG6D,EAAS,WAAY7D,EAAS,CACtD,CAMA,MAAM,OAAoC,CACxC,MAAMQ,EAAO,MAAMa,EAAA,EACnB,OAAKb,EACEI,EAAmBJ,EAAM,KAAK,MAAM,EADzB,IAEpB,CAMA,eAA4D,CAC1D,OAAO,KAAK,UACd,CAEF"}
@@ -1,2 +1,2 @@
1
- (function(g,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("../../core/internal/sanitize"),require("../../core/plugin/base-plugin"),require("../../core/plugin/expander-column")):typeof define=="function"&&define.amd?define(["exports","../../core/internal/sanitize","../../core/plugin/base-plugin","../../core/plugin/expander-column"],w):(g=typeof globalThis<"u"?globalThis:g||self,w(g.TbwGridPlugin_masterDetail={},g.TbwGrid,g.TbwGrid,g.TbwGrid))})(this,(function(g,w,A,x){"use strict";function R(f,e){const t=new Set(f);return t.has(e)?t.delete(e):t.add(e),t}function v(f,e){const t=new Set(f);return t.add(e),t}function y(f,e){const t=new Set(f);return t.delete(e),t}function D(f,e){return f.has(e)}function H(f,e,t,i){const s=document.createElement("div");s.className="master-detail-row",s.setAttribute("data-detail-for",String(e)),s.setAttribute("role","row");const n=document.createElement("div");n.className="master-detail-cell",n.setAttribute("role","cell"),n.style.gridColumn=`1 / ${i+1}`;const c=t(f,e);return typeof c=="string"?n.innerHTML=c:c instanceof HTMLElement&&n.appendChild(c),s.appendChild(n),s}const C="@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-right:none!important;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1 / 3}tbw-grid .master-detail-expander{display:flex;align-items:center;justify-content:center;width:100%;height:100%}tbw-grid .master-detail-toggle{cursor:pointer;opacity:.7;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center}tbw-grid .master-detail-toggle:hover{opacity:1}tbw-grid .master-detail-row{grid-column:1 / -1;display:grid;background:var(--tbw-master-detail-bg, var(--tbw-color-row-alt));border-bottom:1px solid var(--tbw-master-detail-border, var(--tbw-color-border));overflow:hidden}tbw-grid .master-detail-cell{padding:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));overflow:auto}tbw-grid .master-detail-row.tbw-expanding{animation:tbw-detail-expand var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .master-detail-row.tbw-collapsing{animation:tbw-detail-collapse var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-detail-expand{0%{opacity:0;max-height:0;padding-top:0;padding-bottom:0}to{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem);padding-top:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));padding-bottom:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem))}}@keyframes tbw-detail-collapse{0%{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem)}to{opacity:0;max-height:0}}}";class b extends A.BaseGridPlugin{name="masterDetail";styles=C;get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,animation:"slide"}}attach(e){super.attach(e),this.parseLightDomDetail()}parseLightDomDetail(){const e=this.grid;if(!e||typeof e.querySelector!="function")return;const t=e.querySelector("tbw-grid-detail");if(!t)return;const i=e;if(i.__frameworkAdapter?.parseDetailElement){const r=i.__frameworkAdapter.parseDetailElement(t);if(r){this.config={...this.config,detailRenderer:r};return}}const s=t.getAttribute("animation"),n=t.getAttribute("show-expand-column"),c=t.getAttribute("expand-on-row-click"),h=t.getAttribute("collapse-on-click-outside"),d=t.getAttribute("height"),o={};s!==null&&(o.animation=s==="false"?!1:s),n!==null&&(o.showExpandColumn=n!=="false"),c!==null&&(o.expandOnRowClick=c==="true"),h!==null&&(o.collapseOnClickOutside=h==="true"),d!==null&&(o.detailHeight=d==="auto"?"auto":parseInt(d,10));const a=t.innerHTML.trim();a&&!this.config.detailRenderer&&(o.detailRenderer=(r,l)=>{const u=w.evalTemplateString(a,{value:r,row:r});return w.sanitizeHTML(u)}),Object.keys(o).length>0&&(this.config={...this.config,...o})}get animationStyle(){return this.isAnimationEnabled?this.config.animation??"slide":!1}animateExpand(e,t,i){if(!this.isAnimationEnabled||this.animationStyle===!1)return!1;e.classList.add("tbw-expanding");let s=!1;const n=()=>{s||(s=!0,e.classList.remove("tbw-expanding"),t!==void 0&&i!==void 0&&this.#t(e,t,i))};return e.addEventListener("animationend",n,{once:!0}),setTimeout(n,this.animationDuration+50),!0}animateCollapse(e,t){if(!this.isAnimationEnabled||this.animationStyle===!1){t();return}e.classList.add("tbw-collapsing");const i=()=>{e.classList.remove("tbw-collapsing"),t()};e.addEventListener("animationend",i,{once:!0}),setTimeout(i,this.animationDuration+50)}#t(e,t,i){if(!e.isConnected)return;const s=e.offsetHeight;if(s>0){const n=this.measuredDetailHeights.get(t);this.measuredDetailHeights.set(t,s),n!==s&&this.grid.invalidateRowHeight(i)}}expandedRows=new Set;detailElements=new Map;measuredDetailHeights=new Map;rowsToAnimate=new Set;static DEFAULT_DETAIL_HEIGHT=150;getDetailHeight(e){const t=this.detailElements.get(e);if(t&&!(t.classList.contains("tbw-expanding")||t.classList.contains("tbw-collapsing"))){const n=t.offsetHeight;if(n>0)return this.measuredDetailHeights.set(e,n),n}const i=this.measuredDetailHeights.get(e);return i&&i>0?i:typeof this.config?.detailHeight=="number"?this.config.detailHeight:b.DEFAULT_DETAIL_HEIGHT}toggleAndEmit(e,t){this.expandedRows=R(this.expandedRows,e);const i=this.expandedRows.has(e);i&&this.rowsToAnimate.add(e),this.emit("detail-expand",{rowIndex:t,row:e,expanded:i}),this.requestRender()}detach(){this.expandedRows.clear(),this.detailElements.clear(),this.measuredDetailHeights.clear(),this.rowsToAnimate.clear()}processColumns(e){if(!(this.config.showExpandColumn===!0||this.config.showExpandColumn!==!1&&!!this.config.detailRenderer))return[...e];const i=[...e];if(x.findExpanderColumn(i))return i;const n=x.createExpanderColumnConfig(this.name);return n.viewRenderer=c=>{const{row:h}=c,d=this.expandedRows.has(h),o=document.createElement("span");o.className="master-detail-expander expander-cell";const a=document.createElement("span");return a.className=`master-detail-toggle${d?" expanded":""}`,this.setIcon(a,this.resolveIcon(d?"collapse":"expand")),a.setAttribute("role","button"),a.setAttribute("tabindex","0"),a.setAttribute("aria-expanded",String(d)),a.setAttribute("aria-label",d?"Collapse details":"Expand details"),o.appendChild(a),o},[n,...i]}onRowClick(e){if(!(!this.config.expandOnRowClick||!this.config.detailRenderer))return this.toggleAndEmit(e.row,e.rowIndex),!1}onCellClick(e){if(e.originalEvent?.target?.classList.contains("master-detail-toggle"))return this.toggleAndEmit(e.row,e.rowIndex),!0;this.expandedRows.size>0&&queueMicrotask(()=>this.#e())}onKeyDown(e){if(e.key!==" ")return;const t=this.grid._focusCol,i=this.grid._focusRow,s=this.columns[t];if(!s||!x.isExpanderColumn(s))return;const n=this.rows[i];if(n)return e.preventDefault(),this.toggleAndEmit(n,i),this.requestRenderWithFocus(),!0}afterRender(){this.#e()}onScrollRender(){!this.config.detailRenderer||this.expandedRows.size===0||this.#e()}#e(){if(!this.config.detailRenderer)return;const e=this.gridElement?.querySelector(".rows");if(!e)return;const t=this.grid,i=t._rowPool,s=t._virtualization?.start??0,n=t._virtualization?.end??0,c=this.columns.length,h=s,d=n,o=new Map;if(i){const a=Math.min(i.length,d-h);for(let r=0;r<a;r++){const l=i[r];l.parentNode===e&&o.set(h+r,l)}}else{const a=e.querySelectorAll(".data-grid-row");for(const r of a){const l=r.querySelector(".cell[data-row]"),u=l?parseInt(l.getAttribute("data-row")??"-1",10):-1;u>=0&&o.set(u,r)}}for(const[a,r]of this.detailElements){const l=this.rows.indexOf(a),u=this.expandedRows.has(a),p=l>=0&&o.has(l);if(!u||!p){const m=this.grid.__frameworkAdapter;if(m?.unmount){const E=r.querySelector(".master-detail-cell")?.firstElementChild;E&&m.unmount(E)}r.parentNode&&r.remove(),this.detailElements.delete(a)}}for(const[a,r]of o){const l=this.rows[a];if(!l||!this.expandedRows.has(l))continue;const u=this.detailElements.get(l);if(u){u.previousElementSibling!==r&&r.after(u);continue}const p=H(l,a,this.config.detailRenderer,c);typeof this.config.detailHeight=="number"&&(p.style.height=`${this.config.detailHeight}px`),r.after(p),this.detailElements.set(l,p);const m=this.rowsToAnimate.has(l);m&&this.rowsToAnimate.delete(l),m&&this.animateExpand(p,l,a)||requestAnimationFrame(()=>{this.#t(p,l,a)})}}getExtraHeight(){let e=0;for(const t of this.expandedRows)e+=this.getDetailHeight(t);return e}getExtraHeightBefore(e){let t=0;for(const i of this.expandedRows){const s=this.rows.indexOf(i);s>=0&&s<e&&(t+=this.getDetailHeight(i))}return t}getRowHeight(e,t){if(!this.expandedRows.has(e))return;const s=this.grid.defaultRowHeight??28,n=this.getDetailHeight(e);return s+n}adjustVirtualStart(e,t,i){if(this.expandedRows.size===0)return e;const s=this.grid?._virtualization?.positionCache;let n=e;if(s&&s.length>0)for(const c of this.expandedRows){const h=this.rows.indexOf(c);if(h<0||h>=e)continue;s[h].offset+s[h].height>t&&h<n&&(n=h)}else{const c=[];for(const d of this.expandedRows){const o=this.rows.indexOf(d);o>=0&&c.push({index:o,row:d})}c.sort((d,o)=>d.index-o.index);let h=0;for(const{index:d,row:o}of c){const a=d*i+h,r=this.getDetailHeight(o),l=a+i+r;h+=r,!(d>=e)&&l>t&&d<n&&(n=d)}}return n}expand(e){const t=this.rows[e];t&&(this.rowsToAnimate.add(t),this.expandedRows=v(this.expandedRows,t),this.requestRender())}collapse(e){const t=this.rows[e];t&&(this.expandedRows=y(this.expandedRows,t),this.requestRender())}toggle(e){const t=this.rows[e];t&&(this.expandedRows=R(this.expandedRows,t),this.expandedRows.has(t)&&this.rowsToAnimate.add(t),this.requestRender())}isExpanded(e){const t=this.rows[e];return t?D(this.expandedRows,t):!1}expandAll(){for(const e of this.rows)this.rowsToAnimate.add(e),this.expandedRows.add(e);this.requestRender()}collapseAll(){this.expandedRows.clear(),this.requestRender()}getExpandedRows(){const e=[];for(const t of this.expandedRows){const i=this.rows.indexOf(t);i>=0&&e.push(i)}return e}getDetailElement(e){const t=this.rows[e];return t?this.detailElements.get(t):void 0}refreshDetailRenderer(){const e=this.config.detailRenderer;if(this.config={...this.config,detailRenderer:void 0},this.parseLightDomDetail(),!this.config.detailRenderer&&e&&(this.config={...this.config,detailRenderer:e}),this.config.detailRenderer){const t=this.grid;typeof t.refreshColumns=="function"?t.refreshColumns():this.requestRender()}}}g.MasterDetailPlugin=b,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(g,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("../../core/internal/sanitize"),require("../../core/plugin/base-plugin"),require("../../core/plugin/expander-column")):typeof define=="function"&&define.amd?define(["exports","../../core/internal/sanitize","../../core/plugin/base-plugin","../../core/plugin/expander-column"],w):(g=typeof globalThis<"u"?globalThis:g||self,w(g.TbwGridPlugin_masterDetail={},g.TbwGrid,g.TbwGrid,g.TbwGrid))})(this,(function(g,w,A,x){"use strict";function R(f,e){const t=new Set(f);return t.has(e)?t.delete(e):t.add(e),t}function v(f,e){const t=new Set(f);return t.add(e),t}function y(f,e){const t=new Set(f);return t.delete(e),t}function D(f,e){return f.has(e)}function H(f,e,t,i){const s=document.createElement("div");s.className="master-detail-row",s.setAttribute("data-detail-for",String(e)),s.setAttribute("role","row");const n=document.createElement("div");n.className="master-detail-cell",n.setAttribute("role","cell"),n.style.gridColumn=`1 / ${i+1}`;const c=t(f,e);return typeof c=="string"?n.innerHTML=c:c instanceof HTMLElement&&n.appendChild(c),s.appendChild(n),s}const C="@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-right:none!important;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1 / 3}tbw-grid .master-detail-expander{display:flex;align-items:center;justify-content:center;width:100%;height:100%}tbw-grid .master-detail-toggle{cursor:pointer;opacity:.7;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center}tbw-grid .master-detail-toggle:hover{opacity:1}tbw-grid .master-detail-row{grid-column:1 / -1;display:grid;background:var(--tbw-master-detail-bg, var(--tbw-color-row-alt));border-bottom:1px solid var(--tbw-master-detail-border, var(--tbw-color-border));overflow:hidden}tbw-grid .master-detail-cell{padding:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));overflow:auto}tbw-grid .master-detail-row.tbw-expanding{animation:tbw-detail-expand var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .master-detail-row.tbw-collapsing{animation:tbw-detail-collapse var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-detail-expand{0%{opacity:0;max-height:0;padding-top:0;padding-bottom:0}to{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem);padding-top:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem));padding-bottom:var(--tbw-detail-padding, var(--tbw-spacing-xl, 1rem))}}@keyframes tbw-detail-collapse{0%{opacity:1;max-height:var(--tbw-detail-max-height, 31.25rem)}to{opacity:0;max-height:0}}}";class b extends A.BaseGridPlugin{name="masterDetail";styles=C;get defaultConfig(){return{detailHeight:"auto",expandOnRowClick:!1,collapseOnClickOutside:!1,animation:"slide"}}attach(e){super.attach(e),this.parseLightDomDetail()}parseLightDomDetail(){const e=this.grid;if(!e||typeof e.querySelector!="function")return;const t=e.querySelector("tbw-grid-detail");if(!t)return;const i=e;if(i.__frameworkAdapter?.parseDetailElement){const r=i.__frameworkAdapter.parseDetailElement(t);if(r){this.config={...this.config,detailRenderer:r};return}}const s=t.getAttribute("animation"),n=t.getAttribute("show-expand-column"),c=t.getAttribute("expand-on-row-click"),h=t.getAttribute("collapse-on-click-outside"),d=t.getAttribute("height"),o={};s!==null&&(o.animation=s==="false"?!1:s),n!==null&&(o.showExpandColumn=n!=="false"),c!==null&&(o.expandOnRowClick=c==="true"),h!==null&&(o.collapseOnClickOutside=h==="true"),d!==null&&(o.detailHeight=d==="auto"?"auto":parseInt(d,10));const a=t.innerHTML.trim();a&&!this.config.detailRenderer&&(o.detailRenderer=(r,l)=>{const u=w.evalTemplateString(a,{value:r,row:r});return w.sanitizeHTML(u)}),Object.keys(o).length>0&&(this.config={...this.config,...o})}get animationStyle(){return this.isAnimationEnabled?this.config.animation??"slide":!1}animateExpand(e,t,i){if(!this.isAnimationEnabled||this.animationStyle===!1)return!1;e.classList.add("tbw-expanding");let s=!1;const n=()=>{s||(s=!0,e.classList.remove("tbw-expanding"),t!==void 0&&i!==void 0&&this.#t(e,t,i))};return e.addEventListener("animationend",n,{once:!0}),setTimeout(n,this.animationDuration+50),!0}animateCollapse(e,t){if(!this.isAnimationEnabled||this.animationStyle===!1){t();return}e.classList.add("tbw-collapsing");const i=()=>{e.classList.remove("tbw-collapsing"),t()};e.addEventListener("animationend",i,{once:!0}),setTimeout(i,this.animationDuration+50)}#t(e,t,i){if(!e.isConnected)return;const s=e.offsetHeight;if(s>0){const n=this.measuredDetailHeights.get(t);this.measuredDetailHeights.set(t,s),n!==s&&this.grid.invalidateRowHeight(i)}}expandedRows=new Set;detailElements=new Map;measuredDetailHeights=new Map;rowsToAnimate=new Set;static DEFAULT_DETAIL_HEIGHT=150;getDetailHeight(e){const t=this.detailElements.get(e);if(t&&!(t.classList.contains("tbw-expanding")||t.classList.contains("tbw-collapsing"))){const n=t.offsetHeight;if(n>0)return this.measuredDetailHeights.set(e,n),n}const i=this.measuredDetailHeights.get(e);return i&&i>0?i:typeof this.config?.detailHeight=="number"?this.config.detailHeight:b.DEFAULT_DETAIL_HEIGHT}toggleAndEmit(e,t){this.expandedRows=R(this.expandedRows,e);const i=this.expandedRows.has(e);i&&this.rowsToAnimate.add(e),this.emit("detail-expand",{rowIndex:t,row:e,expanded:i}),this.requestRender()}detach(){this.expandedRows.clear(),this.detailElements.clear(),this.measuredDetailHeights.clear(),this.rowsToAnimate.clear()}processColumns(e){if(!(this.config.showExpandColumn===!0||this.config.showExpandColumn!==!1&&!!this.config.detailRenderer))return[...e];const i=[...e];if(x.findExpanderColumn(i))return i;const n=x.createExpanderColumnConfig(this.name);return n.viewRenderer=c=>{const{row:h}=c,d=this.expandedRows.has(h),o=document.createElement("span");o.className="master-detail-expander expander-cell";const a=document.createElement("span");return a.className=`master-detail-toggle${d?" expanded":""}`,this.setIcon(a,this.resolveIcon(d?"collapse":"expand")),a.setAttribute("role","button"),a.setAttribute("tabindex","0"),a.setAttribute("aria-expanded",String(d)),a.setAttribute("aria-label",d?"Collapse details":"Expand details"),o.appendChild(a),o},[n,...i]}onRowClick(e){if(!(!this.config.expandOnRowClick||!this.config.detailRenderer))return this.toggleAndEmit(e.row,e.rowIndex),!1}onCellClick(e){if(e.originalEvent?.target?.classList.contains("master-detail-toggle"))return this.toggleAndEmit(e.row,e.rowIndex),!0;this.expandedRows.size>0&&queueMicrotask(()=>this.#e())}onKeyDown(e){if(e.key!==" ")return;const t=this.grid._focusCol,i=this.grid._focusRow,s=this.visibleColumns[t];if(!s||!x.isExpanderColumn(s))return;const n=this.rows[i];if(n)return e.preventDefault(),this.toggleAndEmit(n,i),this.requestRenderWithFocus(),!0}afterRender(){this.#e()}onScrollRender(){!this.config.detailRenderer||this.expandedRows.size===0||this.#e()}#e(){if(!this.config.detailRenderer)return;const e=this.gridElement?.querySelector(".rows");if(!e)return;const t=this.grid,i=t._rowPool,s=t._virtualization?.start??0,n=t._virtualization?.end??0,c=this.columns.length,h=s,d=n,o=new Map;if(i){const a=Math.min(i.length,d-h);for(let r=0;r<a;r++){const l=i[r];l.parentNode===e&&o.set(h+r,l)}}else{const a=e.querySelectorAll(".data-grid-row");for(const r of a){const l=r.querySelector(".cell[data-row]"),u=l?parseInt(l.getAttribute("data-row")??"-1",10):-1;u>=0&&o.set(u,r)}}for(const[a,r]of this.detailElements){const l=this.rows.indexOf(a),u=this.expandedRows.has(a),p=l>=0&&o.has(l);if(!u||!p){const m=this.grid.__frameworkAdapter;if(m?.unmount){const E=r.querySelector(".master-detail-cell")?.firstElementChild;E&&m.unmount(E)}r.parentNode&&r.remove(),this.detailElements.delete(a)}}for(const[a,r]of o){const l=this.rows[a];if(!l||!this.expandedRows.has(l))continue;const u=this.detailElements.get(l);if(u){u.previousElementSibling!==r&&r.after(u);continue}const p=H(l,a,this.config.detailRenderer,c);typeof this.config.detailHeight=="number"&&(p.style.height=`${this.config.detailHeight}px`),r.after(p),this.detailElements.set(l,p);const m=this.rowsToAnimate.has(l);m&&this.rowsToAnimate.delete(l),m&&this.animateExpand(p,l,a)||requestAnimationFrame(()=>{this.#t(p,l,a)})}}getExtraHeight(){let e=0;for(const t of this.expandedRows)e+=this.getDetailHeight(t);return e}getExtraHeightBefore(e){let t=0;for(const i of this.expandedRows){const s=this.rows.indexOf(i);s>=0&&s<e&&(t+=this.getDetailHeight(i))}return t}getRowHeight(e,t){if(!this.expandedRows.has(e))return;const s=this.grid.defaultRowHeight??28,n=this.getDetailHeight(e);return s+n}adjustVirtualStart(e,t,i){if(this.expandedRows.size===0)return e;const s=this.grid?._virtualization?.positionCache;let n=e;if(s&&s.length>0)for(const c of this.expandedRows){const h=this.rows.indexOf(c);if(h<0||h>=e)continue;s[h].offset+s[h].height>t&&h<n&&(n=h)}else{const c=[];for(const d of this.expandedRows){const o=this.rows.indexOf(d);o>=0&&c.push({index:o,row:d})}c.sort((d,o)=>d.index-o.index);let h=0;for(const{index:d,row:o}of c){const a=d*i+h,r=this.getDetailHeight(o),l=a+i+r;h+=r,!(d>=e)&&l>t&&d<n&&(n=d)}}return n}expand(e){const t=this.rows[e];t&&(this.rowsToAnimate.add(t),this.expandedRows=v(this.expandedRows,t),this.requestRender())}collapse(e){const t=this.rows[e];t&&(this.expandedRows=y(this.expandedRows,t),this.requestRender())}toggle(e){const t=this.rows[e];t&&(this.expandedRows=R(this.expandedRows,t),this.expandedRows.has(t)&&this.rowsToAnimate.add(t),this.requestRender())}isExpanded(e){const t=this.rows[e];return t?D(this.expandedRows,t):!1}expandAll(){for(const e of this.rows)this.rowsToAnimate.add(e),this.expandedRows.add(e);this.requestRender()}collapseAll(){this.expandedRows.clear(),this.requestRender()}getExpandedRows(){const e=[];for(const t of this.expandedRows){const i=this.rows.indexOf(t);i>=0&&e.push(i)}return e}getDetailElement(e){const t=this.rows[e];return t?this.detailElements.get(t):void 0}refreshDetailRenderer(){const e=this.config.detailRenderer;if(this.config={...this.config,detailRenderer:void 0},this.parseLightDomDetail(),!this.config.detailRenderer&&e&&(this.config={...this.config,detailRenderer:e}),this.config.detailRenderer){const t=this.grid;typeof t.refreshColumns=="function"?t.refreshColumns():this.requestRender()}}}g.MasterDetailPlugin=b,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})}));
2
2
  //# sourceMappingURL=master-detail.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"master-detail.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/master-detail/master-detail.ts","../../../../../libs/grid/src/lib/plugins/master-detail/MasterDetailPlugin.ts"],"sourcesContent":["/**\n * Master/Detail Core Logic\n *\n * Pure functions for managing detail row expansion state.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// Uses `any` for maximum flexibility with user-defined row types.\n\n/**\n * Toggle the expansion state of a detail row.\n * Returns a new Set with the updated state.\n */\nexport function toggleDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n if (newExpanded.has(row)) {\n newExpanded.delete(row);\n } else {\n newExpanded.add(row);\n }\n return newExpanded;\n}\n\n/**\n * Expand a detail row.\n * Returns a new Set with the row added.\n */\nexport function expandDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n newExpanded.add(row);\n return newExpanded;\n}\n\n/**\n * Collapse a detail row.\n * Returns a new Set with the row removed.\n */\nexport function collapseDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n newExpanded.delete(row);\n return newExpanded;\n}\n\n/**\n * Check if a detail row is expanded.\n */\nexport function isDetailExpanded(expandedRows: Set<object>, row: object): boolean {\n return expandedRows.has(row);\n}\n\n/**\n * Create a detail element for a given row.\n * The element spans all columns and contains the rendered content.\n */\nexport function createDetailElement(\n row: any,\n rowIndex: number,\n renderer: (row: any, rowIndex: number) => HTMLElement | string,\n columnCount: number\n): HTMLElement {\n const detailRow = document.createElement('div');\n detailRow.className = 'master-detail-row';\n detailRow.setAttribute('data-detail-for', String(rowIndex));\n detailRow.setAttribute('role', 'row');\n\n const detailCell = document.createElement('div');\n detailCell.className = 'master-detail-cell';\n detailCell.setAttribute('role', 'cell');\n detailCell.style.gridColumn = `1 / ${columnCount + 1}`;\n\n const content = renderer(row, rowIndex);\n if (typeof content === 'string') {\n detailCell.innerHTML = content;\n } else if (content instanceof HTMLElement) {\n detailCell.appendChild(content);\n }\n\n detailRow.appendChild(detailCell);\n return detailRow;\n}\n","/**\n * Master/Detail Plugin (Class-based)\n *\n * Enables expandable detail rows showing additional content for each row.\n * Animation style is plugin-configured; respects grid-level animation.mode.\n */\n\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, CellClickEvent, GridElement, RowClickEvent } from '../../core/plugin/base-plugin';\nimport { createExpanderColumnConfig, findExpanderColumn, isExpanderColumn } from '../../core/plugin/expander-column';\nimport type { ColumnConfig } from '../../core/types';\nimport {\n collapseDetailRow,\n createDetailElement,\n expandDetailRow,\n isDetailExpanded,\n toggleDetailRow,\n} from './master-detail';\nimport styles from './master-detail.css?inline';\nimport type { DetailExpandDetail, ExpandCollapseAnimation, MasterDetailConfig } from './types';\n\n/**\n * Master-Detail Plugin for tbw-grid\n *\n * Creates expandable detail rows that reveal additional content beneath each master row.\n * Perfect for order/line-item UIs, employee/department views, or any scenario where\n * you need to show related data without navigating away.\n *\n * ## Installation\n *\n * ```ts\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `detailRenderer` | `(row) => HTMLElement \\| string` | required | Render function for detail content |\n * | `expandOnRowClick` | `boolean` | `false` | Expand when clicking the row |\n * | `detailHeight` | `number \\| 'auto'` | `'auto'` | Fixed height or auto-size |\n * | `collapseOnClickOutside` | `boolean` | `false` | Collapse when clicking outside |\n * | `showExpandColumn` | `boolean` | `true` | Show expand/collapse column |\n * | `animation` | `false \\| 'slide' \\| 'fade'` | `'slide'` | Animation style |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `expandRow` | `(rowIndex) => void` | Expand a specific row |\n * | `collapseRow` | `(rowIndex) => void` | Collapse a specific row |\n * | `toggleRow` | `(rowIndex) => void` | Toggle row expansion |\n * | `expandAll` | `() => void` | Expand all rows |\n * | `collapseAll` | `() => void` | Collapse all rows |\n * | `isRowExpanded` | `(rowIndex) => boolean` | Check if row is expanded |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-master-detail-bg` | `var(--tbw-color-row-alt)` | Detail row background |\n * | `--tbw-master-detail-border` | `var(--tbw-color-border)` | Detail row border |\n * | `--tbw-detail-padding` | `1em` | Detail content padding |\n * | `--tbw-animation-duration` | `200ms` | Expand/collapse animation |\n *\n * @example Basic Master-Detail with HTML Template\n * ```ts\n * import '@toolbox-web/grid';\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'orderId', header: 'Order ID' },\n * { field: 'customer', header: 'Customer' },\n * { field: 'total', header: 'Total', type: 'currency' },\n * ],\n * plugins: [\n * new MasterDetailPlugin({\n * detailRenderer: (row) => `\n * <div class=\"order-details\">\n * <h4>Order Items</h4>\n * <ul>${row.items.map(i => `<li>${i.name} - $${i.price}</li>`).join('')}</ul>\n * </div>\n * `,\n * }),\n * ],\n * };\n * ```\n *\n * @example Nested Grid in Detail\n * ```ts\n * new MasterDetailPlugin({\n * detailRenderer: (row) => {\n * const childGrid = document.createElement('tbw-grid');\n * childGrid.style.height = '200px';\n * childGrid.gridConfig = { columns: [...] };\n * childGrid.rows = row.items || [];\n * return childGrid;\n * },\n * })\n * ```\n *\n * @see {@link MasterDetailConfig} for all configuration options\n * @see {@link DetailExpandDetail} for expand/collapse event details\n *\n * @internal Extends BaseGridPlugin\n */\nexport class MasterDetailPlugin extends BaseGridPlugin<MasterDetailConfig> {\n /** @internal */\n readonly name = 'masterDetail';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<MasterDetailConfig> {\n return {\n detailHeight: 'auto',\n expandOnRowClick: false,\n collapseOnClickOutside: false,\n // Note: showExpandColumn is intentionally NOT defaulted here.\n // If undefined, processColumns() adds expander only when detailRenderer is provided.\n // Set to true for framework adapters that register renderers asynchronously.\n animation: 'slide', // Plugin's own default\n };\n }\n\n // #region Light DOM Parsing\n\n /**\n * Called when plugin is attached to the grid.\n * Parses light DOM for `<tbw-grid-detail>` elements to configure detail templates.\n * @internal\n */\n override attach(grid: GridElement): void {\n super.attach(grid);\n this.parseLightDomDetail();\n }\n\n /**\n * Parse `<tbw-grid-detail>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-detail>\n * <div class=\"detail-content\">\n * <p>Name: {{ row.name }}</p>\n * <p>Email: {{ row.email }}</p>\n * </div>\n * </tbw-grid-detail>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `animation`: 'slide' | 'fade' | 'false' (default: 'slide')\n * - `show-expand-column`: 'true' | 'false' (default: 'true')\n * - `expand-on-row-click`: 'true' | 'false' (default: 'false')\n * - `collapse-on-click-outside`: 'true' | 'false' (default: 'false')\n * - `height`: number (pixels) or 'auto' (default: 'auto')\n */\n private parseLightDomDetail(): void {\n const gridEl = this.grid as unknown as Element;\n if (!gridEl || typeof gridEl.querySelector !== 'function') return;\n\n const detailEl = gridEl.querySelector('tbw-grid-detail');\n if (!detailEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., Angular adapter intercepts for ng-template rendering)\n const gridWithAdapter = gridEl as unknown as {\n __frameworkAdapter?: {\n parseDetailElement?: (el: Element) => ((row: any, rowIndex: number) => HTMLElement | string) | undefined;\n };\n };\n if (gridWithAdapter.__frameworkAdapter?.parseDetailElement) {\n const adapterRenderer = gridWithAdapter.__frameworkAdapter.parseDetailElement(detailEl);\n if (adapterRenderer) {\n this.config = { ...this.config, detailRenderer: adapterRenderer };\n return;\n }\n }\n\n // Parse attributes for configuration\n const animation = detailEl.getAttribute('animation');\n const showExpandColumn = detailEl.getAttribute('show-expand-column');\n const expandOnRowClick = detailEl.getAttribute('expand-on-row-click');\n const collapseOnClickOutside = detailEl.getAttribute('collapse-on-click-outside');\n const heightAttr = detailEl.getAttribute('height');\n\n const configUpdates: Partial<MasterDetailConfig> = {};\n\n if (animation !== null) {\n configUpdates.animation = animation === 'false' ? false : (animation as 'slide' | 'fade');\n }\n if (showExpandColumn !== null) {\n configUpdates.showExpandColumn = showExpandColumn !== 'false';\n }\n if (expandOnRowClick !== null) {\n configUpdates.expandOnRowClick = expandOnRowClick === 'true';\n }\n if (collapseOnClickOutside !== null) {\n configUpdates.collapseOnClickOutside = collapseOnClickOutside === 'true';\n }\n if (heightAttr !== null) {\n configUpdates.detailHeight = heightAttr === 'auto' ? 'auto' : parseInt(heightAttr, 10);\n }\n\n // Get template content from innerHTML\n const templateHTML = detailEl.innerHTML.trim();\n if (templateHTML && !this.config.detailRenderer) {\n // Create a template-based renderer using the inner HTML\n configUpdates.detailRenderer = (row: any, _rowIndex: number): string => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row });\n // Sanitize the result to prevent XSS\n return sanitizeHTML(evaluated);\n };\n }\n\n // Merge updates into config\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n // #region Animation Helpers\n\n /**\n * Get expand/collapse animation style from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationStyle(): ExpandCollapseAnimation {\n if (!this.isAnimationEnabled) return false;\n return this.config.animation ?? 'slide';\n }\n\n /**\n * Apply expand animation to a detail element.\n * Returns true if animation was applied, false if skipped.\n * When animated, height measurement is deferred to animationend to avoid\n * measuring during the max-height: 0 CSS animation constraint.\n */\n private animateExpand(detailEl: HTMLElement, row?: any, rowIndex?: number): boolean {\n if (!this.isAnimationEnabled || this.animationStyle === false) return false;\n\n detailEl.classList.add('tbw-expanding');\n\n let measured = false;\n const measureOnce = () => {\n if (measured) return;\n measured = true;\n detailEl.classList.remove('tbw-expanding');\n\n // Measure height AFTER animation completes - the element now has its\n // natural height without the max-height constraint from the animation.\n if (row !== undefined && rowIndex !== undefined) {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n }\n };\n\n detailEl.addEventListener('animationend', measureOnce, { once: true });\n // Fallback timeout in case animationend doesn't fire (e.g., element detached,\n // animation removed, or framework rendering delays). Matches animateCollapse pattern.\n setTimeout(measureOnce, this.animationDuration + 50);\n return true;\n }\n\n /**\n * Apply collapse animation to a detail element and remove after animation.\n */\n private animateCollapse(detailEl: HTMLElement, onComplete: () => void): void {\n if (!this.isAnimationEnabled || this.animationStyle === false) {\n onComplete();\n return;\n }\n\n detailEl.classList.add('tbw-collapsing');\n const cleanup = () => {\n detailEl.classList.remove('tbw-collapsing');\n onComplete();\n };\n detailEl.addEventListener('animationend', cleanup, { once: true });\n // Fallback timeout in case animation doesn't fire\n setTimeout(cleanup, this.animationDuration + 50);\n }\n\n /**\n * Measure a detail element's height and update the position cache if it changed.\n * Used after layout settles (RAF) or after animation completes (animationend).\n */\n #measureAndCacheDetailHeight(detailEl: HTMLElement, row: any, rowIndex: number): void {\n if (!detailEl.isConnected) return;\n\n const height = detailEl.offsetHeight;\n if (height > 0) {\n const previousHeight = this.measuredDetailHeights.get(row);\n this.measuredDetailHeights.set(row, height);\n\n // Only invalidate if height actually changed\n // This triggers an incremental position cache update, not a full rebuild\n if (previousHeight !== height) {\n this.grid.invalidateRowHeight(rowIndex);\n }\n }\n }\n\n // #endregion\n\n // #region Internal State\n private expandedRows: Set<any> = new Set();\n private detailElements: Map<any, HTMLElement> = new Map();\n /** Cached measured heights - persists even when elements are virtualized out */\n private measuredDetailHeights: Map<any, number> = new Map();\n /** Rows that were just expanded by user action and should animate.\n * Prevents re-animation when rows scroll back into the virtual window. */\n private rowsToAnimate: Set<any> = new Set();\n\n /** Default height for detail rows when not configured */\n private static readonly DEFAULT_DETAIL_HEIGHT = 150;\n\n /**\n * Get the estimated height for a detail row.\n * Uses cached measured height when available (survives virtualization).\n * Avoids reading offsetHeight during CSS animations to prevent poisoning the cache.\n */\n private getDetailHeight(row: any): number {\n // Try DOM element first - works for tests and when element is connected\n const detailEl = this.detailElements.get(row);\n if (detailEl) {\n // Skip DOM measurement if currently animating (max-height constraint gives wrong value)\n const isAnimating = detailEl.classList.contains('tbw-expanding') || detailEl.classList.contains('tbw-collapsing');\n if (!isAnimating) {\n const height = detailEl.offsetHeight;\n if (height > 0) {\n // Cache the measurement for when this row is virtualized out\n this.measuredDetailHeights.set(row, height);\n return height;\n }\n }\n }\n\n // DOM element missing, detached, or animating - check cached measurement\n const cachedHeight = this.measuredDetailHeights.get(row);\n if (cachedHeight && cachedHeight > 0) {\n return cachedHeight;\n }\n\n // Fallback to config or default\n return typeof this.config?.detailHeight === 'number'\n ? this.config.detailHeight\n : MasterDetailPlugin.DEFAULT_DETAIL_HEIGHT;\n }\n\n /**\n * Toggle a row's detail and emit event.\n */\n private toggleAndEmit(row: any, rowIndex: number): void {\n this.expandedRows = toggleDetailRow(this.expandedRows, row as object);\n const expanded = this.expandedRows.has(row as object);\n if (expanded) {\n this.rowsToAnimate.add(row);\n }\n this.emit<DetailExpandDetail>('detail-expand', {\n rowIndex,\n row: row as Record<string, unknown>,\n expanded,\n });\n this.requestRender();\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.expandedRows.clear();\n this.detailElements.clear();\n this.measuredDetailHeights.clear();\n this.rowsToAnimate.clear();\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n // Determine whether to add the expander column:\n // 1. If showExpandColumn === false: never add (explicit opt-out)\n // 2. If showExpandColumn === true: always add (explicit opt-in, for framework adapters)\n // 3. If showExpandColumn is undefined: add only if detailRenderer is provided\n //\n // This supports React/Angular adapters which register renderers asynchronously via light DOM.\n // They must set showExpandColumn: true to get the column immediately, avoiding layout shift.\n const shouldAddExpander =\n this.config.showExpandColumn === true || (this.config.showExpandColumn !== false && !!this.config.detailRenderer);\n\n if (!shouldAddExpander) {\n return [...columns];\n }\n\n const cols = [...columns];\n\n // Check if expander column already exists (from this or another plugin)\n const existingExpander = findExpanderColumn(cols);\n if (existingExpander) {\n // Another plugin already added an expander column - don't add duplicate\n // Our expand logic will be handled via onCellClick on the expander column\n return cols;\n }\n\n // Create dedicated expander column that stays fixed at position 0\n const expanderCol = createExpanderColumnConfig(this.name);\n expanderCol.viewRenderer = (renderCtx) => {\n const { row } = renderCtx;\n const isExpanded = this.expandedRows.has(row as object);\n\n const container = document.createElement('span');\n container.className = 'master-detail-expander expander-cell';\n\n // Expand/collapse toggle icon\n const toggle = document.createElement('span');\n toggle.className = `master-detail-toggle${isExpanded ? ' expanded' : ''}`;\n // Use grid-level icons (fall back to defaults)\n this.setIcon(toggle, this.resolveIcon(isExpanded ? 'collapse' : 'expand'));\n // role=\"button\" is required for aria-expanded to be valid\n toggle.setAttribute('role', 'button');\n toggle.setAttribute('tabindex', '0');\n toggle.setAttribute('aria-expanded', String(isExpanded));\n toggle.setAttribute('aria-label', isExpanded ? 'Collapse details' : 'Expand details');\n container.appendChild(toggle);\n\n return container;\n };\n\n // Prepend expander column to ensure it's always first\n return [expanderCol, ...cols];\n }\n\n /** @internal */\n override onRowClick(event: RowClickEvent): boolean | void {\n if (!this.config.expandOnRowClick || !this.config.detailRenderer) return;\n this.toggleAndEmit(event.row, event.rowIndex);\n return false;\n }\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean | void {\n // Handle click on master-detail toggle icon (same pattern as TreePlugin)\n const target = event.originalEvent?.target as HTMLElement;\n if (target?.classList.contains('master-detail-toggle')) {\n this.toggleAndEmit(event.row, event.rowIndex);\n return true; // Prevent default handling\n }\n\n // Sync detail rows after cell click triggers refreshVirtualWindow\n // This runs in microtask to ensure DOM updates are complete\n if (this.expandedRows.size > 0) {\n queueMicrotask(() => this.#syncDetailRows());\n }\n return; // Don't prevent default\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when focus is on the expander column\n if (event.key !== ' ') return;\n\n const focusCol = this.grid._focusCol;\n const focusRow = this.grid._focusRow;\n const column = this.columns[focusCol];\n\n // Only handle SPACE on expander column\n if (!column || !isExpanderColumn(column)) return;\n\n const row = this.rows[focusRow];\n if (!row) return;\n\n event.preventDefault();\n this.toggleAndEmit(row, focusRow);\n\n // Restore focus styling after render completes via render pipeline\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n this.#syncDetailRows();\n }\n\n /**\n * Called on scroll to sync detail elements with visible rows.\n * Removes details for rows that scrolled out of view and reattaches for visible rows.\n * @internal\n */\n override onScrollRender(): void {\n if (!this.config.detailRenderer || this.expandedRows.size === 0) return;\n // Full sync needed on scroll to clean up orphaned details\n this.#syncDetailRows();\n }\n\n /**\n * Full sync of detail rows - cleans up stale elements and creates new ones.\n * Detail rows are inserted as siblings AFTER their master row to survive row rebuilds.\n *\n * PERF: Uses the grid's row pool (_rowPool) and virtual window (_virtualization.start/end)\n * to avoid querySelectorAll on every scroll frame. The pool is index-aligned with the\n * virtual window, so pool[i] corresponds to row index (start + i).\n */\n #syncDetailRows(): void {\n if (!this.config.detailRenderer) return;\n\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n // Use grid's virtualization state and row pool for O(1) lookups instead of querySelectorAll.\n // The row pool is an array of DOM elements aligned to the virtual window:\n // _rowPool[i] renders row data at index (_virtualization.start + i).\n const gridInternal = this.grid as any;\n const rowPool: HTMLElement[] | undefined = gridInternal._rowPool;\n const vStart: number = gridInternal._virtualization?.start ?? 0;\n const vEnd: number = gridInternal._virtualization?.end ?? 0;\n const columnCount = this.columns.length;\n\n // Build visible row index set from the virtual window range\n const visibleStart = vStart;\n const visibleEnd = vEnd;\n\n // Build a map of row index -> row element using the pool (O(n) where n = visible rows)\n const visibleRowMap = new Map<number, Element>();\n if (rowPool) {\n const poolLen = Math.min(rowPool.length, visibleEnd - visibleStart);\n for (let i = 0; i < poolLen; i++) {\n const rowEl = rowPool[i];\n if (rowEl.parentNode === body) {\n visibleRowMap.set(visibleStart + i, rowEl);\n }\n }\n } else {\n // Fallback: use querySelectorAll if pool is not accessible\n const dataRows = body.querySelectorAll('.data-grid-row');\n for (const rowEl of dataRows) {\n const firstCell = rowEl.querySelector('.cell[data-row]');\n const rowIndex = firstCell ? parseInt(firstCell.getAttribute('data-row') ?? '-1', 10) : -1;\n if (rowIndex >= 0) {\n visibleRowMap.set(rowIndex, rowEl);\n }\n }\n }\n\n // Remove detail rows whose parent row is no longer visible or no longer expanded.\n // Iterate the detailElements map (which we own) instead of querySelectorAll.\n for (const [row, detailEl] of this.detailElements) {\n const rowIndex = this.rows.indexOf(row);\n const isStillExpanded = this.expandedRows.has(row);\n const isRowVisible = rowIndex >= 0 && visibleRowMap.has(rowIndex);\n\n if (!isStillExpanded || !isRowVisible) {\n // Clean up framework adapter resources (React root, Vue app, Angular view)\n // before removing to prevent memory leaks.\n const adapter = (this.grid as unknown as { __frameworkAdapter?: { unmount?(c: HTMLElement): void } })\n .__frameworkAdapter;\n if (adapter?.unmount) {\n const detailCell = detailEl.querySelector('.master-detail-cell');\n const container = detailCell?.firstElementChild as HTMLElement | null;\n if (container) adapter.unmount(container);\n }\n if (detailEl.parentNode) detailEl.remove();\n this.detailElements.delete(row);\n }\n }\n\n // Insert detail rows for expanded rows that are visible\n for (const [rowIndex, rowEl] of visibleRowMap) {\n const row = this.rows[rowIndex];\n if (!row || !this.expandedRows.has(row)) continue;\n\n // Check if detail already exists for this row\n const existingDetail = this.detailElements.get(row);\n if (existingDetail) {\n // Ensure it's positioned correctly (as next sibling of row element)\n if (existingDetail.previousElementSibling !== rowEl) {\n rowEl.after(existingDetail);\n }\n continue;\n }\n\n // Create new detail element\n const detailEl = createDetailElement(row, rowIndex, this.config.detailRenderer, columnCount);\n\n if (typeof this.config.detailHeight === 'number') {\n detailEl.style.height = `${this.config.detailHeight}px`;\n }\n\n // Insert as sibling after the row element (not as child)\n rowEl.after(detailEl);\n this.detailElements.set(row, detailEl);\n\n // Only animate if this row was just expanded by a user action (click, keyboard, API).\n // Rows re-appearing from scroll (virtualization) should not re-animate.\n const shouldAnimate = this.rowsToAnimate.has(row);\n if (shouldAnimate) {\n this.rowsToAnimate.delete(row);\n }\n\n const willAnimate = shouldAnimate && this.animateExpand(detailEl, row, rowIndex);\n\n if (!willAnimate) {\n // No animation - measure height after layout settles via RAF\n requestAnimationFrame(() => {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n });\n }\n // When animating, measurement is deferred to animationend callback\n // (inside animateExpand) to avoid measuring during max-height: 0 constraint\n }\n }\n\n /**\n * Return total extra height from all expanded detail rows.\n * Used by grid virtualization to adjust scrollbar height.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v3.0.\n */\n override getExtraHeight(): number {\n let totalHeight = 0;\n for (const row of this.expandedRows) {\n totalHeight += this.getDetailHeight(row);\n }\n return totalHeight;\n }\n\n /**\n * Return extra height that appears before a given row index.\n * This is the sum of heights of all expanded details whose parent row is before the given index.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v3.0.\n */\n override getExtraHeightBefore(beforeRowIndex: number): number {\n let totalHeight = 0;\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n // Include detail if it's for a row before the given index\n if (rowIndex >= 0 && rowIndex < beforeRowIndex) {\n totalHeight += this.getDetailHeight(row);\n }\n }\n return totalHeight;\n }\n\n /**\n * Get the height of a specific row, including any expanded detail content.\n * Always returns a height to ensure the position cache uses plugin-controlled values\n * rather than stale DOM measurements.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels (base height for collapsed, base + detail for expanded)\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n const isExpanded = this.expandedRows.has(row as object);\n\n if (!isExpanded) {\n // Collapsed row - return undefined to let the grid use its measured/estimated height.\n // This ensures the position cache uses the correct row height from CSS/config.\n return undefined;\n }\n\n // Row is expanded - return base height plus detail height\n // Use grid's defaultRowHeight which reflects the actual measured/configured height\n const baseHeight = this.grid.defaultRowHeight ?? 28;\n const detailHeight = this.getDetailHeight(row);\n\n return baseHeight + detailHeight;\n }\n\n /**\n * Adjust the virtualization start index to keep expanded row visible while its detail is visible.\n * This ensures the detail scrolls smoothly out of view instead of disappearing abruptly.\n */\n override adjustVirtualStart(start: number, scrollTop: number, rowHeight: number): number {\n if (this.expandedRows.size === 0) return start;\n\n // Use position cache for accurate row positions when available (variable heights mode)\n const positionCache = (this.grid as any)?._virtualization?.positionCache as\n | Array<{ offset: number; height: number }>\n | undefined;\n\n let minStart = start;\n\n if (positionCache && positionCache.length > 0) {\n // Variable heights: use position cache for accurate offset\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex < 0 || rowIndex >= start) continue;\n\n // Position cache already includes cumulative heights from all expanded details\n const detailBottom = positionCache[rowIndex].offset + positionCache[rowIndex].height;\n\n if (detailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n } else {\n // Fixed heights fallback: accumulate detail heights manually\n // Build sorted list of expanded row indices for cumulative height calculation\n const expandedIndices: Array<{ index: number; row: any }> = [];\n for (const row of this.expandedRows) {\n const index = this.rows.indexOf(row);\n if (index >= 0) {\n expandedIndices.push({ index, row });\n }\n }\n expandedIndices.sort((a, b) => a.index - b.index);\n\n let cumulativeExtraHeight = 0;\n\n for (const { index: rowIndex, row } of expandedIndices) {\n const actualRowTop = rowIndex * rowHeight + cumulativeExtraHeight;\n const detailHeight = this.getDetailHeight(row);\n const actualDetailBottom = actualRowTop + rowHeight + detailHeight;\n\n cumulativeExtraHeight += detailHeight;\n\n if (rowIndex >= start) continue;\n\n if (actualDetailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n }\n\n return minStart;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Expand the detail row at the given index.\n * @param rowIndex - Index of the row to expand\n */\n expand(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.rowsToAnimate.add(row);\n this.expandedRows = expandDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Collapse the detail row at the given index.\n * @param rowIndex - Index of the row to collapse\n */\n collapse(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = collapseDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Toggle the detail row at the given index.\n * @param rowIndex - Index of the row to toggle\n */\n toggle(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = toggleDetailRow(this.expandedRows, row);\n if (this.expandedRows.has(row)) {\n this.rowsToAnimate.add(row);\n }\n this.requestRender();\n }\n }\n\n /**\n * Check if the detail row at the given index is expanded.\n * @param rowIndex - Index of the row to check\n * @returns Whether the detail row is expanded\n */\n isExpanded(rowIndex: number): boolean {\n const row = this.rows[rowIndex];\n return row ? isDetailExpanded(this.expandedRows, row) : false;\n }\n\n /**\n * Expand all detail rows.\n */\n expandAll(): void {\n for (const row of this.rows) {\n this.rowsToAnimate.add(row);\n this.expandedRows.add(row);\n }\n this.requestRender();\n }\n\n /**\n * Collapse all detail rows.\n */\n collapseAll(): void {\n this.expandedRows.clear();\n this.requestRender();\n }\n\n /**\n * Get the indices of all expanded rows.\n * @returns Array of row indices that are expanded\n */\n getExpandedRows(): number[] {\n const indices: number[] = [];\n for (const row of this.expandedRows) {\n const idx = this.rows.indexOf(row);\n if (idx >= 0) indices.push(idx);\n }\n return indices;\n }\n\n /**\n * Get the detail element for a specific row.\n * @param rowIndex - Index of the row\n * @returns The detail HTMLElement or undefined\n */\n getDetailElement(rowIndex: number): HTMLElement | undefined {\n const row = this.rows[rowIndex];\n return row ? this.detailElements.get(row) : undefined;\n }\n\n /**\n * Re-parse light DOM to refresh the detail renderer.\n * Call this after framework templates are registered (e.g., Angular ngAfterContentInit).\n *\n * This allows frameworks to register templates asynchronously and then\n * update the plugin's detailRenderer.\n */\n refreshDetailRenderer(): void {\n // Force re-parse by temporarily clearing the renderer\n const currentRenderer = this.config.detailRenderer;\n this.config = { ...this.config, detailRenderer: undefined };\n this.parseLightDomDetail();\n\n // If no new renderer was found, restore the original\n if (!this.config.detailRenderer && currentRenderer) {\n this.config = { ...this.config, detailRenderer: currentRenderer };\n }\n\n // Request a COLUMNS phase re-render so processColumns runs again with the new detailRenderer\n // This ensures the expand toggle is added to the first column.\n // Must use refreshColumns() (COLUMNS phase) not requestRender() (ROWS phase)\n // because processColumns only runs at COLUMNS phase or higher.\n if (this.config.detailRenderer) {\n const grid = this.grid as unknown as { refreshColumns?: () => void };\n if (typeof grid.refreshColumns === 'function') {\n grid.refreshColumns();\n } else {\n // Fallback to requestRender if refreshColumns not available\n this.requestRender();\n }\n }\n }\n // #endregion\n}\n"],"names":["toggleDetailRow","expandedRows","row","newExpanded","expandDetailRow","collapseDetailRow","isDetailExpanded","createDetailElement","rowIndex","renderer","columnCount","detailRow","detailCell","content","MasterDetailPlugin","BaseGridPlugin","styles","grid","gridEl","detailEl","gridWithAdapter","adapterRenderer","animation","showExpandColumn","expandOnRowClick","collapseOnClickOutside","heightAttr","configUpdates","templateHTML","_rowIndex","evaluated","evalTemplateString","sanitizeHTML","measured","measureOnce","#measureAndCacheDetailHeight","onComplete","cleanup","height","previousHeight","cachedHeight","expanded","columns","cols","findExpanderColumn","expanderCol","createExpanderColumnConfig","renderCtx","isExpanded","container","toggle","event","#syncDetailRows","focusCol","focusRow","column","isExpanderColumn","body","gridInternal","rowPool","vStart","vEnd","visibleStart","visibleEnd","visibleRowMap","poolLen","i","rowEl","dataRows","firstCell","isStillExpanded","isRowVisible","adapter","existingDetail","shouldAnimate","totalHeight","beforeRowIndex","_index","baseHeight","detailHeight","start","scrollTop","rowHeight","positionCache","minStart","expandedIndices","index","a","b","cumulativeExtraHeight","actualRowTop","actualDetailBottom","indices","idx","currentRenderer"],"mappings":"wfAaO,SAASA,EAAgBC,EAA2BC,EAA0B,CACnF,MAAMC,EAAc,IAAI,IAAIF,CAAY,EACxC,OAAIE,EAAY,IAAID,CAAG,EACrBC,EAAY,OAAOD,CAAG,EAEtBC,EAAY,IAAID,CAAG,EAEdC,CACT,CAMO,SAASC,EAAgBH,EAA2BC,EAA0B,CACnF,MAAMC,EAAc,IAAI,IAAIF,CAAY,EACxC,OAAAE,EAAY,IAAID,CAAG,EACZC,CACT,CAMO,SAASE,EAAkBJ,EAA2BC,EAA0B,CACrF,MAAMC,EAAc,IAAI,IAAIF,CAAY,EACxC,OAAAE,EAAY,OAAOD,CAAG,EACfC,CACT,CAKO,SAASG,EAAiB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AA,CACP,CAKA,aAAoB,CAClB,KAAK,aAAa,MAAA,EAClB,KAAK,cAAA,CACP,CAMA,iBAA4B,CAC1B,MAAM0F,EAAoB,CAAA,EAC1B,UAAW1F,KAAO,KAAK,aAAc,CACnC,MAAM2F,EAAM,KAAK,KAAK,QAAQ3F,CAAG,EAC7B2F,GAAO,GAAGD,EAAQ,KAAKC,CAAG,CAChC,CACA,OAAOD,CACT,CAOA,iBAAiBpF,EAA2C,CAC1D,MAAMN,EAAM,KAAK,KAAKM,CAAQ,EAC9B,OAAON,EAAM,KAAK,eAAe,IAAIA,CAAG,EAAI,MAC9C,CASA,uBAA8B,CAE5B,MAAM4F,EAAkB,KAAK,OAAO,eAapC,GAZA,KAAK,OAAS,CAAE,GAAG,KAAK,OAAQ,eAAgB,MAAA,EAChD,KAAK,oBAAA,EAGD,CAAC,KAAK,OAAO,gBAAkBA,IACjC,KAAK,OAAS,CAAE,GAAG,KAAK,OAAQ,eAAgBA,CAAA,GAO9C,KAAK,OAAO,eAAgB,CAC9B,MAAM7E,EAAO,KAAK,KACd,OAAOA,EAAK,gBAAmB,WACjCA,EAAK,eAAA,EAGL,KAAK,cAAA,CAET,CACF,CAEF"}
1
+ {"version":3,"file":"master-detail.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/master-detail/master-detail.ts","../../../../../libs/grid/src/lib/plugins/master-detail/MasterDetailPlugin.ts"],"sourcesContent":["/**\n * Master/Detail Core Logic\n *\n * Pure functions for managing detail row expansion state.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// Uses `any` for maximum flexibility with user-defined row types.\n\n/**\n * Toggle the expansion state of a detail row.\n * Returns a new Set with the updated state.\n */\nexport function toggleDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n if (newExpanded.has(row)) {\n newExpanded.delete(row);\n } else {\n newExpanded.add(row);\n }\n return newExpanded;\n}\n\n/**\n * Expand a detail row.\n * Returns a new Set with the row added.\n */\nexport function expandDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n newExpanded.add(row);\n return newExpanded;\n}\n\n/**\n * Collapse a detail row.\n * Returns a new Set with the row removed.\n */\nexport function collapseDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n newExpanded.delete(row);\n return newExpanded;\n}\n\n/**\n * Check if a detail row is expanded.\n */\nexport function isDetailExpanded(expandedRows: Set<object>, row: object): boolean {\n return expandedRows.has(row);\n}\n\n/**\n * Create a detail element for a given row.\n * The element spans all columns and contains the rendered content.\n */\nexport function createDetailElement(\n row: any,\n rowIndex: number,\n renderer: (row: any, rowIndex: number) => HTMLElement | string,\n columnCount: number\n): HTMLElement {\n const detailRow = document.createElement('div');\n detailRow.className = 'master-detail-row';\n detailRow.setAttribute('data-detail-for', String(rowIndex));\n detailRow.setAttribute('role', 'row');\n\n const detailCell = document.createElement('div');\n detailCell.className = 'master-detail-cell';\n detailCell.setAttribute('role', 'cell');\n detailCell.style.gridColumn = `1 / ${columnCount + 1}`;\n\n const content = renderer(row, rowIndex);\n if (typeof content === 'string') {\n detailCell.innerHTML = content;\n } else if (content instanceof HTMLElement) {\n detailCell.appendChild(content);\n }\n\n detailRow.appendChild(detailCell);\n return detailRow;\n}\n","/**\n * Master/Detail Plugin (Class-based)\n *\n * Enables expandable detail rows showing additional content for each row.\n * Animation style is plugin-configured; respects grid-level animation.mode.\n */\n\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, CellClickEvent, GridElement, RowClickEvent } from '../../core/plugin/base-plugin';\nimport { createExpanderColumnConfig, findExpanderColumn, isExpanderColumn } from '../../core/plugin/expander-column';\nimport type { ColumnConfig } from '../../core/types';\nimport {\n collapseDetailRow,\n createDetailElement,\n expandDetailRow,\n isDetailExpanded,\n toggleDetailRow,\n} from './master-detail';\nimport styles from './master-detail.css?inline';\nimport type { DetailExpandDetail, ExpandCollapseAnimation, MasterDetailConfig } from './types';\n\n/**\n * Master-Detail Plugin for tbw-grid\n *\n * Creates expandable detail rows that reveal additional content beneath each master row.\n * Perfect for order/line-item UIs, employee/department views, or any scenario where\n * you need to show related data without navigating away.\n *\n * ## Installation\n *\n * ```ts\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `detailRenderer` | `(row) => HTMLElement \\| string` | required | Render function for detail content |\n * | `expandOnRowClick` | `boolean` | `false` | Expand when clicking the row |\n * | `detailHeight` | `number \\| 'auto'` | `'auto'` | Fixed height or auto-size |\n * | `collapseOnClickOutside` | `boolean` | `false` | Collapse when clicking outside |\n * | `showExpandColumn` | `boolean` | `true` | Show expand/collapse column |\n * | `animation` | `false \\| 'slide' \\| 'fade'` | `'slide'` | Animation style |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `expandRow` | `(rowIndex) => void` | Expand a specific row |\n * | `collapseRow` | `(rowIndex) => void` | Collapse a specific row |\n * | `toggleRow` | `(rowIndex) => void` | Toggle row expansion |\n * | `expandAll` | `() => void` | Expand all rows |\n * | `collapseAll` | `() => void` | Collapse all rows |\n * | `isRowExpanded` | `(rowIndex) => boolean` | Check if row is expanded |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-master-detail-bg` | `var(--tbw-color-row-alt)` | Detail row background |\n * | `--tbw-master-detail-border` | `var(--tbw-color-border)` | Detail row border |\n * | `--tbw-detail-padding` | `1em` | Detail content padding |\n * | `--tbw-animation-duration` | `200ms` | Expand/collapse animation |\n *\n * @example Basic Master-Detail with HTML Template\n * ```ts\n * import '@toolbox-web/grid';\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'orderId', header: 'Order ID' },\n * { field: 'customer', header: 'Customer' },\n * { field: 'total', header: 'Total', type: 'currency' },\n * ],\n * plugins: [\n * new MasterDetailPlugin({\n * detailRenderer: (row) => `\n * <div class=\"order-details\">\n * <h4>Order Items</h4>\n * <ul>${row.items.map(i => `<li>${i.name} - $${i.price}</li>`).join('')}</ul>\n * </div>\n * `,\n * }),\n * ],\n * };\n * ```\n *\n * @example Nested Grid in Detail\n * ```ts\n * new MasterDetailPlugin({\n * detailRenderer: (row) => {\n * const childGrid = document.createElement('tbw-grid');\n * childGrid.style.height = '200px';\n * childGrid.gridConfig = { columns: [...] };\n * childGrid.rows = row.items || [];\n * return childGrid;\n * },\n * })\n * ```\n *\n * @see {@link MasterDetailConfig} for all configuration options\n * @see {@link DetailExpandDetail} for expand/collapse event details\n *\n * @internal Extends BaseGridPlugin\n */\nexport class MasterDetailPlugin extends BaseGridPlugin<MasterDetailConfig> {\n /** @internal */\n readonly name = 'masterDetail';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<MasterDetailConfig> {\n return {\n detailHeight: 'auto',\n expandOnRowClick: false,\n collapseOnClickOutside: false,\n // Note: showExpandColumn is intentionally NOT defaulted here.\n // If undefined, processColumns() adds expander only when detailRenderer is provided.\n // Set to true for framework adapters that register renderers asynchronously.\n animation: 'slide', // Plugin's own default\n };\n }\n\n // #region Light DOM Parsing\n\n /**\n * Called when plugin is attached to the grid.\n * Parses light DOM for `<tbw-grid-detail>` elements to configure detail templates.\n * @internal\n */\n override attach(grid: GridElement): void {\n super.attach(grid);\n this.parseLightDomDetail();\n }\n\n /**\n * Parse `<tbw-grid-detail>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-detail>\n * <div class=\"detail-content\">\n * <p>Name: {{ row.name }}</p>\n * <p>Email: {{ row.email }}</p>\n * </div>\n * </tbw-grid-detail>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `animation`: 'slide' | 'fade' | 'false' (default: 'slide')\n * - `show-expand-column`: 'true' | 'false' (default: 'true')\n * - `expand-on-row-click`: 'true' | 'false' (default: 'false')\n * - `collapse-on-click-outside`: 'true' | 'false' (default: 'false')\n * - `height`: number (pixels) or 'auto' (default: 'auto')\n */\n private parseLightDomDetail(): void {\n const gridEl = this.grid as unknown as Element;\n if (!gridEl || typeof gridEl.querySelector !== 'function') return;\n\n const detailEl = gridEl.querySelector('tbw-grid-detail');\n if (!detailEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., Angular adapter intercepts for ng-template rendering)\n const gridWithAdapter = gridEl as unknown as {\n __frameworkAdapter?: {\n parseDetailElement?: (el: Element) => ((row: any, rowIndex: number) => HTMLElement | string) | undefined;\n };\n };\n if (gridWithAdapter.__frameworkAdapter?.parseDetailElement) {\n const adapterRenderer = gridWithAdapter.__frameworkAdapter.parseDetailElement(detailEl);\n if (adapterRenderer) {\n this.config = { ...this.config, detailRenderer: adapterRenderer };\n return;\n }\n }\n\n // Parse attributes for configuration\n const animation = detailEl.getAttribute('animation');\n const showExpandColumn = detailEl.getAttribute('show-expand-column');\n const expandOnRowClick = detailEl.getAttribute('expand-on-row-click');\n const collapseOnClickOutside = detailEl.getAttribute('collapse-on-click-outside');\n const heightAttr = detailEl.getAttribute('height');\n\n const configUpdates: Partial<MasterDetailConfig> = {};\n\n if (animation !== null) {\n configUpdates.animation = animation === 'false' ? false : (animation as 'slide' | 'fade');\n }\n if (showExpandColumn !== null) {\n configUpdates.showExpandColumn = showExpandColumn !== 'false';\n }\n if (expandOnRowClick !== null) {\n configUpdates.expandOnRowClick = expandOnRowClick === 'true';\n }\n if (collapseOnClickOutside !== null) {\n configUpdates.collapseOnClickOutside = collapseOnClickOutside === 'true';\n }\n if (heightAttr !== null) {\n configUpdates.detailHeight = heightAttr === 'auto' ? 'auto' : parseInt(heightAttr, 10);\n }\n\n // Get template content from innerHTML\n const templateHTML = detailEl.innerHTML.trim();\n if (templateHTML && !this.config.detailRenderer) {\n // Create a template-based renderer using the inner HTML\n configUpdates.detailRenderer = (row: any, _rowIndex: number): string => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row });\n // Sanitize the result to prevent XSS\n return sanitizeHTML(evaluated);\n };\n }\n\n // Merge updates into config\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n // #region Animation Helpers\n\n /**\n * Get expand/collapse animation style from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationStyle(): ExpandCollapseAnimation {\n if (!this.isAnimationEnabled) return false;\n return this.config.animation ?? 'slide';\n }\n\n /**\n * Apply expand animation to a detail element.\n * Returns true if animation was applied, false if skipped.\n * When animated, height measurement is deferred to animationend to avoid\n * measuring during the max-height: 0 CSS animation constraint.\n */\n private animateExpand(detailEl: HTMLElement, row?: any, rowIndex?: number): boolean {\n if (!this.isAnimationEnabled || this.animationStyle === false) return false;\n\n detailEl.classList.add('tbw-expanding');\n\n let measured = false;\n const measureOnce = () => {\n if (measured) return;\n measured = true;\n detailEl.classList.remove('tbw-expanding');\n\n // Measure height AFTER animation completes - the element now has its\n // natural height without the max-height constraint from the animation.\n if (row !== undefined && rowIndex !== undefined) {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n }\n };\n\n detailEl.addEventListener('animationend', measureOnce, { once: true });\n // Fallback timeout in case animationend doesn't fire (e.g., element detached,\n // animation removed, or framework rendering delays). Matches animateCollapse pattern.\n setTimeout(measureOnce, this.animationDuration + 50);\n return true;\n }\n\n /**\n * Apply collapse animation to a detail element and remove after animation.\n */\n private animateCollapse(detailEl: HTMLElement, onComplete: () => void): void {\n if (!this.isAnimationEnabled || this.animationStyle === false) {\n onComplete();\n return;\n }\n\n detailEl.classList.add('tbw-collapsing');\n const cleanup = () => {\n detailEl.classList.remove('tbw-collapsing');\n onComplete();\n };\n detailEl.addEventListener('animationend', cleanup, { once: true });\n // Fallback timeout in case animation doesn't fire\n setTimeout(cleanup, this.animationDuration + 50);\n }\n\n /**\n * Measure a detail element's height and update the position cache if it changed.\n * Used after layout settles (RAF) or after animation completes (animationend).\n */\n #measureAndCacheDetailHeight(detailEl: HTMLElement, row: any, rowIndex: number): void {\n if (!detailEl.isConnected) return;\n\n const height = detailEl.offsetHeight;\n if (height > 0) {\n const previousHeight = this.measuredDetailHeights.get(row);\n this.measuredDetailHeights.set(row, height);\n\n // Only invalidate if height actually changed\n // This triggers an incremental position cache update, not a full rebuild\n if (previousHeight !== height) {\n this.grid.invalidateRowHeight(rowIndex);\n }\n }\n }\n\n // #endregion\n\n // #region Internal State\n private expandedRows: Set<any> = new Set();\n private detailElements: Map<any, HTMLElement> = new Map();\n /** Cached measured heights - persists even when elements are virtualized out */\n private measuredDetailHeights: Map<any, number> = new Map();\n /** Rows that were just expanded by user action and should animate.\n * Prevents re-animation when rows scroll back into the virtual window. */\n private rowsToAnimate: Set<any> = new Set();\n\n /** Default height for detail rows when not configured */\n private static readonly DEFAULT_DETAIL_HEIGHT = 150;\n\n /**\n * Get the estimated height for a detail row.\n * Uses cached measured height when available (survives virtualization).\n * Avoids reading offsetHeight during CSS animations to prevent poisoning the cache.\n */\n private getDetailHeight(row: any): number {\n // Try DOM element first - works for tests and when element is connected\n const detailEl = this.detailElements.get(row);\n if (detailEl) {\n // Skip DOM measurement if currently animating (max-height constraint gives wrong value)\n const isAnimating = detailEl.classList.contains('tbw-expanding') || detailEl.classList.contains('tbw-collapsing');\n if (!isAnimating) {\n const height = detailEl.offsetHeight;\n if (height > 0) {\n // Cache the measurement for when this row is virtualized out\n this.measuredDetailHeights.set(row, height);\n return height;\n }\n }\n }\n\n // DOM element missing, detached, or animating - check cached measurement\n const cachedHeight = this.measuredDetailHeights.get(row);\n if (cachedHeight && cachedHeight > 0) {\n return cachedHeight;\n }\n\n // Fallback to config or default\n return typeof this.config?.detailHeight === 'number'\n ? this.config.detailHeight\n : MasterDetailPlugin.DEFAULT_DETAIL_HEIGHT;\n }\n\n /**\n * Toggle a row's detail and emit event.\n */\n private toggleAndEmit(row: any, rowIndex: number): void {\n this.expandedRows = toggleDetailRow(this.expandedRows, row as object);\n const expanded = this.expandedRows.has(row as object);\n if (expanded) {\n this.rowsToAnimate.add(row);\n }\n this.emit<DetailExpandDetail>('detail-expand', {\n rowIndex,\n row: row as Record<string, unknown>,\n expanded,\n });\n this.requestRender();\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.expandedRows.clear();\n this.detailElements.clear();\n this.measuredDetailHeights.clear();\n this.rowsToAnimate.clear();\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n // Determine whether to add the expander column:\n // 1. If showExpandColumn === false: never add (explicit opt-out)\n // 2. If showExpandColumn === true: always add (explicit opt-in, for framework adapters)\n // 3. If showExpandColumn is undefined: add only if detailRenderer is provided\n //\n // This supports React/Angular adapters which register renderers asynchronously via light DOM.\n // They must set showExpandColumn: true to get the column immediately, avoiding layout shift.\n const shouldAddExpander =\n this.config.showExpandColumn === true || (this.config.showExpandColumn !== false && !!this.config.detailRenderer);\n\n if (!shouldAddExpander) {\n return [...columns];\n }\n\n const cols = [...columns];\n\n // Check if expander column already exists (from this or another plugin)\n const existingExpander = findExpanderColumn(cols);\n if (existingExpander) {\n // Another plugin already added an expander column - don't add duplicate\n // Our expand logic will be handled via onCellClick on the expander column\n return cols;\n }\n\n // Create dedicated expander column that stays fixed at position 0\n const expanderCol = createExpanderColumnConfig(this.name);\n expanderCol.viewRenderer = (renderCtx) => {\n const { row } = renderCtx;\n const isExpanded = this.expandedRows.has(row as object);\n\n const container = document.createElement('span');\n container.className = 'master-detail-expander expander-cell';\n\n // Expand/collapse toggle icon\n const toggle = document.createElement('span');\n toggle.className = `master-detail-toggle${isExpanded ? ' expanded' : ''}`;\n // Use grid-level icons (fall back to defaults)\n this.setIcon(toggle, this.resolveIcon(isExpanded ? 'collapse' : 'expand'));\n // role=\"button\" is required for aria-expanded to be valid\n toggle.setAttribute('role', 'button');\n toggle.setAttribute('tabindex', '0');\n toggle.setAttribute('aria-expanded', String(isExpanded));\n toggle.setAttribute('aria-label', isExpanded ? 'Collapse details' : 'Expand details');\n container.appendChild(toggle);\n\n return container;\n };\n\n // Prepend expander column to ensure it's always first\n return [expanderCol, ...cols];\n }\n\n /** @internal */\n override onRowClick(event: RowClickEvent): boolean | void {\n if (!this.config.expandOnRowClick || !this.config.detailRenderer) return;\n this.toggleAndEmit(event.row, event.rowIndex);\n return false;\n }\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean | void {\n // Handle click on master-detail toggle icon (same pattern as TreePlugin)\n const target = event.originalEvent?.target as HTMLElement;\n if (target?.classList.contains('master-detail-toggle')) {\n this.toggleAndEmit(event.row, event.rowIndex);\n return true; // Prevent default handling\n }\n\n // Sync detail rows after cell click triggers refreshVirtualWindow\n // This runs in microtask to ensure DOM updates are complete\n if (this.expandedRows.size > 0) {\n queueMicrotask(() => this.#syncDetailRows());\n }\n return; // Don't prevent default\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when focus is on the expander column\n if (event.key !== ' ') return;\n\n const focusCol = this.grid._focusCol;\n const focusRow = this.grid._focusRow;\n // _focusCol is a visible-column index (set from data-col), so use visibleColumns\n const column = this.visibleColumns[focusCol];\n\n // Only handle SPACE on expander column\n if (!column || !isExpanderColumn(column)) return;\n\n const row = this.rows[focusRow];\n if (!row) return;\n\n event.preventDefault();\n this.toggleAndEmit(row, focusRow);\n\n // Restore focus styling after render completes via render pipeline\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n this.#syncDetailRows();\n }\n\n /**\n * Called on scroll to sync detail elements with visible rows.\n * Removes details for rows that scrolled out of view and reattaches for visible rows.\n * @internal\n */\n override onScrollRender(): void {\n if (!this.config.detailRenderer || this.expandedRows.size === 0) return;\n // Full sync needed on scroll to clean up orphaned details\n this.#syncDetailRows();\n }\n\n /**\n * Full sync of detail rows - cleans up stale elements and creates new ones.\n * Detail rows are inserted as siblings AFTER their master row to survive row rebuilds.\n *\n * PERF: Uses the grid's row pool (_rowPool) and virtual window (_virtualization.start/end)\n * to avoid querySelectorAll on every scroll frame. The pool is index-aligned with the\n * virtual window, so pool[i] corresponds to row index (start + i).\n */\n #syncDetailRows(): void {\n if (!this.config.detailRenderer) return;\n\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n // Use grid's virtualization state and row pool for O(1) lookups instead of querySelectorAll.\n // The row pool is an array of DOM elements aligned to the virtual window:\n // _rowPool[i] renders row data at index (_virtualization.start + i).\n const gridInternal = this.grid as any;\n const rowPool: HTMLElement[] | undefined = gridInternal._rowPool;\n const vStart: number = gridInternal._virtualization?.start ?? 0;\n const vEnd: number = gridInternal._virtualization?.end ?? 0;\n const columnCount = this.columns.length;\n\n // Build visible row index set from the virtual window range\n const visibleStart = vStart;\n const visibleEnd = vEnd;\n\n // Build a map of row index -> row element using the pool (O(n) where n = visible rows)\n const visibleRowMap = new Map<number, Element>();\n if (rowPool) {\n const poolLen = Math.min(rowPool.length, visibleEnd - visibleStart);\n for (let i = 0; i < poolLen; i++) {\n const rowEl = rowPool[i];\n if (rowEl.parentNode === body) {\n visibleRowMap.set(visibleStart + i, rowEl);\n }\n }\n } else {\n // Fallback: use querySelectorAll if pool is not accessible\n const dataRows = body.querySelectorAll('.data-grid-row');\n for (const rowEl of dataRows) {\n const firstCell = rowEl.querySelector('.cell[data-row]');\n const rowIndex = firstCell ? parseInt(firstCell.getAttribute('data-row') ?? '-1', 10) : -1;\n if (rowIndex >= 0) {\n visibleRowMap.set(rowIndex, rowEl);\n }\n }\n }\n\n // Remove detail rows whose parent row is no longer visible or no longer expanded.\n // Iterate the detailElements map (which we own) instead of querySelectorAll.\n for (const [row, detailEl] of this.detailElements) {\n const rowIndex = this.rows.indexOf(row);\n const isStillExpanded = this.expandedRows.has(row);\n const isRowVisible = rowIndex >= 0 && visibleRowMap.has(rowIndex);\n\n if (!isStillExpanded || !isRowVisible) {\n // Clean up framework adapter resources (React root, Vue app, Angular view)\n // before removing to prevent memory leaks.\n const adapter = (this.grid as unknown as { __frameworkAdapter?: { unmount?(c: HTMLElement): void } })\n .__frameworkAdapter;\n if (adapter?.unmount) {\n const detailCell = detailEl.querySelector('.master-detail-cell');\n const container = detailCell?.firstElementChild as HTMLElement | null;\n if (container) adapter.unmount(container);\n }\n if (detailEl.parentNode) detailEl.remove();\n this.detailElements.delete(row);\n }\n }\n\n // Insert detail rows for expanded rows that are visible\n for (const [rowIndex, rowEl] of visibleRowMap) {\n const row = this.rows[rowIndex];\n if (!row || !this.expandedRows.has(row)) continue;\n\n // Check if detail already exists for this row\n const existingDetail = this.detailElements.get(row);\n if (existingDetail) {\n // Ensure it's positioned correctly (as next sibling of row element)\n if (existingDetail.previousElementSibling !== rowEl) {\n rowEl.after(existingDetail);\n }\n continue;\n }\n\n // Create new detail element\n const detailEl = createDetailElement(row, rowIndex, this.config.detailRenderer, columnCount);\n\n if (typeof this.config.detailHeight === 'number') {\n detailEl.style.height = `${this.config.detailHeight}px`;\n }\n\n // Insert as sibling after the row element (not as child)\n rowEl.after(detailEl);\n this.detailElements.set(row, detailEl);\n\n // Only animate if this row was just expanded by a user action (click, keyboard, API).\n // Rows re-appearing from scroll (virtualization) should not re-animate.\n const shouldAnimate = this.rowsToAnimate.has(row);\n if (shouldAnimate) {\n this.rowsToAnimate.delete(row);\n }\n\n const willAnimate = shouldAnimate && this.animateExpand(detailEl, row, rowIndex);\n\n if (!willAnimate) {\n // No animation - measure height after layout settles via RAF\n requestAnimationFrame(() => {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n });\n }\n // When animating, measurement is deferred to animationend callback\n // (inside animateExpand) to avoid measuring during max-height: 0 constraint\n }\n }\n\n /**\n * Return total extra height from all expanded detail rows.\n * Used by grid virtualization to adjust scrollbar height.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v3.0.\n */\n override getExtraHeight(): number {\n let totalHeight = 0;\n for (const row of this.expandedRows) {\n totalHeight += this.getDetailHeight(row);\n }\n return totalHeight;\n }\n\n /**\n * Return extra height that appears before a given row index.\n * This is the sum of heights of all expanded details whose parent row is before the given index.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v3.0.\n */\n override getExtraHeightBefore(beforeRowIndex: number): number {\n let totalHeight = 0;\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n // Include detail if it's for a row before the given index\n if (rowIndex >= 0 && rowIndex < beforeRowIndex) {\n totalHeight += this.getDetailHeight(row);\n }\n }\n return totalHeight;\n }\n\n /**\n * Get the height of a specific row, including any expanded detail content.\n * Always returns a height to ensure the position cache uses plugin-controlled values\n * rather than stale DOM measurements.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels (base height for collapsed, base + detail for expanded)\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n const isExpanded = this.expandedRows.has(row as object);\n\n if (!isExpanded) {\n // Collapsed row - return undefined to let the grid use its measured/estimated height.\n // This ensures the position cache uses the correct row height from CSS/config.\n return undefined;\n }\n\n // Row is expanded - return base height plus detail height\n // Use grid's defaultRowHeight which reflects the actual measured/configured height\n const baseHeight = this.grid.defaultRowHeight ?? 28;\n const detailHeight = this.getDetailHeight(row);\n\n return baseHeight + detailHeight;\n }\n\n /**\n * Adjust the virtualization start index to keep expanded row visible while its detail is visible.\n * This ensures the detail scrolls smoothly out of view instead of disappearing abruptly.\n */\n override adjustVirtualStart(start: number, scrollTop: number, rowHeight: number): number {\n if (this.expandedRows.size === 0) return start;\n\n // Use position cache for accurate row positions when available (variable heights mode)\n const positionCache = (this.grid as any)?._virtualization?.positionCache as\n | Array<{ offset: number; height: number }>\n | undefined;\n\n let minStart = start;\n\n if (positionCache && positionCache.length > 0) {\n // Variable heights: use position cache for accurate offset\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex < 0 || rowIndex >= start) continue;\n\n // Position cache already includes cumulative heights from all expanded details\n const detailBottom = positionCache[rowIndex].offset + positionCache[rowIndex].height;\n\n if (detailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n } else {\n // Fixed heights fallback: accumulate detail heights manually\n // Build sorted list of expanded row indices for cumulative height calculation\n const expandedIndices: Array<{ index: number; row: any }> = [];\n for (const row of this.expandedRows) {\n const index = this.rows.indexOf(row);\n if (index >= 0) {\n expandedIndices.push({ index, row });\n }\n }\n expandedIndices.sort((a, b) => a.index - b.index);\n\n let cumulativeExtraHeight = 0;\n\n for (const { index: rowIndex, row } of expandedIndices) {\n const actualRowTop = rowIndex * rowHeight + cumulativeExtraHeight;\n const detailHeight = this.getDetailHeight(row);\n const actualDetailBottom = actualRowTop + rowHeight + detailHeight;\n\n cumulativeExtraHeight += detailHeight;\n\n if (rowIndex >= start) continue;\n\n if (actualDetailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n }\n\n return minStart;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Expand the detail row at the given index.\n * @param rowIndex - Index of the row to expand\n */\n expand(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.rowsToAnimate.add(row);\n this.expandedRows = expandDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Collapse the detail row at the given index.\n * @param rowIndex - Index of the row to collapse\n */\n collapse(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = collapseDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Toggle the detail row at the given index.\n * @param rowIndex - Index of the row to toggle\n */\n toggle(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = toggleDetailRow(this.expandedRows, row);\n if (this.expandedRows.has(row)) {\n this.rowsToAnimate.add(row);\n }\n this.requestRender();\n }\n }\n\n /**\n * Check if the detail row at the given index is expanded.\n * @param rowIndex - Index of the row to check\n * @returns Whether the detail row is expanded\n */\n isExpanded(rowIndex: number): boolean {\n const row = this.rows[rowIndex];\n return row ? isDetailExpanded(this.expandedRows, row) : false;\n }\n\n /**\n * Expand all detail rows.\n */\n expandAll(): void {\n for (const row of this.rows) {\n this.rowsToAnimate.add(row);\n this.expandedRows.add(row);\n }\n this.requestRender();\n }\n\n /**\n * Collapse all detail rows.\n */\n collapseAll(): void {\n this.expandedRows.clear();\n this.requestRender();\n }\n\n /**\n * Get the indices of all expanded rows.\n * @returns Array of row indices that are expanded\n */\n getExpandedRows(): number[] {\n const indices: number[] = [];\n for (const row of this.expandedRows) {\n const idx = this.rows.indexOf(row);\n if (idx >= 0) indices.push(idx);\n }\n return indices;\n }\n\n /**\n * Get the detail element for a specific row.\n * @param rowIndex - Index of the row\n * @returns The detail HTMLElement or undefined\n */\n getDetailElement(rowIndex: number): HTMLElement | undefined {\n const row = this.rows[rowIndex];\n return row ? this.detailElements.get(row) : undefined;\n }\n\n /**\n * Re-parse light DOM to refresh the detail renderer.\n * Call this after framework templates are registered (e.g., Angular ngAfterContentInit).\n *\n * This allows frameworks to register templates asynchronously and then\n * update the plugin's detailRenderer.\n */\n refreshDetailRenderer(): void {\n // Force re-parse by temporarily clearing the renderer\n const currentRenderer = this.config.detailRenderer;\n this.config = { ...this.config, detailRenderer: undefined };\n this.parseLightDomDetail();\n\n // If no new renderer was found, restore the original\n if (!this.config.detailRenderer && currentRenderer) {\n this.config = { ...this.config, detailRenderer: currentRenderer };\n }\n\n // Request a COLUMNS phase re-render so processColumns runs again with the new detailRenderer\n // This ensures the expand toggle is added to the first column.\n // Must use refreshColumns() (COLUMNS phase) not requestRender() (ROWS phase)\n // because processColumns only runs at COLUMNS phase or higher.\n if (this.config.detailRenderer) {\n const grid = this.grid as unknown as { refreshColumns?: () => void };\n if (typeof grid.refreshColumns === 'function') {\n grid.refreshColumns();\n } else {\n // Fallback to requestRender if refreshColumns not available\n this.requestRender();\n }\n }\n }\n // #endregion\n}\n"],"names":["toggleDetailRow","expandedRows","row","newExpanded","expandDetailRow","collapseDetailRow","isDetailExpanded","createDetailElement","rowIndex","renderer","columnCount","detailRow","detailCell","content","MasterDetailPlugin","BaseGridPlugin","styles","grid","gridEl","detailEl","gridWithAdapter","adapterRenderer","animation","showExpandColumn","expandOnRowClick","collapseOnClickOutside","heightAttr","configUpdates","templateHTML","_rowIndex","evaluated","evalTemplateString","sanitizeHTML","measured","measureOnce","#measureAndCacheDetailHeight","onComplete","cleanup","height","previousHeight","cachedHeight","expanded","columns","cols","findExpanderColumn","expanderCol","createExpanderColumnConfig","renderCtx","isExpanded","container","toggle","event","#syncDetailRows","focusCol","focusRow","column","isExpanderColumn","body","gridInternal","rowPool","vStart","vEnd","visibleStart","visibleEnd","visibleRowMap","poolLen","i","rowEl","dataRows","firstCell","isStillExpanded","isRowVisible","adapter","existingDetail","shouldAnimate","totalHeight","beforeRowIndex","_index","baseHeight","detailHeight","start","scrollTop","rowHeight","positionCache","minStart","expandedIndices","index","a","b","cumulativeExtraHeight","actualRowTop","actualDetailBottom","indices","idx","currentRenderer"],"mappings":"wfAaO,SAASA,EAAgBC,EAA2BC,EAA0B,CACnF,MAAMC,EAAc,IAAI,IAAIF,CAAY,EACxC,OAAIE,EAAY,IAAID,CAAG,EACrBC,EAAY,OAAOD,CAAG,EAEtBC,EAAY,IAAID,CAAG,EAEdC,CACT,CAMO,SAASC,EAAgBH,EAA2BC,EAA0B,CACnF,MAAMC,EAAc,IAAI,IAAIF,CAAY,EACxC,OAAAE,EAAY,IAAID,CAAG,EACZC,CACT,CAMO,SAASE,EAAkBJ,EAA2BC,EAA0B,CACrF,MAAMC,EAAc,IAAI,IAAIF,CAAY,EACxC,OAAAE,EAAY,OAAOD,CAAG,EACfC,CACT,CAKO,SAASG,EAAiBL,EAA2BC,EAAsB,CAChF,OAAOD,EAAa,IAAIC,CAAG,CAC7B,CAMO,SAASK,EACdL,EACAM,EACAC,EACAC,EACa,CACb,MAAMC,EAAY,SAA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