@toolbox-web/grid 2.7.2 → 2.7.3

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.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/value-accessor"),require("../../core/plugin/base-plugin"),require("../../core/internal/diagnostics")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/value-accessor","../../core/plugin/base-plugin","../../core/internal/diagnostics"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_clipboard={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,n,o){"use strict";function i(e,t,n=!0){let o=e;if(n&&(o=o.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.utility)),t?.length){const e=new Set(t);o=o.filter(t=>e.has(t.field))}return o}function r(e,t){const n=t.delimiter??"\t",o=t.newline??"\n",i=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=[];let s=[],l="",a=!1;for(let c=0;c<i.length;c++){const e=i[c];'"'!==e||a?'"'===e&&a?'"'===i[c+1]?(l+='"',c++):a=!1:e!==n||a?e!==o||a?l+=e:(s.push(l),l="",(s.length>1||s.some(e=>""!==e.trim()))&&r.push(s),s=[]):(s.push(l),l=""):a=!0}return s.push(l),(s.length>1||s.some(e=>""!==e.trim()))&&r.push(s),r}function s(e,t){const{rows:n,target:o,fields:i}=e;if(!o)return;const r=t.rows,s=t.effectiveConfig.columns??[],l=s.map(e=>e.field),a=new Map;s.forEach(e=>{a.set(e.field,!0===e.editable)});const c=[...r],u=o.bounds?o.bounds.endRow:1/0;n.forEach((e,t)=>{const n=o.row+t;if(!(n>u)){if(o.bounds){if(n>=c.length)return}else for(;n>=c.length;){const e={};l.forEach(t=>e[t]=""),c.push(e)}c[n]={...c[n]},e.forEach((e,t)=>{const o=i[t];o&&a.get(o)&&(c[n][o]=e)})}}),t.rows=c}class l extends n.BaseGridPlugin{static manifest={queries:[{type:"clipboard:copy",description:"Triggers a copy operation and returns the copied text"}]};static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:"\t",newline:"\n",quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e),e.addEventListener("paste",e=>this.#e(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}handleQuery(e){if("clipboard:copy"===e.type)return this.copy(),!0}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#t(e.target),!0)}#t(e){const t=this.#n();if(t&&0===t.ranges.length){const t=this.#o(e);if(!t)return;const n=this.columns[t.col];if(!n)return;return void this.copy({rowIndices:[t.row],columns:[n.field]})}this.copy()}#e(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const n=r(t,this.config),o=this.#n(),i=o?.ranges?.[0],s=i?.from.row??0,l=i?.from.col??0,a=i&&("range"===o?.mode||"row"===o?.mode)&&(i.from.row!==i.to.row||i.from.col!==i.to.col)?{endRow:i.to.row,endCol:i.to.col}:null,c=a?.endCol??this.visibleColumns.length-1,u=this.visibleColumns[l],d=u?{row:s,col:l,field:u.field,bounds:a}:null,f=[],h=n[0]?.length??0;for(let r=0;r<h&&l+r<=c;r++){const e=this.visibleColumns[l+r];e&&f.push(e.field)}const p={rows:n,text:t,target:d,fields:f};this.emit("paste",p),this.#i(p)}#i(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??s)(e,this.grid)}#n(){const e=this.grid?.query("getSelection");return e?.[0]}#r(e){const t=this.#n();let n,o;if(e?.columns)n=i(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],o=Math.min(e.from.col,e.to.col),r=Math.max(e.from.col,e.to.col);n=i(this.visibleColumns.slice(o,r+1))}else n=i(this.columns);if(e?.rowIndices)o=function(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}(this.rows,e.rowIndices);else if(t?.ranges.length){const e=t.ranges[t.ranges.length-1],n=Math.min(e.from.row,e.to.row),i=Math.max(e.from.row,e.to.row);o=[];for(let t=n;t<=i;t++){const e=this.rows[t];e&&o.push(e)}}else o=this.rows;return{columns:n,rows:o}}#s(e,n,o){const i=o?.delimiter??this.config.delimiter??"\t",r=o?.newline??this.config.newline??"\n",s=o?.includeHeaders??this.config.includeHeaders??!1,l=o?.processCell??this.config.processCell,a=[];s&&a.push(e.map(e=>e.header||e.field).join(i));for(const c of n){const n=e.map(e=>{const n=t.resolveCellValue(c,e);return l?l(n,e.field,c):this.#l(e,n,c)});a.push(n.join(i))}return a.join(r)}#l(e,t,n){if(e.format)try{const o=e.format(t,n);return null==o?"":String(o)}catch{}if(e.renderer||e.viewRenderer){const t=this.#a(e.field,n);if(null!=t)return t}return function(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}(t)}#a(e,t){const n=this.gridElement;if(!n)return null;const o=this.rows.indexOf(t);if(-1===o)return null;const i=n.querySelector(`.cell[data-row="${o}"][data-field="${e}"]`);return i?i.textContent?.trim()??null:null}#o(e){const t=e.closest("[data-field-cache]");if(!t)return null;const n=t.dataset.fieldCache,o=t.dataset.row;if(!n||!o)return null;const i=parseInt(o,10);if(isNaN(i))return null;const r=this.columns.findIndex(e=>e.field===n);return-1===r?null:{row:i,col:r}}getSelectionAsText(e){const{columns:t,rows:n}=this.#r(e);return 0===t.length||0===n.length?"":this.#s(t,n,e)}async copy(e){const{columns:t,rows:n}=this.#r(e);if(0===t.length||0===n.length)return"";const i=this.#s(t,n,e);return await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){o.warnDiagnostic(o.CLIPBOARD_FAILED,`Clipboard API failed: ${t}`);const n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",n.style.pointerEvents="none",document.body.appendChild(n),n.select();const i=document.execCommand("copy");return document.body.removeChild(n),i}}(i),this.lastCopied={text:i,timestamp:Date.now()},this.emit("copy",{text:i,rowCount:n.length,columnCount:t.length}),i}async copyRows(e,t){return 0===e.length?"":this.copy({...t,rowIndices:e})}async paste(){const e=await async function(){try{return await navigator.clipboard.readText()}catch{return""}}();return e?r(e,this.config):null}getLastCopied(){return this.lastCopied}}e.ClipboardPlugin=l,e.defaultPasteHandler=s,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/value-accessor"),require("../../core/plugin/base-plugin"),require("../../core/internal/diagnostics")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/value-accessor","../../core/plugin/base-plugin","../../core/internal/diagnostics"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_clipboard={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,n,o){"use strict";function i(e,t,n=!0){let o=e;if(n&&(o=o.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.utility)),t?.length){const e=new Set(t);o=o.filter(t=>e.has(t.field))}return o}function r(e,t){const n=t.delimiter??"\t",o=t.newline??"\n",i=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=[];let s=[],l="",a=!1;for(let c=0;c<i.length;c++){const e=i[c];'"'!==e||a?'"'===e&&a?'"'===i[c+1]?(l+='"',c++):a=!1:e!==n||a?e!==o||a?l+=e:(s.push(l),l="",(s.length>1||s.some(e=>""!==e.trim()))&&r.push(s),s=[]):(s.push(l),l=""):a=!0}return s.push(l),(s.length>1||s.some(e=>""!==e.trim()))&&r.push(s),r}function s(e,t){const{rows:n,target:o,fields:i}=e;if(!o)return;const r=t.rows,s=t.effectiveConfig.columns??[],l=s.map(e=>e.field),a=new Map;s.forEach(e=>{a.set(e.field,!0===e.editable)});const c=[...r],u=o.bounds?o.bounds.endRow:1/0;n.forEach((e,t)=>{const n=o.row+t;if(!(n>u)){if(o.bounds){if(n>=c.length)return}else for(;n>=c.length;){const e={};l.forEach(t=>e[t]=""),c.push(e)}c[n]={...c[n]},e.forEach((e,t)=>{const o=i[t];o&&a.get(o)&&(c[n][o]=e)})}}),t.rows=c}class l extends n.BaseGridPlugin{static manifest={queries:[{type:"clipboard:copy",description:"Triggers a copy operation and returns the copied text"}]};static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:"\t",newline:"\n",quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e),e.addEventListener("paste",e=>this.#e(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}handleQuery(e){if("clipboard:copy"===e.type)return this.copy(),!0}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#t(e.target),!0)}#t(e){const t=this.#n();if(t&&0===t.ranges.length){const t=this.#o(e);if(!t)return;const n=this.columns[t.col];if(!n)return;return void this.copy({rowIndices:[t.row],columns:[n.field]})}this.copy()}#e(e){if(this.#i(e.target))return;const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const n=r(t,this.config),o=this.#n(),i=o?.ranges?.[0],s=i?.from.row??0,l=i?.from.col??0,a=i&&("range"===o?.mode||"row"===o?.mode)&&(i.from.row!==i.to.row||i.from.col!==i.to.col)?{endRow:i.to.row,endCol:i.to.col}:null,c=a?.endCol??this.visibleColumns.length-1,u=this.visibleColumns[l],d=u?{row:s,col:l,field:u.field,bounds:a}:null,f=[],h=n[0]?.length??0;for(let r=0;r<h&&l+r<=c;r++){const e=this.visibleColumns[l+r];e&&f.push(e.field)}const g={rows:n,text:t,target:d,fields:f};this.emit("paste",g),this.#r(g)}#r(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??s)(e,this.grid)}#i(e){return e instanceof Element&&!!e.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]')}#n(){const e=this.grid?.query("getSelection");return e?.[0]}#s(e){const t=this.#n();let n,o;if(e?.columns)n=i(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],o=Math.min(e.from.col,e.to.col),r=Math.max(e.from.col,e.to.col);n=i(this.visibleColumns.slice(o,r+1))}else n=i(this.columns);if(e?.rowIndices)o=function(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}(this.rows,e.rowIndices);else if(t?.ranges.length){const e=t.ranges[t.ranges.length-1],n=Math.min(e.from.row,e.to.row),i=Math.max(e.from.row,e.to.row);o=[];for(let t=n;t<=i;t++){const e=this.rows[t];e&&o.push(e)}}else o=this.rows;return{columns:n,rows:o}}#l(e,n,o){const i=o?.delimiter??this.config.delimiter??"\t",r=o?.newline??this.config.newline??"\n",s=o?.includeHeaders??this.config.includeHeaders??!1,l=o?.processCell??this.config.processCell,a=[];s&&a.push(e.map(e=>e.header||e.field).join(i));for(const c of n){const n=e.map(e=>{const n=t.resolveCellValue(c,e);return l?l(n,e.field,c):this.#a(e,n,c)});a.push(n.join(i))}return a.join(r)}#a(e,t,n){if(e.format)try{const o=e.format(t,n);return null==o?"":String(o)}catch{}if(e.renderer||e.viewRenderer){const t=this.#c(e.field,n);if(null!=t)return t}return function(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}(t)}#c(e,t){const n=this.gridElement;if(!n)return null;const o=this.rows.indexOf(t);if(-1===o)return null;const i=n.querySelector(`.cell[data-row="${o}"][data-field="${e}"]`);return i?i.textContent?.trim()??null:null}#o(e){const t=e.closest("[data-field-cache]");if(!t)return null;const n=t.dataset.fieldCache,o=t.dataset.row;if(!n||!o)return null;const i=parseInt(o,10);if(isNaN(i))return null;const r=this.columns.findIndex(e=>e.field===n);return-1===r?null:{row:i,col:r}}getSelectionAsText(e){const{columns:t,rows:n}=this.#s(e);return 0===t.length||0===n.length?"":this.#l(t,n,e)}async copy(e){const{columns:t,rows:n}=this.#s(e);if(0===t.length||0===n.length)return"";const i=this.#l(t,n,e);return await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){o.warnDiagnostic(o.CLIPBOARD_FAILED,`Clipboard API failed: ${t}`);const n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",n.style.pointerEvents="none",document.body.appendChild(n),n.select();const i=document.execCommand("copy");return document.body.removeChild(n),i}}(i),this.lastCopied={text:i,timestamp:Date.now()},this.emit("copy",{text:i,rowCount:n.length,columnCount:t.length}),i}async copyRows(e,t){return 0===e.length?"":this.copy({...t,rowIndices:e})}async paste(){const e=await async function(){try{return await navigator.clipboard.readText()}catch{return""}}();return e?r(e,this.config):null}getLastCopied(){return this.lastCopied}}e.ClipboardPlugin=l,e.defaultPasteHandler=s,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=clipboard.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../libs/grid/src/lib/plugins/clipboard/ClipboardPlugin.ts","../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts"],"sourcesContent":["/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n","/**\n * Clipboard Paste Logic\n *\n * Pure functions for reading and parsing clipboard data.\n */\n\nimport type { ClipboardConfig } from './types';\n\n/**\n * Parse clipboard text into a 2D array of cell values.\n *\n * Handles:\n * - Quoted values (with escaped double quotes \"\")\n * - Multi-line quoted values (newlines within quotes are preserved)\n * - Custom delimiters and newlines\n * - Empty lines (filtered out only if they contain no data)\n *\n * @param text - Raw clipboard text\n * @param config - Clipboard configuration\n * @returns 2D array where each sub-array is a row of cell values\n */\nexport function parseClipboardText(text: string, config: ClipboardConfig): string[][] {\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Handle Windows CRLF line endings\n const normalizedText = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n // Parse the entire text handling quoted fields that may span multiple lines\n const rows: string[][] = [];\n let currentRow: string[] = [];\n let currentCell = '';\n let inQuotes = false;\n\n for (let i = 0; i < normalizedText.length; i++) {\n const char = normalizedText[i];\n\n if (char === '\"' && !inQuotes) {\n // Start of quoted field\n inQuotes = true;\n } else if (char === '\"' && inQuotes) {\n // Check for escaped quote (\"\")\n if (normalizedText[i + 1] === '\"') {\n currentCell += '\"';\n i++; // Skip the second quote\n } else {\n // End of quoted field\n inQuotes = false;\n }\n } else if (char === delimiter && !inQuotes) {\n // Field separator\n currentRow.push(currentCell);\n currentCell = '';\n } else if (char === newline && !inQuotes) {\n // Row separator (only if not inside quotes)\n currentRow.push(currentCell);\n currentCell = '';\n // Only add non-empty rows (at least one non-empty cell or multiple cells)\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n currentRow = [];\n } else {\n currentCell += char;\n }\n }\n\n // Handle the last cell and row\n currentRow.push(currentCell);\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n\n return rows;\n}\n\n/**\n * Read text from the system clipboard.\n *\n * Uses the modern Clipboard API. Returns empty string if\n * the API is not available or permission is denied.\n *\n * @returns Promise resolving to clipboard text or empty string\n */\nexport async function readFromClipboard(): Promise<string> {\n try {\n return await navigator.clipboard.readText();\n } catch {\n // Permission denied or API not available\n return '';\n }\n}\n","/**\n * Clipboard Plugin Types\n *\n * Type definitions for clipboard copy/paste functionality.\n */\n\nimport type { GridElement } from '../../core/plugin/base-plugin';\n\n/**\n * Custom paste handler function.\n *\n * @param detail - The parsed paste data with target and field info\n * @param grid - The grid element to update\n * @returns `false` to prevent the default paste behavior, or `void`/`true` to allow it\n *\n * @example\n * ```ts\n * // Custom handler that validates before pasting\n * new ClipboardPlugin({\n * pasteHandler: (detail, grid) => {\n * if (!detail.target) return false;\n * // Apply custom validation/transformation...\n * applyPasteData(detail, grid);\n * return false; // We handled it, skip default\n * }\n * })\n * ```\n */\nexport type PasteHandler = (detail: PasteDetail, grid: GridElement) => boolean | void;\n\n/**\n * Options for programmatic copy operations.\n *\n * Allows callers to control exactly which columns and rows are included\n * in a copy, independently of the current selection state.\n *\n * @example Copy specific columns from selected rows\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * // User selected rows 0, 2, 4 via a dialog, chose columns to include\n * const text = await clipboard.copy({\n * rowIndices: [0, 2, 4],\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * ```\n */\nexport interface CopyOptions {\n /** Specific column fields to include. If omitted, uses current selection or all visible columns. */\n columns?: string[];\n /** Specific row indices to copy. If omitted, uses current selection or all rows. */\n rowIndices?: number[];\n /** Include column headers in copied text. Defaults to the plugin config value. */\n includeHeaders?: boolean;\n /** Column delimiter override. Defaults to the plugin config value. */\n delimiter?: string;\n /** Row delimiter override. Defaults to the plugin config value. */\n newline?: string;\n /** Custom cell value processor for this operation. Overrides the plugin config's `processCell`. */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n}\n\n/** Configuration options for the clipboard plugin */\nexport interface ClipboardConfig {\n /** Include column headers in copied text (default: false) */\n includeHeaders?: boolean;\n /** Column delimiter character (default: '\\t' for tab) */\n delimiter?: string;\n /** Row delimiter/newline character (default: '\\n') */\n newline?: string;\n /** Wrap string values with quotes (default: false) */\n quoteStrings?: boolean;\n /** Custom cell value processor for copy operations */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n /**\n * Custom paste handler. By default, the plugin applies pasted data to `grid.rows`\n * starting at the target cell.\n *\n * - Set to a custom function to handle paste yourself\n * - Set to `null` to disable auto-paste (event still fires)\n * - Return `false` from handler to prevent default behavior\n *\n * @default defaultPasteHandler (auto-applies paste data)\n */\n pasteHandler?: PasteHandler | null;\n}\n\n/** Internal state managed by the clipboard plugin */\nexport interface ClipboardState {\n /** The last copied text (for reference/debugging) */\n lastCopied: string | null;\n}\n\n/** Event detail emitted after a successful copy operation */\nexport interface CopyDetail {\n /** The text that was copied to clipboard */\n text: string;\n /** Number of rows copied */\n rowCount: number;\n /** Number of columns copied */\n columnCount: number;\n}\n\n/** Target cell coordinates and bounds for paste operations */\nexport interface PasteTarget {\n /** Target row index (top-left of paste area) */\n row: number;\n /** Target column index (top-left of paste area) */\n col: number;\n /** Target column field name (for easy data mapping) */\n field: string;\n /**\n * Selection bounds that constrain the paste area.\n * If set, paste data will be clipped to fit within these bounds.\n * If null, paste expands freely from the target cell.\n */\n bounds: {\n /** End row index (inclusive) */\n endRow: number;\n /** End column index (inclusive) */\n endCol: number;\n } | null;\n}\n\n/** Event detail emitted after a paste operation */\nexport interface PasteDetail {\n /** Parsed rows from clipboard (2D array of cell values) */\n rows: string[][];\n /** Raw text that was pasted */\n text: string;\n /** The target cell where paste starts (top-left of paste area). Null if no cell is selected. */\n target: PasteTarget | null;\n /**\n * Column fields for each column in the paste range, starting from target.col.\n * Useful for mapping parsed cell values to data fields.\n * Length matches the width of the pasted data (or available columns, whichever is smaller).\n */\n fields: string[];\n}\n\n/**\n * Default paste handler that applies pasted data to grid.rows.\n *\n * This is the built-in handler used when no custom `pasteHandler` is configured.\n * It clones the rows array for immutability and applies values starting at the target cell.\n *\n * Behavior:\n * - Single cell selection: paste expands freely, adds new rows if needed\n * - Range/row selection: paste is clipped to fit within selection bounds\n * - Non-editable columns: values are skipped (column alignment preserved)\n *\n * @param detail - The parsed paste data from clipboard\n * @param grid - The grid element to update\n */\nexport function defaultPasteHandler(detail: PasteDetail, grid: GridElement): void {\n const { rows: pastedRows, target, fields } = detail;\n\n // No target = nothing to do\n if (!target) return;\n\n // Get current rows and columns from grid\n const currentRows = grid.rows as Record<string, unknown>[];\n const columns = grid.effectiveConfig.columns ?? [];\n const allFields = columns.map((col) => col.field);\n\n // Build a map of field -> editable for quick lookup\n const editableMap = new Map<string, boolean>();\n columns.forEach((col) => {\n editableMap.set(col.field, col.editable === true);\n });\n\n // Clone data for immutability\n const newRows = [...currentRows];\n\n // Calculate row bounds\n const maxPasteRow = target.bounds ? target.bounds.endRow : Infinity;\n\n // Apply pasted data starting at target cell\n pastedRows.forEach((rowData, rowOffset) => {\n const targetRowIndex = target.row + rowOffset;\n\n // Stop if we've exceeded the selection bounds\n if (targetRowIndex > maxPasteRow) return;\n\n // Only grow array if no bounds (single cell selection)\n if (!target.bounds) {\n while (targetRowIndex >= newRows.length) {\n const emptyRow: Record<string, unknown> = {};\n allFields.forEach((field) => (emptyRow[field] = ''));\n newRows.push(emptyRow);\n }\n } else if (targetRowIndex >= newRows.length) {\n // With bounds, don't paste beyond existing rows\n return;\n }\n\n // Clone the target row and apply values\n newRows[targetRowIndex] = { ...newRows[targetRowIndex] };\n rowData.forEach((cellValue, colOffset) => {\n // fields array is already constrained by bounds in ClipboardPlugin\n const field = fields[colOffset];\n if (field && editableMap.get(field)) {\n // Only paste into editable columns\n newRows[targetRowIndex][field] = cellValue;\n }\n });\n });\n\n // Update grid with new data\n grid.rows = newRows;\n}\n\n// Module Augmentation - Register plugin name for type-safe getPluginByName()\ndeclare module '../../core/types' {\n interface DataGridEventMap {\n /** Fired after a successful copy operation. Provides the copied text, row count, and column count. @group Clipboard Events */\n 'copy': CopyDetail;\n /** Fired after a paste operation. Provides parsed rows, target cell, and column fields. @group Clipboard Events */\n 'paste': PasteDetail;\n }\n\n interface PluginNameMap {\n clipboard: import('./ClipboardPlugin').ClipboardPlugin;\n }\n}\n","/**\n * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport {\n BaseGridPlugin,\n type GridElement,\n type PluginDependency,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatValueAsText, resolveColumns, resolveRows } from '../shared/data-collection';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type CopyOptions,\n type PasteDetail,\n type PasteTarget,\n} from './types';\n\n/**\n * Clipboard Plugin for tbw-grid\n *\n * Brings familiar copy/cut/paste functionality with full keyboard shortcut support\n * (Ctrl+C, Ctrl+X, Ctrl+V). Handles single cells, multi-cell selections, and integrates\n * seamlessly with Excel and other spreadsheet applications via tab-delimited output.\n *\n * > **Optional Dependency:** Works best with SelectionPlugin for copying/pasting selected\n * > cells. Without SelectionPlugin, copies the entire grid and pastes at row 0, column 0.\n *\n * ## Installation\n *\n * ```ts\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * ```\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see SelectionPlugin for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin manifest — declares queries for inter-plugin communication.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [{ type: 'clipboard:copy', description: 'Triggers a copy operation and returns the copied text' }],\n };\n\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n grid.addEventListener('paste', (e) => this.#handleNativePaste(e), {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'clipboard:copy') {\n this.copy();\n return true;\n }\n return undefined;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n // Prevent the browser's default copy action so it doesn't overwrite\n // our clipboard write with whatever text is selected in the DOM.\n event.preventDefault();\n this.#handleCopy(event.target as HTMLElement);\n return true;\n }\n\n // For paste, we do NOT return true - let the native paste event fire\n // so we can access clipboardData synchronously in #handleNativePaste\n return false;\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Handle copy operation from keyboard shortcut.\n *\n * For keyboard-triggered copies, respects the current selection or\n * falls back to the focused cell from the DOM.\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n\n // Selection plugin exists but nothing selected → try focused cell from DOM\n if (selection && selection.ranges.length === 0) {\n const focused = this.#getFocusedCellFromDOM(target);\n if (!focused) return;\n const col = this.columns[focused.col];\n if (!col) return;\n this.copy({ rowIndices: [focused.row], columns: [col.field] });\n return;\n }\n\n // Delegate to the public copy() method (selection or full grid)\n this.copy();\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection via query\n const selection = this.#getSelection();\n const firstRange = selection?.ranges?.[0];\n\n // Determine target cell and bounds\n const targetRow = firstRange?.from.row ?? 0;\n const targetCol = firstRange?.from.col ?? 0;\n\n // Check if multi-cell selection (range with different start/end)\n const isMultiCell =\n firstRange &&\n (selection?.mode === 'range' || selection?.mode === 'row') &&\n (firstRange.from.row !== firstRange.to.row || firstRange.from.col !== firstRange.to.col);\n\n const bounds = isMultiCell ? { endRow: firstRange.to.row, endCol: firstRange.to.col } : null;\n // Selection range indices are visible-column indices (from data-col)\n const maxCol = bounds?.endCol ?? this.visibleColumns.length - 1;\n\n // Build target info\n const column = this.visibleColumns[targetCol];\n const target: PasteTarget | null = column ? { row: targetRow, col: targetCol, field: column.field, bounds } : null;\n\n // Build field list for paste width (constrained by bounds if set)\n const fields: string[] = [];\n const pasteWidth = parsed[0]?.length ?? 0;\n for (let i = 0; i < pasteWidth && targetCol + i <= maxCol; i++) {\n const col = this.visibleColumns[targetCol + i];\n if (col) {\n fields.push(col.field);\n }\n }\n\n const detail: PasteDetail = { rows: parsed, text, target, fields };\n\n // Emit the event for any listeners\n this.emit<PasteDetail>('paste', detail);\n\n // Apply paste data using the configured handler (or default)\n this.#applyPasteHandler(detail);\n }\n\n /**\n * Apply the paste handler to update grid data.\n *\n * Uses the configured `pasteHandler`, or the default handler if not specified.\n * Set `pasteHandler: null` in config to disable auto-paste.\n */\n #applyPasteHandler(detail: PasteDetail): void {\n if (!this.grid) return;\n\n const { pasteHandler } = this.config;\n\n // pasteHandler: null means explicitly disabled\n if (pasteHandler === null) return;\n\n // Use custom handler or default\n const handler = pasteHandler ?? defaultPasteHandler;\n handler(detail, this.grid);\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection');\n return responses?.[0];\n }\n\n /**\n * Resolve columns and rows to include based on options and/or current selection.\n *\n * Priority for columns:\n * 1. `options.columns` (explicit field list)\n * 2. Selection range column bounds (range/cell mode only)\n * 3. All visible non-utility columns\n *\n * Priority for rows:\n * 1. `options.rowIndices` (explicit indices)\n * 2. Selection range row bounds\n * 3. All rows\n */\n #resolveData(options?: CopyOptions): { columns: ColumnConfig[]; rows: Record<string, unknown>[] } {\n const selection = this.#getSelection();\n\n // --- Columns ---\n let columns: ColumnConfig[];\n if (options?.columns) {\n // Caller specified exact fields\n columns = resolveColumns(this.columns, options.columns);\n } else if (selection?.ranges.length && selection.mode !== 'row') {\n // Range/cell selection: restrict to selection column bounds\n // Selection indices are visible-column indices (from data-col)\n const range = selection.ranges[selection.ranges.length - 1];\n const minCol = Math.min(range.from.col, range.to.col);\n const maxCol = Math.max(range.from.col, range.to.col);\n columns = resolveColumns(this.visibleColumns.slice(minCol, maxCol + 1));\n } else {\n // Row selection or no selection: all visible columns\n columns = resolveColumns(this.columns);\n }\n\n // --- Rows ---\n let rows: Record<string, unknown>[];\n if (options?.rowIndices) {\n // Caller specified exact row indices\n rows = resolveRows(this.rows as Record<string, unknown>[], options.rowIndices);\n } else if (selection?.ranges.length) {\n // Selection range: extract contiguous row range\n const range = selection.ranges[selection.ranges.length - 1];\n const minRow = Math.min(range.from.row, range.to.row);\n const maxRow = Math.max(range.from.row, range.to.row);\n rows = [];\n for (let r = minRow; r <= maxRow; r++) {\n const row = this.rows[r] as Record<string, unknown> | undefined;\n if (row) rows.push(row);\n }\n } else {\n // No selection: all rows\n rows = this.rows as Record<string, unknown>[];\n }\n\n return { columns, rows };\n }\n\n /**\n * Build delimited text from resolved columns and rows.\n *\n * When no `processCell` callback is configured, uses \"copy what you see\" logic:\n * 1. Column `format` function (includes typeDefaults merged at config time)\n * 2. DOM cell textContent for columns with custom renderers (visible rows only)\n * 3. Raw value via `formatValueAsText` as final fallback\n */\n #buildText(columns: ColumnConfig[], rows: Record<string, unknown>[], options?: CopyOptions): string {\n const delimiter = options?.delimiter ?? this.config.delimiter ?? '\\t';\n const newline = options?.newline ?? this.config.newline ?? '\\n';\n const includeHeaders = options?.includeHeaders ?? this.config.includeHeaders ?? false;\n const processCell = options?.processCell ?? this.config.processCell;\n\n const lines: string[] = [];\n\n // Header row\n if (includeHeaders) {\n lines.push(columns.map((c) => c.header || c.field).join(delimiter));\n }\n\n // Data rows\n for (const row of rows) {\n const cells = columns.map((col) => {\n const value = resolveCellValue(row, col);\n if (processCell) return processCell(value, col.field, row);\n return this.#formatCellAsDisplayed(col, value, row);\n });\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n }\n\n /**\n * Format a cell value the way the grid displays it.\n *\n * Priority:\n * 1. Column `format` function (includes typeDefaults applied at config merge time)\n * 2. DOM textContent for columns with a custom renderer (virtualized rows only)\n * 3. Raw value via `formatValueAsText`\n */\n #formatCellAsDisplayed(col: ColumnConfig, value: unknown, row: Record<string, unknown>): string {\n // 1. Column format function (covers col.format and typeDefaults)\n if (col.format) {\n try {\n const formatted = col.format(value, row);\n return formatted == null ? '' : String(formatted);\n } catch {\n // Format failed — fall through to next strategy\n }\n }\n\n // 2. DOM textContent for columns with custom renderers\n if (col.renderer || col.viewRenderer) {\n const text = this.#readCellTextFromDOM(col.field, row);\n if (text != null) return text;\n }\n\n // 3. Fallback to raw value formatting\n return formatValueAsText(value);\n }\n\n /**\n * Try to read a cell's displayed text from the DOM.\n *\n * Only works for rows currently rendered in the virtualized viewport.\n * Returns `null` if the row is not in the DOM (caller should fall back).\n */\n #readCellTextFromDOM(field: string, row: Record<string, unknown>): string | null {\n const host = this.gridElement;\n if (!host) return null;\n\n // Find the row index in the grid's current row array\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex === -1) return null;\n\n // Query the rendered cell by row index and field name\n const cell = host.querySelector<HTMLElement>(`.cell[data-row=\"${rowIndex}\"][data-field=\"${field}\"]`);\n if (!cell) return null;\n\n return cell.textContent?.trim() ?? null;\n }\n\n /**\n * Get focused cell coordinates from DOM.\n * Used as fallback when SelectionPlugin has no selection.\n */\n #getFocusedCellFromDOM(target: HTMLElement): { row: number; col: number } | null {\n const cell = target.closest('[data-field-cache]') as HTMLElement | null;\n if (!cell) return null;\n\n const field = cell.dataset.fieldCache;\n const rowIndexStr = cell.dataset.row;\n if (!field || !rowIndexStr) return null;\n\n const row = parseInt(rowIndexStr, 10);\n if (isNaN(row)) return null;\n\n const col = this.columns.findIndex((c) => c.field === field);\n if (col === -1) return null;\n\n return { row, col };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the text representation of the current selection (or specified data)\n * without writing to the system clipboard.\n *\n * Useful for previewing what would be copied, or for feeding the text into\n * a custom UI (e.g., a \"copy with column picker\" dialog).\n *\n * @param options - Control which columns/rows to include\n * @returns Delimited text, or empty string if nothing to copy\n *\n * @example Get text for specific columns\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * const text = clipboard.getSelectionAsText({\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * console.log(text);\n * // \"Name\\tEmail\\nAlice\\talice@example.com\\n...\"\n * ```\n */\n getSelectionAsText(options?: CopyOptions): string {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) return '';\n return this.#buildText(columns, rows, options);\n }\n\n /**\n * Copy data to the system clipboard.\n *\n * Without options, copies the current selection (or entire grid if no selection).\n * With options, copies exactly the specified columns and/or rows — ideal for\n * \"copy with column picker\" workflows where the user selects rows first,\n * then chooses which columns to include via a dialog.\n *\n * @param options - Control which columns/rows to include\n * @returns The copied text\n *\n * @example Copy current selection (default)\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * await clipboard.copy();\n * ```\n *\n * @example Copy specific columns from specific rows\n * ```ts\n * // User selected rows in the grid, then picked columns in a dialog\n * const selectedRowIndices = [0, 3, 7];\n * const chosenColumns = ['name', 'department', 'salary'];\n * await clipboard.copy({\n * rowIndices: selectedRowIndices,\n * columns: chosenColumns,\n * includeHeaders: true,\n * });\n * ```\n */\n async copy(options?: CopyOptions): Promise<string> {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) {\n return '';\n }\n\n const text = this.#buildText(columns, rows, options);\n await copyToClipboard(text);\n this.lastCopied = { text, timestamp: Date.now() };\n this.emit<CopyDetail>('copy', {\n text,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n return text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n *\n * Convenience wrapper around {@link copy} for row-based workflows.\n * Supports non-contiguous row indices (e.g., `[0, 3, 7]`).\n *\n * @param indices - Array of row indices to copy\n * @param options - Additional copy options (columns, headers, etc.)\n * @returns The copied text\n *\n * @example\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * // Copy only rows 0 and 5, including just name and email columns\n * await clipboard.copyRows([0, 5], { columns: ['name', 'email'] });\n * ```\n */\n async copyRows(indices: number[], options?: Omit<CopyOptions, 'rowIndices'>): Promise<string> {\n if (indices.length === 0) return '';\n return this.copy({ ...options, rowIndices: indices });\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, CopyOptions, PasteDetail } from './types';\n","/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport { CLIPBOARD_FAILED, warnDiagnostic } from '../../core/internal/diagnostics';\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport type { ColumnConfig } from '../../core/types';\nimport type { ClipboardConfig } from './types';\n\n/** Parameters for building clipboard text */\nexport interface CopyParams {\n /** All grid rows */\n rows: unknown[];\n /** Column configurations */\n columns: ColumnConfig[];\n /** Selected row indices */\n selectedIndices: Set<number> | number[];\n /** Clipboard configuration */\n config: ClipboardConfig;\n}\n\n/**\n * Format a cell value for clipboard output.\n *\n * Uses custom processCell if provided, otherwise applies default formatting:\n * - null/undefined → empty string\n * - Date → ISO string\n * - Object → JSON string\n * - Other → String conversion with optional quoting\n *\n * @param value - The cell value to format\n * @param field - The field name\n * @param row - The full row object\n * @param config - Clipboard configuration\n * @returns Formatted string value\n */\nexport function formatCellValue(value: unknown, field: string, row: unknown, config: ClipboardConfig): string {\n if (config.processCell) {\n return config.processCell(value, field, row);\n }\n\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n\n const str = String(value);\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Quote if contains delimiter, newline, or quotes (or if quoteStrings is enabled)\n if (config.quoteStrings || str.includes(delimiter) || str.includes(newline) || str.includes('\"')) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build clipboard text from selected rows and columns.\n *\n * @param params - Copy parameters including rows, columns, selection, and config\n * @returns Tab-separated (or custom delimiter) text ready for clipboard\n */\nexport function buildClipboardText(params: CopyParams): string {\n const { rows, columns, selectedIndices, config } = params;\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Filter to visible columns (not hidden, not internal __ prefixed)\n const visibleColumns = columns.filter((c) => !c.hidden && !c.field.startsWith('__'));\n\n const lines: string[] = [];\n\n // Add header row if configured\n if (config.includeHeaders) {\n const headerCells = visibleColumns.map((c) => {\n const header = c.header || c.field;\n // Quote headers if they contain special characters\n if (header.includes(delimiter) || header.includes(newline) || header.includes('\"')) {\n return `\"${header.replace(/\"/g, '\"\"')}\"`;\n }\n return header;\n });\n lines.push(headerCells.join(delimiter));\n }\n\n // Convert indices to sorted array\n const indices = selectedIndices instanceof Set ? [...selectedIndices] : selectedIndices;\n const sortedIndices = [...indices].sort((a, b) => a - b);\n\n // Build data rows\n for (const idx of sortedIndices) {\n const row = rows[idx];\n if (!row) continue;\n\n const cells = visibleColumns.map((col) => formatCellValue(resolveCellValue(row, col), col.field, row, config));\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n}\n\n/**\n * Copy text to the system clipboard.\n *\n * Uses the modern Clipboard API when available, with fallback\n * to execCommand for older browsers.\n *\n * @param text - The text to copy\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch (err) {\n warnDiagnostic(CLIPBOARD_FAILED, `Clipboard API failed: ${err}`);\n // Fallback for older browsers or when Clipboard API is not available\n const textarea = document.createElement('textarea');\n textarea.value = text;\n textarea.style.position = 'fixed';\n textarea.style.opacity = '0';\n textarea.style.pointerEvents = 'none';\n document.body.appendChild(textarea);\n textarea.select();\n const success = document.execCommand('copy');\n document.body.removeChild(textarea);\n return success;\n }\n}\n"],"names":["resolveColumns","columns","fields","onlyVisible","result","filter","c","hidden","field","startsWith","utility","length","fieldSet","Set","has","parseClipboardText","text","config","delimiter","newline","normalizedText","replace","rows","currentRow","currentCell","inQuotes","i","char","push","some","trim","defaultPasteHandler","detail","grid","pastedRows","target","currentRows","effectiveConfig","allFields","map","col","editableMap","Map","forEach","set","editable","newRows","maxPasteRow","bounds","endRow","Infinity","rowData","rowOffset","targetRowIndex","row","emptyRow","cellValue","colOffset","get","ClipboardPlugin","BaseGridPlugin","static","queries","type","description","name","required","reason","defaultConfig","includeHeaders","quoteStrings","lastCopied","attach","super","addEventListener","e","this","handleNativePaste","signal","disconnectSignal","detach","handleQuery","query","copy","onKeyDown","event","ctrlKey","metaKey","key","preventDefault","handleCopy","selection","getSelection","ranges","focused","getFocusedCellFromDOM","rowIndices","clipboardData","getData","parsed","firstRange","targetRow","from","targetCol","mode","to","endCol","maxCol","visibleColumns","column","pasteWidth","emit","applyPasteHandler","pasteHandler","responses","resolveData","options","range","minCol","Math","min","max","slice","indices","sort","a","b","r","resolveRows","minRow","maxRow","buildText","processCell","lines","header","join","cells","value","resolveCellValue","formatCellAsDisplayed","format","formatted","String","renderer","viewRenderer","readCellTextFromDOM","Date","toISOString","JSON","stringify","formatValueAsText","host","gridElement","rowIndex","indexOf","cell","querySelector","textContent","closest","dataset","fieldCache","rowIndexStr","parseInt","isNaN","findIndex","getSelectionAsText","async","navigator","clipboard","writeText","err","warnDiagnostic","CLIPBOARD_FAILED","textarea","document","createElement","style","position","opacity","pointerEvents","body","appendChild","select","success","execCommand","removeChild","copyToClipboard","timestamp","now","rowCount","columnCount","copyRows","paste","readText","readFromClipboard","getLastCopied"],"mappings":"2gBAwBO,SAASA,EACdC,EACAC,EACAC,GAAc,GAEd,IAAIC,EAASH,EAMb,GAJIE,IACFC,EAASA,EAAOC,OAAQC,IAAOA,EAAEC,SAAWD,EAAEE,MAAMC,WAAW,QAAuB,IAAdH,EAAEI,UAGxER,GAAQS,OAAQ,CAClB,MAAMC,EAAW,IAAIC,IAAIX,GACzBE,EAASA,EAAOC,OAAQC,GAAMM,EAASE,IAAIR,EAAEE,OAC/C,CAEA,OAAOJ,CACT,CCpBO,SAASW,EAAmBC,EAAcC,GAC/C,MAAMC,EAAYD,EAAOC,WAAa,KAChCC,EAAUF,EAAOE,SAAW,KAG5BC,EAAiBJ,EAAKK,QAAQ,QAAS,MAAMA,QAAQ,MAAO,MAG5DC,EAAmB,GACzB,IAAIC,EAAuB,GACvBC,EAAc,GACdC,GAAW,EAEf,IAAA,IAASC,EAAI,EAAGA,EAAIN,EAAeT,OAAQe,IAAK,CAC9C,MAAMC,EAAOP,EAAeM,GAEf,MAATC,GAAiBF,EAGD,MAATE,GAAgBF,EAEK,MAA1BL,EAAeM,EAAI,IACrBF,GAAe,IACfE,KAGAD,GAAW,EAEJE,IAAST,GAAcO,EAIvBE,IAASR,GAAYM,EAU9BD,GAAeG,GARfJ,EAAWK,KAAKJ,GAChBA,EAAc,IAEVD,EAAWZ,OAAS,GAAKY,EAAWM,KAAMvB,GAAmB,KAAbA,EAAEwB,UACpDR,EAAKM,KAAKL,GAEZA,EAAa,KAVbA,EAAWK,KAAKJ,GAChBA,EAAc,IAbdC,GAAW,CA0Bf,CAQA,OALAF,EAAWK,KAAKJ,IACZD,EAAWZ,OAAS,GAAKY,EAAWM,KAAMvB,GAAmB,KAAbA,EAAEwB,UACpDR,EAAKM,KAAKL,GAGLD,CACT,C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,WAAMqE,GACJ,MAAMhL,QFreVsJ,iBACE,IACE,aAAaC,UAAUC,UAAUyB,UACnC,CAAA,MAEE,MAAO,EACT,CACF,CE8duBC,GACnB,OAAKlL,EACED,EAAmBC,EAAM4D,KAAK3D,QADnB,IAEpB,CAMA,aAAAkL,GACE,OAAOvH,KAAKL,UACd"}
1
+ {"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../libs/grid/src/lib/plugins/clipboard/ClipboardPlugin.ts","../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts"],"sourcesContent":["/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n","/**\n * Clipboard Paste Logic\n *\n * Pure functions for reading and parsing clipboard data.\n */\n\nimport type { ClipboardConfig } from './types';\n\n/**\n * Parse clipboard text into a 2D array of cell values.\n *\n * Handles:\n * - Quoted values (with escaped double quotes \"\")\n * - Multi-line quoted values (newlines within quotes are preserved)\n * - Custom delimiters and newlines\n * - Empty lines (filtered out only if they contain no data)\n *\n * @param text - Raw clipboard text\n * @param config - Clipboard configuration\n * @returns 2D array where each sub-array is a row of cell values\n */\nexport function parseClipboardText(text: string, config: ClipboardConfig): string[][] {\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Handle Windows CRLF line endings\n const normalizedText = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n // Parse the entire text handling quoted fields that may span multiple lines\n const rows: string[][] = [];\n let currentRow: string[] = [];\n let currentCell = '';\n let inQuotes = false;\n\n for (let i = 0; i < normalizedText.length; i++) {\n const char = normalizedText[i];\n\n if (char === '\"' && !inQuotes) {\n // Start of quoted field\n inQuotes = true;\n } else if (char === '\"' && inQuotes) {\n // Check for escaped quote (\"\")\n if (normalizedText[i + 1] === '\"') {\n currentCell += '\"';\n i++; // Skip the second quote\n } else {\n // End of quoted field\n inQuotes = false;\n }\n } else if (char === delimiter && !inQuotes) {\n // Field separator\n currentRow.push(currentCell);\n currentCell = '';\n } else if (char === newline && !inQuotes) {\n // Row separator (only if not inside quotes)\n currentRow.push(currentCell);\n currentCell = '';\n // Only add non-empty rows (at least one non-empty cell or multiple cells)\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n currentRow = [];\n } else {\n currentCell += char;\n }\n }\n\n // Handle the last cell and row\n currentRow.push(currentCell);\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n\n return rows;\n}\n\n/**\n * Read text from the system clipboard.\n *\n * Uses the modern Clipboard API. Returns empty string if\n * the API is not available or permission is denied.\n *\n * @returns Promise resolving to clipboard text or empty string\n */\nexport async function readFromClipboard(): Promise<string> {\n try {\n return await navigator.clipboard.readText();\n } catch {\n // Permission denied or API not available\n return '';\n }\n}\n","/**\n * Clipboard Plugin Types\n *\n * Type definitions for clipboard copy/paste functionality.\n */\n\nimport type { GridElement } from '../../core/plugin/base-plugin';\n\n/**\n * Custom paste handler function.\n *\n * @param detail - The parsed paste data with target and field info\n * @param grid - The grid element to update\n * @returns `false` to prevent the default paste behavior, or `void`/`true` to allow it\n *\n * @example\n * ```ts\n * // Custom handler that validates before pasting\n * new ClipboardPlugin({\n * pasteHandler: (detail, grid) => {\n * if (!detail.target) return false;\n * // Apply custom validation/transformation...\n * applyPasteData(detail, grid);\n * return false; // We handled it, skip default\n * }\n * })\n * ```\n */\nexport type PasteHandler = (detail: PasteDetail, grid: GridElement) => boolean | void;\n\n/**\n * Options for programmatic copy operations.\n *\n * Allows callers to control exactly which columns and rows are included\n * in a copy, independently of the current selection state.\n *\n * @example Copy specific columns from selected rows\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * // User selected rows 0, 2, 4 via a dialog, chose columns to include\n * const text = await clipboard.copy({\n * rowIndices: [0, 2, 4],\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * ```\n */\nexport interface CopyOptions {\n /** Specific column fields to include. If omitted, uses current selection or all visible columns. */\n columns?: string[];\n /** Specific row indices to copy. If omitted, uses current selection or all rows. */\n rowIndices?: number[];\n /** Include column headers in copied text. Defaults to the plugin config value. */\n includeHeaders?: boolean;\n /** Column delimiter override. Defaults to the plugin config value. */\n delimiter?: string;\n /** Row delimiter override. Defaults to the plugin config value. */\n newline?: string;\n /** Custom cell value processor for this operation. Overrides the plugin config's `processCell`. */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n}\n\n/** Configuration options for the clipboard plugin */\nexport interface ClipboardConfig {\n /** Include column headers in copied text (default: false) */\n includeHeaders?: boolean;\n /** Column delimiter character (default: '\\t' for tab) */\n delimiter?: string;\n /** Row delimiter/newline character (default: '\\n') */\n newline?: string;\n /** Wrap string values with quotes (default: false) */\n quoteStrings?: boolean;\n /** Custom cell value processor for copy operations */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n /**\n * Custom paste handler. By default, the plugin applies pasted data to `grid.rows`\n * starting at the target cell.\n *\n * - Set to a custom function to handle paste yourself\n * - Set to `null` to disable auto-paste (event still fires)\n * - Return `false` from handler to prevent default behavior\n *\n * @default defaultPasteHandler (auto-applies paste data)\n */\n pasteHandler?: PasteHandler | null;\n}\n\n/** Internal state managed by the clipboard plugin */\nexport interface ClipboardState {\n /** The last copied text (for reference/debugging) */\n lastCopied: string | null;\n}\n\n/** Event detail emitted after a successful copy operation */\nexport interface CopyDetail {\n /** The text that was copied to clipboard */\n text: string;\n /** Number of rows copied */\n rowCount: number;\n /** Number of columns copied */\n columnCount: number;\n}\n\n/** Target cell coordinates and bounds for paste operations */\nexport interface PasteTarget {\n /** Target row index (top-left of paste area) */\n row: number;\n /** Target column index (top-left of paste area) */\n col: number;\n /** Target column field name (for easy data mapping) */\n field: string;\n /**\n * Selection bounds that constrain the paste area.\n * If set, paste data will be clipped to fit within these bounds.\n * If null, paste expands freely from the target cell.\n */\n bounds: {\n /** End row index (inclusive) */\n endRow: number;\n /** End column index (inclusive) */\n endCol: number;\n } | null;\n}\n\n/** Event detail emitted after a paste operation */\nexport interface PasteDetail {\n /** Parsed rows from clipboard (2D array of cell values) */\n rows: string[][];\n /** Raw text that was pasted */\n text: string;\n /** The target cell where paste starts (top-left of paste area). Null if no cell is selected. */\n target: PasteTarget | null;\n /**\n * Column fields for each column in the paste range, starting from target.col.\n * Useful for mapping parsed cell values to data fields.\n * Length matches the width of the pasted data (or available columns, whichever is smaller).\n */\n fields: string[];\n}\n\n/**\n * Default paste handler that applies pasted data to grid.rows.\n *\n * This is the built-in handler used when no custom `pasteHandler` is configured.\n * It clones the rows array for immutability and applies values starting at the target cell.\n *\n * Behavior:\n * - Single cell selection: paste expands freely, adds new rows if needed\n * - Range/row selection: paste is clipped to fit within selection bounds\n * - Non-editable columns: values are skipped (column alignment preserved)\n *\n * @param detail - The parsed paste data from clipboard\n * @param grid - The grid element to update\n */\nexport function defaultPasteHandler(detail: PasteDetail, grid: GridElement): void {\n const { rows: pastedRows, target, fields } = detail;\n\n // No target = nothing to do\n if (!target) return;\n\n // Get current rows and columns from grid\n const currentRows = grid.rows as Record<string, unknown>[];\n const columns = grid.effectiveConfig.columns ?? [];\n const allFields = columns.map((col) => col.field);\n\n // Build a map of field -> editable for quick lookup\n const editableMap = new Map<string, boolean>();\n columns.forEach((col) => {\n editableMap.set(col.field, col.editable === true);\n });\n\n // Clone data for immutability\n const newRows = [...currentRows];\n\n // Calculate row bounds\n const maxPasteRow = target.bounds ? target.bounds.endRow : Infinity;\n\n // Apply pasted data starting at target cell\n pastedRows.forEach((rowData, rowOffset) => {\n const targetRowIndex = target.row + rowOffset;\n\n // Stop if we've exceeded the selection bounds\n if (targetRowIndex > maxPasteRow) return;\n\n // Only grow array if no bounds (single cell selection)\n if (!target.bounds) {\n while (targetRowIndex >= newRows.length) {\n const emptyRow: Record<string, unknown> = {};\n allFields.forEach((field) => (emptyRow[field] = ''));\n newRows.push(emptyRow);\n }\n } else if (targetRowIndex >= newRows.length) {\n // With bounds, don't paste beyond existing rows\n return;\n }\n\n // Clone the target row and apply values\n newRows[targetRowIndex] = { ...newRows[targetRowIndex] };\n rowData.forEach((cellValue, colOffset) => {\n // fields array is already constrained by bounds in ClipboardPlugin\n const field = fields[colOffset];\n if (field && editableMap.get(field)) {\n // Only paste into editable columns\n newRows[targetRowIndex][field] = cellValue;\n }\n });\n });\n\n // Update grid with new data\n grid.rows = newRows;\n}\n\n// Module Augmentation - Register plugin name for type-safe getPluginByName()\ndeclare module '../../core/types' {\n interface DataGridEventMap {\n /** Fired after a successful copy operation. Provides the copied text, row count, and column count. @group Clipboard Events */\n 'copy': CopyDetail;\n /** Fired after a paste operation. Provides parsed rows, target cell, and column fields. @group Clipboard Events */\n 'paste': PasteDetail;\n }\n\n interface PluginNameMap {\n clipboard: import('./ClipboardPlugin').ClipboardPlugin;\n }\n}\n","/**\n * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport {\n BaseGridPlugin,\n type GridElement,\n type PluginDependency,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatValueAsText, resolveColumns, resolveRows } from '../shared/data-collection';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type CopyOptions,\n type PasteDetail,\n type PasteTarget,\n} from './types';\n\n/**\n * Clipboard Plugin for tbw-grid\n *\n * Brings familiar copy/cut/paste functionality with full keyboard shortcut support\n * (Ctrl+C, Ctrl+X, Ctrl+V). Handles single cells, multi-cell selections, and integrates\n * seamlessly with Excel and other spreadsheet applications via tab-delimited output.\n *\n * > **Optional Dependency:** Works best with SelectionPlugin for copying/pasting selected\n * > cells. Without SelectionPlugin, copies the entire grid and pastes at row 0, column 0.\n *\n * ## Installation\n *\n * ```ts\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * ```\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see SelectionPlugin for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin manifest — declares queries for inter-plugin communication.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [{ type: 'clipboard:copy', description: 'Triggers a copy operation and returns the copied text' }],\n };\n\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n grid.addEventListener('paste', (e) => this.#handleNativePaste(e), {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'clipboard:copy') {\n this.copy();\n return true;\n }\n return undefined;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n // Prevent the browser's default copy action so it doesn't overwrite\n // our clipboard write with whatever text is selected in the DOM.\n event.preventDefault();\n this.#handleCopy(event.target as HTMLElement);\n return true;\n }\n\n // For paste, we do NOT return true - let the native paste event fire\n // so we can access clipboardData synchronously in #handleNativePaste\n return false;\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Handle copy operation from keyboard shortcut.\n *\n * For keyboard-triggered copies, respects the current selection or\n * falls back to the focused cell from the DOM.\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n\n // Selection plugin exists but nothing selected → try focused cell from DOM\n if (selection && selection.ranges.length === 0) {\n const focused = this.#getFocusedCellFromDOM(target);\n if (!focused) return;\n const col = this.columns[focused.col];\n if (!col) return;\n this.copy({ rowIndices: [focused.row], columns: [col.field] });\n return;\n }\n\n // Delegate to the public copy() method (selection or full grid)\n this.copy();\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n // If the paste target is an editable form control or contenteditable element\n // (e.g. an active cell editor injected by EditingPlugin, a filter input, a\n // header search box), let the browser deliver the paste to that control\n // natively. Without this guard `event.preventDefault()` below would swallow\n // the user's keystroke and the editor input would never receive the text.\n if (this.#isEditablePasteTarget(event.target)) return;\n\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 * True when the paste event originated from a focusable form control or\n * contenteditable element — i.e. somewhere the user expects the browser's\n * native paste behavior (typing into an editor input). Lets EditingPlugin\n * editors, filter inputs, and other text fields receive paste normally\n * instead of having ClipboardPlugin swallow the event.\n */\n #isEditablePasteTarget(target: EventTarget | null): boolean {\n if (!(target instanceof Element)) return false;\n if (target.closest('input, textarea, select, [contenteditable=\"\"], [contenteditable=\"true\"]')) {\n return true;\n }\n return false;\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection');\n return responses?.[0];\n }\n\n /**\n * Resolve columns and rows to include based on options and/or current selection.\n *\n * Priority for columns:\n * 1. `options.columns` (explicit field list)\n * 2. Selection range column bounds (range/cell mode only)\n * 3. All visible non-utility columns\n *\n * Priority for rows:\n * 1. `options.rowIndices` (explicit indices)\n * 2. Selection range row bounds\n * 3. All rows\n */\n #resolveData(options?: CopyOptions): { columns: ColumnConfig[]; rows: Record<string, unknown>[] } {\n const selection = this.#getSelection();\n\n // --- Columns ---\n let columns: ColumnConfig[];\n if (options?.columns) {\n // Caller specified exact fields\n columns = resolveColumns(this.columns, options.columns);\n } else if (selection?.ranges.length && selection.mode !== 'row') {\n // Range/cell selection: restrict to selection column bounds\n // Selection indices are visible-column indices (from data-col)\n const range = selection.ranges[selection.ranges.length - 1];\n const minCol = Math.min(range.from.col, range.to.col);\n const maxCol = Math.max(range.from.col, range.to.col);\n columns = resolveColumns(this.visibleColumns.slice(minCol, maxCol + 1));\n } else {\n // Row selection or no selection: all visible columns\n columns = resolveColumns(this.columns);\n }\n\n // --- Rows ---\n let rows: Record<string, unknown>[];\n if (options?.rowIndices) {\n // Caller specified exact row indices\n rows = resolveRows(this.rows as Record<string, unknown>[], options.rowIndices);\n } else if (selection?.ranges.length) {\n // Selection range: extract contiguous row range\n const range = selection.ranges[selection.ranges.length - 1];\n const minRow = Math.min(range.from.row, range.to.row);\n const maxRow = Math.max(range.from.row, range.to.row);\n rows = [];\n for (let r = minRow; r <= maxRow; r++) {\n const row = this.rows[r] as Record<string, unknown> | undefined;\n if (row) rows.push(row);\n }\n } else {\n // No selection: all rows\n rows = this.rows as Record<string, unknown>[];\n }\n\n return { columns, rows };\n }\n\n /**\n * Build delimited text from resolved columns and rows.\n *\n * When no `processCell` callback is configured, uses \"copy what you see\" logic:\n * 1. Column `format` function (includes typeDefaults merged at config time)\n * 2. DOM cell textContent for columns with custom renderers (visible rows only)\n * 3. Raw value via `formatValueAsText` as final fallback\n */\n #buildText(columns: ColumnConfig[], rows: Record<string, unknown>[], options?: CopyOptions): string {\n const delimiter = options?.delimiter ?? this.config.delimiter ?? '\\t';\n const newline = options?.newline ?? this.config.newline ?? '\\n';\n const includeHeaders = options?.includeHeaders ?? this.config.includeHeaders ?? false;\n const processCell = options?.processCell ?? this.config.processCell;\n\n const lines: string[] = [];\n\n // Header row\n if (includeHeaders) {\n lines.push(columns.map((c) => c.header || c.field).join(delimiter));\n }\n\n // Data rows\n for (const row of rows) {\n const cells = columns.map((col) => {\n const value = resolveCellValue(row, col);\n if (processCell) return processCell(value, col.field, row);\n return this.#formatCellAsDisplayed(col, value, row);\n });\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n }\n\n /**\n * Format a cell value the way the grid displays it.\n *\n * Priority:\n * 1. Column `format` function (includes typeDefaults applied at config merge time)\n * 2. DOM textContent for columns with a custom renderer (virtualized rows only)\n * 3. Raw value via `formatValueAsText`\n */\n #formatCellAsDisplayed(col: ColumnConfig, value: unknown, row: Record<string, unknown>): string {\n // 1. Column format function (covers col.format and typeDefaults)\n if (col.format) {\n try {\n const formatted = col.format(value, row);\n return formatted == null ? '' : String(formatted);\n } catch {\n // Format failed — fall through to next strategy\n }\n }\n\n // 2. DOM textContent for columns with custom renderers\n if (col.renderer || col.viewRenderer) {\n const text = this.#readCellTextFromDOM(col.field, row);\n if (text != null) return text;\n }\n\n // 3. Fallback to raw value formatting\n return formatValueAsText(value);\n }\n\n /**\n * Try to read a cell's displayed text from the DOM.\n *\n * Only works for rows currently rendered in the virtualized viewport.\n * Returns `null` if the row is not in the DOM (caller should fall back).\n */\n #readCellTextFromDOM(field: string, row: Record<string, unknown>): string | null {\n const host = this.gridElement;\n if (!host) return null;\n\n // Find the row index in the grid's current row array\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex === -1) return null;\n\n // Query the rendered cell by row index and field name\n const cell = host.querySelector<HTMLElement>(`.cell[data-row=\"${rowIndex}\"][data-field=\"${field}\"]`);\n if (!cell) return null;\n\n return cell.textContent?.trim() ?? null;\n }\n\n /**\n * Get focused cell coordinates from DOM.\n * Used as fallback when SelectionPlugin has no selection.\n */\n #getFocusedCellFromDOM(target: HTMLElement): { row: number; col: number } | null {\n const cell = target.closest('[data-field-cache]') as HTMLElement | null;\n if (!cell) return null;\n\n const field = cell.dataset.fieldCache;\n const rowIndexStr = cell.dataset.row;\n if (!field || !rowIndexStr) return null;\n\n const row = parseInt(rowIndexStr, 10);\n if (isNaN(row)) return null;\n\n const col = this.columns.findIndex((c) => c.field === field);\n if (col === -1) return null;\n\n return { row, col };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the text representation of the current selection (or specified data)\n * without writing to the system clipboard.\n *\n * Useful for previewing what would be copied, or for feeding the text into\n * a custom UI (e.g., a \"copy with column picker\" dialog).\n *\n * @param options - Control which columns/rows to include\n * @returns Delimited text, or empty string if nothing to copy\n *\n * @example Get text for specific columns\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * const text = clipboard.getSelectionAsText({\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * console.log(text);\n * // \"Name\\tEmail\\nAlice\\talice@example.com\\n...\"\n * ```\n */\n getSelectionAsText(options?: CopyOptions): string {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) return '';\n return this.#buildText(columns, rows, options);\n }\n\n /**\n * Copy data to the system clipboard.\n *\n * Without options, copies the current selection (or entire grid if no selection).\n * With options, copies exactly the specified columns and/or rows — ideal for\n * \"copy with column picker\" workflows where the user selects rows first,\n * then chooses which columns to include via a dialog.\n *\n * @param options - Control which columns/rows to include\n * @returns The copied text\n *\n * @example Copy current selection (default)\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * await clipboard.copy();\n * ```\n *\n * @example Copy specific columns from specific rows\n * ```ts\n * // User selected rows in the grid, then picked columns in a dialog\n * const selectedRowIndices = [0, 3, 7];\n * const chosenColumns = ['name', 'department', 'salary'];\n * await clipboard.copy({\n * rowIndices: selectedRowIndices,\n * columns: chosenColumns,\n * includeHeaders: true,\n * });\n * ```\n */\n async copy(options?: CopyOptions): Promise<string> {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) {\n return '';\n }\n\n const text = this.#buildText(columns, rows, options);\n await copyToClipboard(text);\n this.lastCopied = { text, timestamp: Date.now() };\n this.emit<CopyDetail>('copy', {\n text,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n return text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n *\n * Convenience wrapper around {@link copy} for row-based workflows.\n * Supports non-contiguous row indices (e.g., `[0, 3, 7]`).\n *\n * @param indices - Array of row indices to copy\n * @param options - Additional copy options (columns, headers, etc.)\n * @returns The copied text\n *\n * @example\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * // Copy only rows 0 and 5, including just name and email columns\n * await clipboard.copyRows([0, 5], { columns: ['name', 'email'] });\n * ```\n */\n async copyRows(indices: number[], options?: Omit<CopyOptions, 'rowIndices'>): Promise<string> {\n if (indices.length === 0) return '';\n return this.copy({ ...options, rowIndices: indices });\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, CopyOptions, PasteDetail } from './types';\n","/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport { CLIPBOARD_FAILED, warnDiagnostic } from '../../core/internal/diagnostics';\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport type { ColumnConfig } from '../../core/types';\nimport type { ClipboardConfig } from './types';\n\n/** Parameters for building clipboard text */\nexport interface CopyParams {\n /** All grid rows */\n rows: unknown[];\n /** Column configurations */\n columns: ColumnConfig[];\n /** Selected row indices */\n selectedIndices: Set<number> | number[];\n /** Clipboard configuration */\n config: ClipboardConfig;\n}\n\n/**\n * Format a cell value for clipboard output.\n *\n * Uses custom processCell if provided, otherwise applies default formatting:\n * - null/undefined → empty string\n * - Date → ISO string\n * - Object → JSON string\n * - Other → String conversion with optional quoting\n *\n * @param value - The cell value to format\n * @param field - The field name\n * @param row - The full row object\n * @param config - Clipboard configuration\n * @returns Formatted string value\n */\nexport function formatCellValue(value: unknown, field: string, row: unknown, config: ClipboardConfig): string {\n if (config.processCell) {\n return config.processCell(value, field, row);\n }\n\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n\n const str = String(value);\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Quote if contains delimiter, newline, or quotes (or if quoteStrings is enabled)\n if (config.quoteStrings || str.includes(delimiter) || str.includes(newline) || str.includes('\"')) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build clipboard text from selected rows and columns.\n *\n * @param params - Copy parameters including rows, columns, selection, and config\n * @returns Tab-separated (or custom delimiter) text ready for clipboard\n */\nexport function buildClipboardText(params: CopyParams): string {\n const { rows, columns, selectedIndices, config } = params;\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Filter to visible columns (not hidden, not internal __ prefixed)\n const visibleColumns = columns.filter((c) => !c.hidden && !c.field.startsWith('__'));\n\n const lines: string[] = [];\n\n // Add header row if configured\n if (config.includeHeaders) {\n const headerCells = visibleColumns.map((c) => {\n const header = c.header || c.field;\n // Quote headers if they contain special characters\n if (header.includes(delimiter) || header.includes(newline) || header.includes('\"')) {\n return `\"${header.replace(/\"/g, '\"\"')}\"`;\n }\n return header;\n });\n lines.push(headerCells.join(delimiter));\n }\n\n // Convert indices to sorted array\n const indices = selectedIndices instanceof Set ? [...selectedIndices] : selectedIndices;\n const sortedIndices = [...indices].sort((a, b) => a - b);\n\n // Build data rows\n for (const idx of sortedIndices) {\n const row = rows[idx];\n if (!row) continue;\n\n const cells = visibleColumns.map((col) => formatCellValue(resolveCellValue(row, col), col.field, row, config));\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n}\n\n/**\n * Copy text to the system clipboard.\n *\n * Uses the modern Clipboard API when available, with fallback\n * to execCommand for older browsers.\n *\n * @param text - The text to copy\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch (err) {\n warnDiagnostic(CLIPBOARD_FAILED, `Clipboard API failed: ${err}`);\n // Fallback for older browsers or when Clipboard API is not available\n const textarea = document.createElement('textarea');\n textarea.value = text;\n textarea.style.position = 'fixed';\n textarea.style.opacity = '0';\n textarea.style.pointerEvents = 'none';\n document.body.appendChild(textarea);\n textarea.select();\n const success = document.execCommand('copy');\n document.body.removeChild(textarea);\n return success;\n }\n}\n"],"names":["resolveColumns","columns","fields","onlyVisible","result","filter","c","hidden","field","startsWith","utility","length","fieldSet","Set","has","parseClipboardText","text","config","delimiter","newline","normalizedText","replace","rows","currentRow","currentCell","inQuotes","i","char","push","some","trim","defaultPasteHandler","detail","grid","pastedRows","target","currentRows","effectiveConfig","allFields","map","col","editableMap","Map","forEach","set","editable","newRows","maxPasteRow","bounds","endRow","Infinity","rowData","rowOffset","targetRowIndex","row","emptyRow","cellValue","colOffset","get","ClipboardPlugin","BaseGridPlugin","static","queries","type","description","name","required","reason","defaultConfig","includeHeaders","quoteStrings","lastCopied","attach","super","addEventListener","e","this","handleNativePaste","signal","disconnectSignal","detach","handleQuery","query","copy","onKeyDown","event","ctrlKey","metaKey","key","preventDefault","handleCopy","selection","getSelection","ranges","focused","getFocusedCellFromDOM","rowIndices","isEditablePasteTarget","clipboardData","getData","parsed","firstRange","targetRow","from","targetCol","mode","to","endCol","maxCol","visibleColumns","column","pasteWidth","emit","applyPasteHandler","pasteHandler","Element","closest","responses","resolveData","options","range","minCol","Math","min","max","slice","indices","sort","a","b","r","resolveRows","minRow","maxRow","buildText","processCell","lines","header","join","cells","value","resolveCellValue","formatCellAsDisplayed","format","formatted","String","renderer","viewRenderer","readCellTextFromDOM","Date","toISOString","JSON","stringify","formatValueAsText","host","gridElement","rowIndex","indexOf","cell","querySelector","textContent","dataset","fieldCache","rowIndexStr","parseInt","isNaN","findIndex","getSelectionAsText","async","navigator","clipboard","writeText","err","warnDiagnostic","CLIPBOARD_FAILED","textarea","document","createElement","style","position","opacity","pointerEvents","body","appendChild","select","success","execCommand","removeChild","copyToClipboard","timestamp","now","rowCount","columnCount","copyRows","paste","readText","readFromClipboard","getLastCopied"],"mappings":"2gBAwBO,SAASA,EACdC,EACAC,EACAC,GAAc,GAEd,IAAIC,EAASH,EAMb,GAJIE,IACFC,EAASA,EAAOC,OAAQC,IAAOA,EAAEC,SAAWD,EAAEE,MAAMC,WAAW,QAAuB,IAAdH,EAAEI,UAGxER,GAAQS,OAAQ,CAClB,MAAMC,EAAW,IAAIC,IAAIX,GACzBE,EAASA,EAAOC,OAAQC,GAAMM,EAASE,IAAIR,EAAEE,OAC/C,CAEA,OAAOJ,CACT,CCpBO,SAASW,EAAmBC,EAAcC,GAC/C,MAAMC,EAAYD,EAAOC,WAAa,KAChCC,EAAUF,EAAOE,SAAW,KAG5BC,EAAiBJ,EAAKK,QAAQ,QAAS,MAAMA,QAAQ,MAAO,MAG5DC,EAAmB,GACzB,IAAIC,EAAuB,GACvBC,EAAc,GACdC,GAAW,EAEf,IAAA,IAASC,EAAI,EAAGA,EAAIN,EAAeT,OAAQe,IAAK,CAC9C,MAAMC,EAAOP,EAAeM,GAEf,MAATC,GAAiBF,EAGD,MAATE,GAAgBF,EAEK,MAA1BL,EAAeM,EAAI,IACrBF,GAAe,IACfE,KAGAD,GAAW,EAEJE,IAAST,GAAcO,EAIvBE,IAASR,GAAYM,EAU9BD,GAAeG,GARfJ,EAAWK,KAAKJ,GAChBA,EAAc,IAEVD,EAAWZ,OAAS,GAAKY,EAAWM,KAAMvB,GAAmB,KAAbA,EAAEwB,UACpDR,EAAKM,KAAKL,GAEZA,EAAa,KAVbA,EAAWK,KAAKJ,GAChBA,EAAc,IAbdC,GAAW,CA0Bf,CA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M6K,UAAWxC,KAAKyC,OAC1ClH,KAAKoC,KAAiB,OAAQ,CAC5BhG,OACA+K,SAAUzK,EAAKX,OACfqL,YAAa/L,EAAQU,SAEhBK,CACT,CAmBA,cAAMiL,CAASnE,EAAmBP,GAChC,OAAuB,IAAnBO,EAAQnH,OAAqB,GAC1BiE,KAAKO,KAAK,IAAKoC,EAASvB,WAAY8B,GAC7C,CAMA,WAAMoE,GACJ,MAAMlL,QF3fVwJ,iBACE,IACE,aAAaC,UAAUC,UAAUyB,UACnC,CAAA,MAEE,MAAO,EACT,CACF,CEofuBC,GACnB,OAAKpL,EACED,EAAmBC,EAAM4D,KAAK3D,QADnB,IAEpB,CAMA,aAAAoL,GACE,OAAOzH,KAAKL,UACd"}
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("../../core/internal/aria"),require("../../core/plugin/base-plugin"),require("../../core/internal/value-accessor")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/aria","../../core/plugin/base-plugin","../../core/internal/value-accessor"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_multiSort={},t.TbwGrid,t.TbwGrid,t.TbwGrid)}(this,function(t,e,r,i){"use strict";function o(t,e){const r=!0===t?.__loading;return r===(!0===e?.__loading)?0:r?1:-1}function s(t,e){return null==t&&null==e?0:null==t?1:null==e?-1:"number"==typeof t&&"number"==typeof e?t-e:t instanceof Date&&e instanceof Date?t.getTime()-e.getTime():"boolean"==typeof t&&"boolean"==typeof e?t===e?0:t?-1:1:String(t).localeCompare(String(e))}function n(t,e){const r=t.findIndex(t=>t.field===e);return r>=0?r+1:void 0}function l(t,e){return t.find(t=>t.field===e)?.direction}class d extends r.BaseGridPlugin{static manifest={queries:[{type:"sort:get-model",description:"Returns the current multi-sort model as SortModel[]"},{type:"sort:set-model",description:"Sets the multi-sort model from context (SortModel[])"}]};name="multiSort";styles='@layer tbw-plugins{.header-cell[data-sort=asc]:after{content:"↑";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.header-cell[data-sort=desc]:after{content:"↓";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-indicator{margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-index{font-size:var(--tbw-font-size-2xs, .7em);background:var(--tbw-multi-sort-badge-bg, var(--tbw-color-panel-bg));color:var(--tbw-multi-sort-badge-color, var(--tbw-color-fg));border-radius:50%;width:var(--tbw-multi-sort-badge-size, 1em);height:var(--tbw-multi-sort-badge-size, 1em);display:inline-flex;align-items:center;justify-content:center;margin-left:var(--tbw-spacing-xs, .125em);font-weight:600}}';get defaultConfig(){return{maxSortColumns:3,showSortIndex:!0}}sortModel=[];cachedSortResult=null;#t=!1;#e=[];get#r(){return this.grid}clearCoreSortState(){this.#r._sortState=null}#i(t){const e=this.grid?.query?.("grouping:get-grouped-fields",null);if(!Array.isArray(e)||0===e.length)return t;const r=e[0];if(!Array.isArray(r)||0===r.length)return t;const i=new Set(r),o=t.filter(t=>!i.has(t.field));return o.length===t.length?t:o}detach(){this.sortModel=[],this.cachedSortResult=null}handleQuery(t){switch(t.type){case"sort:get-model":return[...this.sortModel];case"sort:set-model":{const e=t.context;return!!Array.isArray(e)&&(this.sortModel=[...e],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),!0)}default:return}}processRows(t){if(0===this.sortModel.length)return this.cachedSortResult=null,[...t];const e=this.#r;if(!e._isGridEditMode&&"number"==typeof e._activeEditRows&&-1!==e._activeEditRows&&this.cachedSortResult&&this.cachedSortResult.length===t.length)return[...this.cachedSortResult];const r=this.#i(this.sortModel),n=t;return r.length>0&&function(t,e,r){if(!e.length)return;const n=e.map(t=>{const e=r.find(e=>e.field===t.field),i=e?.sortComparator??s;return{field:t.field,asc:"asc"===t.direction,comparator:i,pinPlaceholders:!e?.sortComparator,column:e}}),l=(t,e)=>e.column?.valueAccessor?i.resolveCellValue(t,e.column):t[e.field];if(1===n.length){const e=n[0];t.sort((t,r)=>{if(e.pinPlaceholders){const e=o(t,r);if(0!==e)return e}const i=e.comparator(l(t,e),l(r,e),t,r);return e.asc?i:-i})}else t.sort((t,e)=>{if(n.some(t=>t.pinPlaceholders)){const r=o(t,e);if(0!==r)return r}for(let r=0;r<n.length;r++){const i=n[r],o=i.comparator(l(t,i),l(e,i),t,e);if(0!==o)return i.asc?o:-o}return 0})}(n,r,this.columns),this.cachedSortResult=n,n}onHeaderClick(t){const r=this.columns.find(e=>e.field===t.field);if(!r?.sortable)return!1;const i=t.originalEvent.shiftKey,o=this.config.maxSortColumns??3;if(this.sortModel=function(t,e,r,i){const o=t.find(t=>t.field===e);return r?o?"asc"===o.direction?t.map(t=>t.field===e?{...t,direction:"desc"}:t):t.filter(t=>t.field!==e):t.length<i?[...t,{field:e,direction:"asc"}]:t:"asc"===o?.direction?[{field:e,direction:"desc"}]:"desc"===o?.direction?[]:[{field:e,direction:"asc"}]}(this.sortModel,t.field,i,o),this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),this.grid?.requestStateChange?.(),this.sortModel.length>0){const t=this.sortModel.map(t=>{const e=this.columns.find(e=>e.field===t.field);return`${e?.header??t.field} ${"asc"===t.direction?"ascending":"descending"}`});e.announce(this.gridElement,e.getA11yMessage(this.gridElement,"sortApplied",t.join(", then "),""))}else e.announce(this.gridElement,e.getA11yMessage(this.gridElement,"sortCleared"));return!0}afterRender(){const t=this.gridElement;if(!t)return;const e=!1!==this.config.showSortIndex;t.querySelectorAll(".header-row .cell[data-field]").forEach(t=>{const r=t.getAttribute("data-field");if(!r)return;const i=n(this.sortModel,r),o=l(this.sortModel,r);if(t.querySelector(".sort-index")?.remove(),o){const r=this.updateSortIndicator(t,o);if(e&&this.sortModel.length>1&&void 0!==i){const e=document.createElement("span");e.className="sort-index",e.textContent=String(i),r.nextSibling?t.insertBefore(e,r.nextSibling):t.appendChild(e)}}else t.classList.contains("sortable")&&this.updateSortIndicator(t,null)})}getSortModel(){return[...this.sortModel]}setSortModel(t){if(this.sortModel=[...t],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...t]}),this.requestRender(),this.grid?.requestStateChange?.(),t.length>0){const r=t.map(t=>{const e=this.columns.find(e=>e.field===t.field);return`${e?.header??t.field} ${"asc"===t.direction?"ascending":"descending"}`});e.announce(this.gridElement,e.getA11yMessage(this.gridElement,"sortApplied",r.join(", then "),""))}}clearSort(){this.sortModel=[],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[]}),this.requestRender(),this.grid?.requestStateChange?.(),e.announce(this.gridElement,e.getA11yMessage(this.gridElement,"sortCleared"))}getSortIndex(t){return n(this.sortModel,t)}getSortDirection(t){return l(this.sortModel,t)}getColumnState(t){const e=this.sortModel.findIndex(e=>e.field===t);if(-1===e)return;return{sort:{direction:this.sortModel[e].direction,priority:e}}}applyColumnState(t,e){if(this.#t||(this.#e=[...this.sortModel]),e.sort){const r=this.sortModel.findIndex(e=>e.field===t),i={field:t,direction:e.sort.direction};-1!==r?this.sortModel[r]=i:this.sortModel.splice(e.sort.priority,0,i)}else this.sortModel=this.sortModel.filter(e=>e.field!==t);this.clearCoreSortState(),this.#t||(this.#t=!0,queueMicrotask(()=>{this.#t=!1;const t=this.#e;this.#e=[],function(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r].field!==e[r].field||t[r].direction!==e[r].direction)return!1;return!0}(t,this.sortModel)||(this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender())}))}}t.MultiSortPlugin=d,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("../../core/internal/aria"),require("../../core/plugin/base-plugin"),require("../../core/internal/value-accessor")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/aria","../../core/plugin/base-plugin","../../core/internal/value-accessor"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_multiSort={},t.TbwGrid,t.TbwGrid,t.TbwGrid)}(this,function(t,e,r,i){"use strict";const o=new Intl.Collator(void 0,{sensitivity:"variant"});function n(t,e){return null==t&&null==e?0:null==t?1:null==e?-1:"number"==typeof t&&"number"==typeof e?t-e:t instanceof Date&&e instanceof Date?t.getTime()-e.getTime():"boolean"==typeof t&&"boolean"==typeof e?t===e?0:t?-1:1:o.compare("string"==typeof t?t:String(t),"string"==typeof e?e:String(e))}function s(t,e){const r=t.findIndex(t=>t.field===e);return r>=0?r+1:void 0}function l(t,e){return t.find(t=>t.field===e)?.direction}class d extends r.BaseGridPlugin{static manifest={queries:[{type:"sort:get-model",description:"Returns the current multi-sort model as SortModel[]"},{type:"sort:set-model",description:"Sets the multi-sort model from context (SortModel[])"}]};name="multiSort";styles='@layer tbw-plugins{.header-cell[data-sort=asc]:after{content:"↑";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.header-cell[data-sort=desc]:after{content:"↓";margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-indicator{margin-left:var(--tbw-spacing-xs, .25em);opacity:.8}.sort-index{font-size:var(--tbw-font-size-2xs, .7em);background:var(--tbw-multi-sort-badge-bg, var(--tbw-color-panel-bg));color:var(--tbw-multi-sort-badge-color, var(--tbw-color-fg));border-radius:50%;width:var(--tbw-multi-sort-badge-size, 1em);height:var(--tbw-multi-sort-badge-size, 1em);display:inline-flex;align-items:center;justify-content:center;margin-left:var(--tbw-spacing-xs, .125em);font-weight:600}}';get defaultConfig(){return{maxSortColumns:3,showSortIndex:!0}}sortModel=[];cachedSortResult=null;#t=!1;#e=[];get#r(){return this.grid}clearCoreSortState(){this.#r._sortState=null}#i(t){const e=this.grid?.query?.("grouping:get-grouped-fields",null);if(!Array.isArray(e)||0===e.length)return t;const r=e[0];if(!Array.isArray(r)||0===r.length)return t;const i=new Set(r),o=t.filter(t=>!i.has(t.field));return o.length===t.length?t:o}detach(){this.sortModel=[],this.cachedSortResult=null}handleQuery(t){switch(t.type){case"sort:get-model":return[...this.sortModel];case"sort:set-model":{const e=t.context;return!!Array.isArray(e)&&(this.sortModel=[...e],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),!0)}default:return}}processRows(t){if(0===this.sortModel.length)return this.cachedSortResult=null,[...t];const e=this.#r;if(!e._isGridEditMode&&"number"==typeof e._activeEditRows&&-1!==e._activeEditRows&&this.cachedSortResult&&this.cachedSortResult.length===t.length)return[...this.cachedSortResult];const r=this.#i(this.sortModel),o=t;return r.length>0&&function(t,e,r){if(!e.length)return;const o=e.map(t=>{const e=r.find(e=>e.field===t.field),o=e?.sortComparator??n,s=t.field,l=e?.valueAccessor?t=>i.resolveCellValue(t,e):t=>t[s];return{field:s,asc:"asc"===t.direction,comparator:o,getValue:l,pinPlaceholders:!e?.sortComparator}}),s=o.some(t=>t.pinPlaceholders)&&function(t){for(let e=0;e<t.length;e++)if(!0===t[e]?.__loading)return!0;return!1}(t),l=t.length,d=o.length,a=new Array(l*d);for(let i=0;i<l;i++){const e=t[i],r=i*d;for(let t=0;t<d;t++)a[r+t]=o[t].getValue(e)}const c=l<=4294967295?new Uint32Array(l):new Array(l);for(let i=0;i<l;i++)c[i]=i;const h=(e,r)=>{if(s){const i=function(t,e){const r=!0===t?.__loading;return r===(!0===e?.__loading)?0:r?1:-1}(t[e],t[r]);if(0!==i)return i}const i=e*d,n=r*d;for(let s=0;s<d;s++){const l=o[s],d=l.comparator(a[i+s],a[n+s],t[e],t[r]);if(0!==d)return l.asc?d:-d}return 0};Uint32Array,c.sort(h);const u=t.slice();for(let i=0;i<l;i++)t[i]=u[c[i]]}(o,r,this.columns),this.cachedSortResult=o,o}onHeaderClick(t){const r=this.columns.find(e=>e.field===t.field);if(!r?.sortable)return!1;const i=t.originalEvent.shiftKey,o=this.config.maxSortColumns??3;if(this.sortModel=function(t,e,r,i){const o=t.find(t=>t.field===e);return r?o?"asc"===o.direction?t.map(t=>t.field===e?{...t,direction:"desc"}:t):t.filter(t=>t.field!==e):t.length<i?[...t,{field:e,direction:"asc"}]:t:"asc"===o?.direction?[{field:e,direction:"desc"}]:"desc"===o?.direction?[]:[{field:e,direction:"asc"}]}(this.sortModel,t.field,i,o),this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender(),this.grid?.requestStateChange?.(),this.sortModel.length>0){const t=this.sortModel.map(t=>{const e=this.columns.find(e=>e.field===t.field);return`${e?.header??t.field} ${"asc"===t.direction?"ascending":"descending"}`});e.announce(this.gridElement,e.getA11yMessage(this.gridElement,"sortApplied",t.join(", then "),""))}else e.announce(this.gridElement,e.getA11yMessage(this.gridElement,"sortCleared"));return!0}afterRender(){const t=this.gridElement;if(!t)return;const e=!1!==this.config.showSortIndex;t.querySelectorAll(".header-row .cell[data-field]").forEach(t=>{const r=t.getAttribute("data-field");if(!r)return;const i=s(this.sortModel,r),o=l(this.sortModel,r);if(t.querySelector(".sort-index")?.remove(),o){const r=this.updateSortIndicator(t,o);if(e&&this.sortModel.length>1&&void 0!==i){const e=document.createElement("span");e.className="sort-index",e.textContent=String(i),r.nextSibling?t.insertBefore(e,r.nextSibling):t.appendChild(e)}}else t.classList.contains("sortable")&&this.updateSortIndicator(t,null)})}getSortModel(){return[...this.sortModel]}setSortModel(t){if(this.sortModel=[...t],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[...t]}),this.requestRender(),this.grid?.requestStateChange?.(),t.length>0){const r=t.map(t=>{const e=this.columns.find(e=>e.field===t.field);return`${e?.header??t.field} ${"asc"===t.direction?"ascending":"descending"}`});e.announce(this.gridElement,e.getA11yMessage(this.gridElement,"sortApplied",r.join(", then "),""))}}clearSort(){this.sortModel=[],this.clearCoreSortState(),this.broadcast("sort-change",{sortModel:[]}),this.requestRender(),this.grid?.requestStateChange?.(),e.announce(this.gridElement,e.getA11yMessage(this.gridElement,"sortCleared"))}getSortIndex(t){return s(this.sortModel,t)}getSortDirection(t){return l(this.sortModel,t)}getColumnState(t){const e=this.sortModel.findIndex(e=>e.field===t);if(-1===e)return;return{sort:{direction:this.sortModel[e].direction,priority:e}}}applyColumnState(t,e){if(this.#t||(this.#e=[...this.sortModel]),e.sort){const r=this.sortModel.findIndex(e=>e.field===t),i={field:t,direction:e.sort.direction};-1!==r?this.sortModel[r]=i:this.sortModel.splice(e.sort.priority,0,i)}else this.sortModel=this.sortModel.filter(e=>e.field!==t);this.clearCoreSortState(),this.#t||(this.#t=!0,queueMicrotask(()=>{this.#t=!1;const t=this.#e;this.#e=[],function(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r].field!==e[r].field||t[r].direction!==e[r].direction)return!1;return!0}(t,this.sortModel)||(this.broadcast("sort-change",{sortModel:[...this.sortModel]}),this.requestRender())}))}}t.MultiSortPlugin=d,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=multi-sort.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"multi-sort.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/multi-sort/multi-sort.ts","../../../../../libs/grid/src/lib/plugins/multi-sort/MultiSortPlugin.ts"],"sourcesContent":["/**\n * Multi-Sort Core Logic\n *\n * Pure functions for multi-column sorting operations.\n */\n\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport type { ColumnConfig } from '../../core/types';\nimport type { SortModel } from './types';\n\n/**\n * Apply multiple sort columns to a row array.\n * Sorts are applied in order - first sort has highest priority.\n *\n * @param rows - Array of row objects to sort\n * @param sorts - Ordered array of sort configurations\n * @param columns - Column configurations (for custom comparators)\n * @returns New sorted array (does not mutate original)\n */\nexport function applySorts<TRow = unknown>(rows: TRow[], sorts: SortModel[], columns: ColumnConfig<TRow>[]): TRow[] {\n if (!sorts.length) return [...rows];\n\n const copy = [...rows];\n sortRowsInPlace(copy, sorts, columns);\n return copy;\n}\n\n/**\n * Sort an array in-place using multiple sort columns.\n * Pre-resolves column comparators to avoid O(n·log·n·m) column lookups\n * inside the comparator.\n * @internal\n */\nexport function sortRowsInPlace<TRow = unknown>(rows: TRow[], sorts: SortModel[], columns: ColumnConfig<TRow>[]): void {\n if (!sorts.length) return;\n\n // Pre-resolve comparator chain — avoids columns.find() on every pair comparison\n const chain = sorts.map((sort) => {\n const col = columns.find((c) => c.field === sort.field);\n const comparator = col?.sortComparator ?? defaultComparator;\n return {\n field: sort.field,\n asc: sort.direction === 'asc',\n comparator,\n // Auto-pin `__loading` placeholder rows (e.g. ServerSidePlugin under `sortMode: 'local'`)\n // to the end ONLY when no custom comparator is configured. Custom comparators receive\n // the row pair as 3rd/4th args and own placeholder handling themselves.\n pinPlaceholders: !col?.sortComparator,\n column: col,\n };\n });\n\n // sortComparator (when present) takes precedence over valueAccessor; both still\n // receive the accessor-resolved value when no comparator is given. Documented\n // precedence: sortComparator → valueAccessor → field.\n const getValue = (row: any, link: (typeof chain)[number]) =>\n link.column?.valueAccessor ? resolveCellValue(row, link.column) : row[link.field];\n\n if (chain.length === 1) {\n // Single-sort fast path — avoid loop overhead\n const link = chain[0];\n rows.sort((a: any, b: any) => {\n if (link.pinPlaceholders) {\n const pinned = pinLoadingRows(a, b);\n if (pinned !== 0) return pinned;\n }\n const result = link.comparator(getValue(a, link), getValue(b, link), a, b);\n return link.asc ? result : -result;\n });\n } else {\n rows.sort((a: any, b: any) => {\n // Pin placeholders ahead of the chain — independent of every column's direction.\n // We only need to check once per pair, using the most permissive flag in the chain.\n const anyPin = chain.some((l) => l.pinPlaceholders);\n if (anyPin) {\n const pinned = pinLoadingRows(a, b);\n if (pinned !== 0) return pinned;\n }\n for (let i = 0; i < chain.length; i++) {\n const link = chain[i];\n const result = link.comparator(getValue(a, link), getValue(b, link), a, b);\n if (result !== 0) return link.asc ? result : -result;\n }\n return 0;\n });\n }\n}\n\n/**\n * Pin `__loading` placeholder rows (e.g. ServerSidePlugin under `sortMode: 'local'`)\n * to the end of the sorted array regardless of sort direction.\n *\n * Returns 0 when neither row is a placeholder, +1 when `a` is, -1 when `b` is.\n *\n * @internal\n */\nfunction pinLoadingRows(a: unknown, b: unknown): number {\n const aLoading = (a as { __loading?: unknown } | null)?.__loading === true;\n const bLoading = (b as { __loading?: unknown } | null)?.__loading === true;\n if (aLoading === bLoading) return 0;\n return aLoading ? 1 : -1;\n}\n\n/**\n * Default comparator for sorting values.\n * Handles nulls, numbers, dates, and strings.\n *\n * @param a - First value\n * @param b - Second value\n * @returns Comparison result (-1, 0, 1)\n */\nexport function defaultComparator(a: unknown, b: unknown): number {\n // Handle nulls/undefined - push to end\n if (a == null && b == null) return 0;\n if (a == null) return 1;\n if (b == null) return -1;\n\n // Type-aware comparison\n if (typeof a === 'number' && typeof b === 'number') {\n return a - b;\n }\n\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() - b.getTime();\n }\n\n // Boolean comparison\n if (typeof a === 'boolean' && typeof b === 'boolean') {\n return a === b ? 0 : a ? -1 : 1;\n }\n\n // String comparison (fallback)\n return String(a).localeCompare(String(b));\n}\n\n/**\n * Toggle sort state for a field.\n * With shift key: adds/toggles in multi-sort list\n * Without shift key: replaces entire sort with single column\n *\n * @param current - Current sort model\n * @param field - Field to toggle\n * @param shiftKey - Whether shift key is held (multi-sort mode)\n * @param maxColumns - Maximum columns allowed in sort\n * @returns New sort model\n */\nexport function toggleSort(current: SortModel[], field: string, shiftKey: boolean, maxColumns: number): SortModel[] {\n const existing = current.find((s) => s.field === field);\n\n if (shiftKey) {\n // Multi-sort: add/toggle in list\n if (existing) {\n if (existing.direction === 'asc') {\n // Flip to descending\n return current.map((s) => (s.field === field ? { ...s, direction: 'desc' as const } : s));\n } else {\n // Remove from sort\n return current.filter((s) => s.field !== field);\n }\n } else if (current.length < maxColumns) {\n // Add new sort column\n return [...current, { field, direction: 'asc' as const }];\n }\n // Max columns reached, return unchanged\n return current;\n } else {\n // Single sort: replace all\n if (existing?.direction === 'asc') {\n return [{ field, direction: 'desc' }];\n } else if (existing?.direction === 'desc') {\n return [];\n }\n return [{ field, direction: 'asc' }];\n }\n}\n\n/**\n * Get the sort index (1-based) for a field in the sort model.\n * Returns undefined if the field is not in the sort model.\n *\n * @param sortModel - Current sort model\n * @param field - Field to check\n * @returns 1-based index or undefined\n */\nexport function getSortIndex(sortModel: SortModel[], field: string): number | undefined {\n const index = sortModel.findIndex((s) => s.field === field);\n return index >= 0 ? index + 1 : undefined;\n}\n\n/**\n * Get the sort direction for a field in the sort model.\n *\n * @param sortModel - Current sort model\n * @param field - Field to check\n * @returns Sort direction or undefined if not sorted\n */\nexport function getSortDirection(sortModel: SortModel[], field: string): 'asc' | 'desc' | undefined {\n return sortModel.find((s) => s.field === field)?.direction;\n}\n","/**\n * Multi-Sort Plugin (Class-based)\n *\n * Provides multi-column sorting capabilities for tbw-grid.\n * Supports shift+click for adding secondary sort columns.\n */\n\nimport { announce, getA11yMessage } from '../../core/internal/aria';\nimport { BaseGridPlugin, HeaderClickEvent, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { ColumnState, GridHost } from '../../core/types';\nimport { getSortDirection, getSortIndex, sortRowsInPlace, toggleSort } from './multi-sort';\nimport styles from './multi-sort.css?inline';\nimport type { MultiSortConfig, SortModel } from './types';\n\n/**\n * Multi-Sort Plugin for tbw-grid\n *\n * Enables sorting by multiple columns at once—hold Shift and click additional column\n * headers to build up a sort stack. Priority badges show the sort order, so users\n * always know which column takes precedence.\n *\n * ## Installation\n *\n * ```ts\n * import { MultiSortPlugin } from '@toolbox-web/grid/plugins/multi-sort';\n * ```\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Click header` | Sort by column (clears other sorts) |\n * | `Shift + Click` | Add column to multi-sort stack |\n * | `Ctrl + Click` | Toggle sort direction |\n *\n * ## Events\n *\n * | Event | Detail | Description |\n * |-------|--------|-------------|\n * | `sort-change` | `{ sortModel: SortModel[] }` | Fired when sort changes |\n *\n * @example Basic Multi-Column Sorting\n * ```ts\n * import { queryGrid } from '@toolbox-web/grid';\n * import { MultiSortPlugin } from '@toolbox-web/grid/plugins/multi-sort';\n *\n * const grid = queryGrid('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name', sortable: true },\n * { field: 'department', header: 'Department', sortable: true },\n * { field: 'salary', header: 'Salary', type: 'number', sortable: true },\n * ],\n * plugins: [new MultiSortPlugin({ maxSortColumns: 3, showSortIndex: true })],\n * };\n *\n * grid.on('sort-change', ({ sortModel }) => {\n * console.log('Active sorts:', sortModel);\n * });\n * ```\n *\n * @example Initial Sort Configuration\n * ```ts\n * new MultiSortPlugin({\n * initialSort: [\n * { field: 'department', direction: 'asc' },\n * { field: 'salary', direction: 'desc' },\n * ],\n * })\n * ```\n *\n * @see {@link MultiSortConfig} for all configuration options\n * @see {@link SortModel} for the sort model structure\n *\n * @internal Extends BaseGridPlugin\n */\nexport class MultiSortPlugin extends BaseGridPlugin<MultiSortConfig> {\n /**\n * Plugin manifest declaring query types this plugin responds to.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [\n { type: 'sort:get-model', description: 'Returns the current multi-sort model as SortModel[]' },\n { type: 'sort:set-model', description: 'Sets the multi-sort model from context (SortModel[])' },\n ],\n };\n\n /** @internal */\n readonly name = 'multiSort';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<MultiSortConfig> {\n return {\n maxSortColumns: 3,\n showSortIndex: true,\n };\n }\n\n // #region Internal State\n private sortModel: SortModel[] = [];\n /** Cached sort result — returned as-is while a row edit is active to prevent\n * the edited row from jumping to a new sorted position mid-edit. Row data\n * mutations are still visible because the array holds shared object refs. */\n private cachedSortResult: unknown[] | null = null;\n /** Guards deferred sort-change broadcast during applyColumnState batch. */\n #pendingStateBroadcast = false;\n /** Snapshot of sortModel taken at the start of an applyColumnState batch,\n * used by the deferred broadcast to skip when the model didn't change. */\n #preBatchSortModel: SortModel[] = [];\n\n /** Typed internal grid accessor. */\n get #internalGrid(): GridHost {\n return this.grid as unknown as GridHost;\n }\n\n /**\n * Clear the core `_sortState` so that only this plugin's `processRows`\n * sorting applies. `ConfigManager.applyState()` always sets the core sort\n * state when restoring from storage, even when a plugin handles sorting.\n * Without this, the stale core state leaks into `collectState()` and\n * `reapplyCoreSort()` after the plugin clears its own model.\n */\n private clearCoreSortState(): void {\n this.#internalGrid._sortState = null;\n }\n\n /**\n * Remove sorts on fields that are owned by the grouping plugin.\n * GroupingRowsPlugin handles group header ordering independently, so\n * multi-sort should only sort by non-grouped data columns.\n */\n #filterGroupedFields(model: SortModel[]): SortModel[] {\n const results = this.grid?.query?.('grouping:get-grouped-fields', null);\n if (!Array.isArray(results) || results.length === 0) return model;\n\n const groupedFields = results[0] as string[];\n if (!Array.isArray(groupedFields) || groupedFields.length === 0) return model;\n\n const groupedSet = new Set(groupedFields);\n const filtered = model.filter((s) => !groupedSet.has(s.field));\n return filtered.length === model.length ? model : filtered;\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.sortModel = [];\n this.cachedSortResult = null;\n }\n // #endregion\n\n // #region Query System\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n switch (query.type) {\n case 'sort:get-model':\n return [...this.sortModel];\n case 'sort:set-model': {\n const model = query.context;\n if (!Array.isArray(model)) return false;\n this.sortModel = [...model] as SortModel[];\n this.clearCoreSortState();\n this.broadcast('sort-change', { sortModel: [...this.sortModel] });\n this.requestRender();\n return true;\n }\n default:\n return undefined;\n }\n }\n\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processRows(rows: readonly unknown[]): unknown[] {\n if (this.sortModel.length === 0) {\n this.cachedSortResult = null;\n return [...rows];\n }\n\n // Freeze sort order while a row is actively being edited (row mode only).\n // Re-sorting mid-edit would move the edited row to a new index while the\n // editors remain at the old position, causing data/UI mismatch.\n // In grid mode (_isGridEditMode) sorting is safe — afterCellRender\n // re-injects editors into the re-sorted cells.\n // We return the cached previous sort result (same object references, so\n // in-place value mutations are already visible) instead of unsorted input.\n const grid = this.#internalGrid;\n if (!grid._isGridEditMode && typeof grid._activeEditRows === 'number' && grid._activeEditRows !== -1) {\n if (this.cachedSortResult && this.cachedSortResult.length === rows.length) {\n return [...this.cachedSortResult];\n }\n }\n\n // Sort in-place — the input array is already a mutable copy from plugin-manager.\n // Pre-resolved comparator chain avoids column lookup on every pair comparison.\n // Exclude fields owned by the grouping plugin — group header order is handled\n // by GroupingRowsPlugin, so multi-sort should only affect within-group data order.\n const effectiveModel = this.#filterGroupedFields(this.sortModel);\n\n const mutableRows = rows as unknown[];\n if (effectiveModel.length > 0) {\n sortRowsInPlace(mutableRows, effectiveModel, this.columns);\n }\n this.cachedSortResult = mutableRows;\n return mutableRows;\n }\n\n /** @internal */\n override onHeaderClick(event: HeaderClickEvent): boolean {\n const column = this.columns.find((c) => c.field === event.field);\n if (!column?.sortable) return false;\n\n const shiftKey = event.originalEvent.shiftKey;\n const maxColumns = this.config.maxSortColumns ?? 3;\n\n this.sortModel = toggleSort(this.sortModel, event.field, shiftKey, maxColumns);\n this.clearCoreSortState();\n\n this.broadcast('sort-change', { sortModel: [...this.sortModel] });\n this.requestRender();\n this.grid?.requestStateChange?.();\n\n // Announce for screen readers\n if (this.sortModel.length > 0) {\n const labels = this.sortModel.map((s) => {\n const col = this.columns.find((c) => c.field === s.field);\n return `${col?.header ?? s.field} ${s.direction === 'asc' ? 'ascending' : 'descending'}`;\n });\n announce(this.gridElement!, getA11yMessage(this.gridElement!, 'sortApplied', labels.join(', then '), ''));\n } else {\n announce(this.gridElement!, getA11yMessage(this.gridElement!, 'sortCleared'));\n }\n\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const showIndex = this.config.showSortIndex !== false;\n\n const headerCells = gridEl.querySelectorAll('.header-row .cell[data-field]');\n headerCells.forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (!field) return;\n\n const sortIndex = getSortIndex(this.sortModel, field);\n const sortDir = getSortDirection(this.sortModel, field);\n\n // Remove existing sort index badge (always clean up)\n cell.querySelector('.sort-index')?.remove();\n\n if (sortDir) {\n const indicator = this.updateSortIndicator(cell, sortDir);\n\n // Add sort index badge if multiple columns sorted and showSortIndex is enabled\n if (showIndex && this.sortModel.length > 1 && sortIndex !== undefined) {\n const badge = document.createElement('span');\n badge.className = 'sort-index';\n badge.textContent = String(sortIndex);\n if (indicator.nextSibling) {\n cell.insertBefore(badge, indicator.nextSibling);\n } else {\n cell.appendChild(badge);\n }\n }\n } else if (cell.classList.contains('sortable')) {\n this.updateSortIndicator(cell, null);\n }\n });\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the current sort model.\n * @returns Copy of the current sort model\n */\n getSortModel(): SortModel[] {\n return [...this.sortModel];\n }\n\n /**\n * Set the sort model programmatically.\n * @param model - New sort model to apply\n */\n setSortModel(model: SortModel[]): void {\n this.sortModel = [...model];\n this.clearCoreSortState();\n this.broadcast('sort-change', { sortModel: [...model] });\n this.requestRender();\n this.grid?.requestStateChange?.();\n if (model.length > 0) {\n const labels = model.map((s) => {\n const col = this.columns.find((c) => c.field === s.field);\n return `${col?.header ?? s.field} ${s.direction === 'asc' ? 'ascending' : 'descending'}`;\n });\n announce(this.gridElement!, getA11yMessage(this.gridElement!, 'sortApplied', labels.join(', then '), ''));\n }\n }\n\n /**\n * Clear all sorting.\n */\n clearSort(): void {\n this.sortModel = [];\n this.clearCoreSortState();\n this.broadcast('sort-change', { sortModel: [] });\n this.requestRender();\n this.grid?.requestStateChange?.();\n announce(this.gridElement!, getA11yMessage(this.gridElement!, 'sortCleared'));\n }\n\n /**\n * Get the sort index (1-based) for a specific field.\n * @param field - Field to check\n * @returns 1-based index or undefined if not sorted\n */\n getSortIndex(field: string): number | undefined {\n return getSortIndex(this.sortModel, field);\n }\n\n /**\n * Get the sort direction for a specific field.\n * @param field - Field to check\n * @returns Sort direction or undefined if not sorted\n */\n getSortDirection(field: string): 'asc' | 'desc' | undefined {\n return getSortDirection(this.sortModel, field);\n }\n // #endregion\n\n // #region Column State Hooks\n\n /**\n * Return sort state for a column if it's in the sort model.\n * @internal\n */\n override getColumnState(field: string): Partial<ColumnState> | undefined {\n const index = this.sortModel.findIndex((s) => s.field === field);\n if (index === -1) return undefined;\n\n const sortEntry = this.sortModel[index];\n return {\n sort: {\n direction: sortEntry.direction,\n priority: index,\n },\n };\n }\n\n /**\n * Apply sort state from column state.\n * Rebuilds the sort model from all column states.\n * @internal\n */\n override applyColumnState(field: string, state: ColumnState): void {\n // Snapshot model before mutation so the microtask can skip a no-op\n // broadcast/render when nothing actually changed.\n if (!this.#pendingStateBroadcast) {\n this.#preBatchSortModel = [...this.sortModel];\n }\n\n if (!state.sort) {\n // Remove this field from sortModel if it exists\n this.sortModel = this.sortModel.filter((s) => s.field !== field);\n } else {\n // Find existing entry or add new one\n const existingIndex = this.sortModel.findIndex((s) => s.field === field);\n const newEntry: SortModel = {\n field,\n direction: state.sort.direction,\n };\n\n if (existingIndex !== -1) {\n // Update existing entry\n this.sortModel[existingIndex] = newEntry;\n } else {\n // Add at the correct priority position\n this.sortModel.splice(state.sort.priority, 0, newEntry);\n }\n }\n\n // Clear core sort state — this plugin exclusively handles sorting via\n // processRows. The core _sortState is set by ConfigManager.applyState()\n // before plugins run; null it so reapplyCoreSort() is a no-op.\n this.clearCoreSortState();\n\n // Broadcast sort-change + force a row re-render after state restoration.\n // Both are deferred to a microtask so per-column calls coalesce into one\n // event and one render. The render handles the \"sort cleared\" case that\n // core's width-only fast path cannot detect (core only inspects the\n // *incoming* state, not what the plugin's model became). Skip entirely\n // when the model is unchanged so unrelated state restores stay cheap.\n if (!this.#pendingStateBroadcast) {\n this.#pendingStateBroadcast = true;\n queueMicrotask(() => {\n this.#pendingStateBroadcast = false;\n const prev = this.#preBatchSortModel;\n this.#preBatchSortModel = [];\n if (sortModelEquals(prev, this.sortModel)) return;\n this.broadcast('sort-change', { sortModel: [...this.sortModel] });\n this.requestRender();\n });\n }\n }\n // #endregion\n}\n\n/** Shallow equality for two sort models (order-sensitive). */\nfunction sortModelEquals(a: SortModel[], b: SortModel[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i].field !== b[i].field || a[i].direction !== b[i].direction) return false;\n }\n return true;\n}\n"],"names":["pinLoadingRows","a","b","aLoading","__loading","defaultComparator","Date","getTime","String","localeCompare","getSortIndex","sortModel","field","index","findIndex","s","getSortDirection","find","direction","MultiSortPlugin","BaseGridPlugin","static","queries","type","description","name","styles","defaultConfig","maxSortColumns","showSortIndex","cachedSortResult","pendingStateBroadcast","preBatchSortModel","internalGrid","this","grid","clearCoreSortState","_sortState","filterGroupedFields","model","results","query","Array","isArray","length","groupedFields","groupedSet","Set","filtered","filter","has","detach","handleQuery","context","broadcast","requestRender","processRows","rows","_isGridEditMode","_activeEditRows","effectiveModel","mutableRows","sorts","columns","chain","map","sort","col","c","comparator","sortComparator","asc","pinPlaceholders","column","getValue","row","link","valueAccessor","resolveCellValue","pinned","result","some","l","i","sortRowsInPlace","onHeaderClick","event","sortable","shiftKey","originalEvent","maxColumns","config","current","existing","toggleSort","requestStateChange","labels","header","announce","gridElement","getA11yMessage","join","afterRender","gridEl","showIndex","querySelectorAll","forEach","cell","getAttribute","sortIndex","sortDir","querySelector","remove","indicator","updateSortIndicator","badge","document","createElement","className","textContent","nextSibling","insertBefore","appendChild","classList","contains","getSortModel","setSortModel","clearSort","getColumnState","priority","applyColumnState","state","existingIndex","newEntry","splice","queueMicrotask","prev","sortModelEquals"],"mappings":"6fAgGA,SAASA,EAAeC,EAAYC,GAClC,MAAMC,GAAgE,IAApDF,GAAsCG,UAExD,OAAID,MADkE,IAApDD,GAAsCE,WACtB,EAC3BD,EAAW,GAAI,CACxB,CAUO,SAASE,EAAkBJ,EAAYC,GAE5C,OAAS,MAALD,GAAkB,MAALC,EAAkB,EAC1B,MAALD,EAAkB,EACb,MAALC,GAAkB,EAGL,iBAAND,GAA+B,iBAANC,EAC3BD,EAAIC,EAGTD,aAAaK,MAAQJ,aAAaI,KAC7BL,EAAEM,UAA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KAAM,CACJhD,UAHcgB,KAAKvB,UAAUE,GAGRK,UACrB+G,SAAUpH,GAGhB,CAOS,gBAAAqH,CAAiBtH,EAAeuH,GAOvC,GAJKjG,MAAKH,IACRG,MAAKF,EAAqB,IAAIE,KAAKvB,YAGhCwH,EAAMjE,KAGJ,CAEL,MAAMkE,EAAgBlG,KAAKvB,UAAUG,UAAWC,GAAMA,EAAEH,QAAUA,GAC5DyH,EAAsB,CAC1BzH,QACAM,UAAWiH,EAAMjE,KAAKhD,YAGF,IAAlBkH,EAEFlG,KAAKvB,UAAUyH,GAAiBC,EAGhCnG,KAAKvB,UAAU2H,OAAOH,EAAMjE,KAAK+D,SAAU,EAAGI,EAElD,MAhBEnG,KAAKvB,UAAYuB,KAAKvB,UAAUsC,OAAQlC,GAAMA,EAAEH,QAAUA,GAqB5DsB,KAAKE,qBAQAF,MAAKH,IACRG,MAAKH,GAAyB,EAC9BwG,eAAe,KACbrG,MAAKH,GAAyB,EAC9B,MAAMyG,EAAOtG,MAAKF,EAClBE,MAAKF,EAAqB,GAWlC,SAAyB/B,EAAgBC,GACvC,GAAID,EAAE2C,SAAW1C,EAAE0C,OAAQ,OAAO,EAClC,IAAA,IAASuC,EAAI,EAAGA,EAAIlF,EAAE2C,OAAQuC,IAC5B,GAAIlF,EAAEkF,GAAGvE,QAAUV,EAAEiF,GAAGvE,OAASX,EAAEkF,GAAGjE,YAAchB,EAAEiF,GAAGjE,UAAW,OAAO,EAE7E,OAAO,CACT,CAhBYuH,CAAgBD,EAAMtG,KAAKvB,aAC/BuB,KAAKoB,UAAU,cAAe,CAAE3C,UAAW,IAAIuB,KAAKvB,aACpDuB,KAAKqB,mBAGX"}
1
+ {"version":3,"file":"multi-sort.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/multi-sort/multi-sort.ts","../../../../../libs/grid/src/lib/plugins/multi-sort/MultiSortPlugin.ts"],"sourcesContent":["/**\n * Multi-Sort Core Logic\n *\n * Pure functions for multi-column sorting operations.\n */\n\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport type { ColumnConfig } from '../../core/types';\nimport type { SortModel } from './types';\n\n// Module-level cached collator. `String.prototype.localeCompare(b)` (no args)\n// lazily allocates a fresh Intl.Collator on every call in V8 — measurable on\n// large datasets where string comparisons dominate the secondary sort key.\n// A single cached `Intl.Collator` reused via `.compare(a, b)` is ~3-5x faster.\nconst stringCollator = new Intl.Collator(undefined, { sensitivity: 'variant' });\n\n/**\n * Apply multiple sort columns to a row array.\n * Sorts are applied in order - first sort has highest priority.\n *\n * @param rows - Array of row objects to sort\n * @param sorts - Ordered array of sort configurations\n * @param columns - Column configurations (for custom comparators)\n * @returns New sorted array (does not mutate original)\n */\nexport function applySorts<TRow = unknown>(rows: TRow[], sorts: SortModel[], columns: ColumnConfig<TRow>[]): TRow[] {\n if (!sorts.length) return [...rows];\n\n const copy = [...rows];\n sortRowsInPlace(copy, sorts, columns);\n return copy;\n}\n\n/**\n * Sort an array in-place using multiple sort columns.\n * Pre-resolves column comparators to avoid O(n·log·n·m) column lookups\n * inside the comparator.\n * @internal\n */\nexport function sortRowsInPlace<TRow = unknown>(rows: TRow[], sorts: SortModel[], columns: ColumnConfig<TRow>[]): void {\n if (!sorts.length) return;\n\n // Pre-resolve comparator chain — avoids columns.find() on every pair comparison\n const chain = sorts.map((sort) => {\n const col = columns.find((c) => c.field === sort.field);\n const comparator = col?.sortComparator ?? defaultComparator;\n // Pre-bind the value getter per link so the hot comparator path doesn't\n // re-evaluate `column?.valueAccessor` on every pair comparison. For the\n // common case (no valueAccessor) this collapses to a single property read.\n // Documented precedence: sortComparator → valueAccessor → field.\n const field = sort.field;\n const getValue: (row: TRow) => unknown = col?.valueAccessor\n ? (row: TRow) => resolveCellValue(row, col)\n : (row: TRow) => (row as Record<string, unknown>)[field];\n return {\n field,\n asc: sort.direction === 'asc',\n comparator,\n getValue,\n // Auto-pin `__loading` placeholder rows (e.g. ServerSidePlugin under `sortMode: 'local'`)\n // to the end ONLY when no custom comparator is configured. Custom comparators receive\n // the row pair as 3rd/4th args and own placeholder handling themselves.\n pinPlaceholders: !col?.sortComparator,\n };\n });\n\n // Only enable per-pair pin checks if the dataset *actually* contains loading\n // placeholders — for the common case (no `__loading` rows) we skip ~n·log·n\n // property reads + branch on the hot path. Single O(n) scan up front.\n const chainNeedsPin = chain.some((l) => l.pinPlaceholders);\n const needsPinScan = chainNeedsPin && hasLoadingRow(rows);\n\n // Schwartzian transform: extract sort keys ONCE per row up front, then sort\n // indices by the cached keys. `Array.prototype.sort` calls the comparator\n // ~n·log·n times; without caching, each call would re-extract every key\n // (2 sides × k columns = 2·k property reads / accessor invocations per\n // compare). Caching collapses ~2·k·n·log·n extractions to k·n. For 10K\n // rows × 2 keys that's 20K extractions instead of ~260K, and the comparator\n // body becomes a pure key-vs-key comparison the JIT can optimize tightly.\n const n = rows.length;\n const k = chain.length;\n const keys: unknown[] = new Array(n * k);\n for (let i = 0; i < n; i++) {\n const row = rows[i];\n const base = i * k;\n for (let j = 0; j < k; j++) {\n keys[base + j] = chain[j].getValue(row);\n }\n }\n\n // Index array — sort this and then permute `rows` in one pass at the end.\n // Typed array when it fits; falls back to plain Array for very large datasets.\n const indices: Uint32Array | number[] = n <= 0xffffffff ? new Uint32Array(n) : new Array(n);\n for (let i = 0; i < n; i++) indices[i] = i;\n\n const compareIndices = (ia: number, ib: number): number => {\n if (needsPinScan) {\n const pinned = pinLoadingRows(rows[ia], rows[ib]);\n if (pinned !== 0) return pinned;\n }\n const baseA = ia * k;\n const baseB = ib * k;\n for (let j = 0; j < k; j++) {\n const link = chain[j];\n // Custom comparators receive the row pair as 3rd/4th args; defaultComparator\n // ignores them. Keys are already cached so no extraction happens here.\n const result = link.comparator(keys[baseA + j], keys[baseB + j], rows[ia], rows[ib]);\n if (result !== 0) return link.asc ? result : -result;\n }\n return 0;\n };\n\n if (indices instanceof Uint32Array) {\n indices.sort(compareIndices);\n } else {\n (indices as number[]).sort(compareIndices);\n }\n\n // Permute rows in-place using the sorted index array. Single allocation of\n // a snapshot; then write back. Done in two passes to avoid clobbering.\n const snapshot = rows.slice();\n for (let i = 0; i < n; i++) {\n rows[i] = snapshot[indices[i]];\n }\n}\n\n/**\n * O(n) scan checking whether any row has the `__loading` placeholder marker.\n * Cheap relative to the O(n·log·n) sort, and lets us elide per-pair pin checks\n * when the dataset has no placeholders (the overwhelmingly common case).\n * @internal\n */\nfunction hasLoadingRow(rows: readonly unknown[]): boolean {\n for (let i = 0; i < rows.length; i++) {\n if ((rows[i] as { __loading?: unknown } | null)?.__loading === true) return true;\n }\n return false;\n}\n\n/**\n * Pin `__loading` placeholder rows (e.g. ServerSidePlugin under `sortMode: 'local'`)\n * to the end of the sorted array regardless of sort direction.\n *\n * Returns 0 when neither row is a placeholder, +1 when `a` is, -1 when `b` is.\n *\n * @internal\n */\nfunction pinLoadingRows(a: unknown, b: unknown): number {\n const aLoading = (a as { __loading?: unknown } | null)?.__loading === true;\n const bLoading = (b as { __loading?: unknown } | null)?.__loading === true;\n if (aLoading === bLoading) return 0;\n return aLoading ? 1 : -1;\n}\n\n/**\n * Default comparator for sorting values.\n * Handles nulls, numbers, dates, and strings.\n *\n * @param a - First value\n * @param b - Second value\n * @returns Comparison result (-1, 0, 1)\n */\nexport function defaultComparator(a: unknown, b: unknown): number {\n // Handle nulls/undefined - push to end\n if (a == null && b == null) return 0;\n if (a == null) return 1;\n if (b == null) return -1;\n\n // Type-aware comparison\n if (typeof a === 'number' && typeof b === 'number') {\n return a - b;\n }\n\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() - b.getTime();\n }\n\n // Boolean comparison\n if (typeof a === 'boolean' && typeof b === 'boolean') {\n return a === b ? 0 : a ? -1 : 1;\n }\n\n // String comparison (fallback). Uses a module-level cached Intl.Collator\n // — see `stringCollator` declaration for rationale.\n return stringCollator.compare(typeof a === 'string' ? a : String(a), typeof b === 'string' ? b : String(b));\n}\n\n/**\n * Toggle sort state for a field.\n * With shift key: adds/toggles in multi-sort list\n * Without shift key: replaces entire sort with single column\n *\n * @param current - Current sort model\n * @param field - Field to toggle\n * @param shiftKey - Whether shift key is held (multi-sort mode)\n * @param maxColumns - Maximum columns allowed in sort\n * @returns New sort model\n */\nexport function toggleSort(current: SortModel[], field: string, shiftKey: boolean, maxColumns: number): SortModel[] {\n const existing = current.find((s) => s.field === field);\n\n if (shiftKey) {\n // Multi-sort: add/toggle in list\n if (existing) {\n if (existing.direction === 'asc') {\n // Flip to descending\n return current.map((s) => (s.field === field ? { ...s, direction: 'desc' as const } : s));\n } else {\n // Remove from sort\n return current.filter((s) => s.field !== field);\n }\n } else if (current.length < maxColumns) {\n // Add new sort column\n return [...current, { field, direction: 'asc' as const }];\n }\n // Max columns reached, return unchanged\n return current;\n } else {\n // Single sort: replace all\n if (existing?.direction === 'asc') {\n return [{ field, direction: 'desc' }];\n } else if (existing?.direction === 'desc') {\n return [];\n }\n return [{ field, direction: 'asc' }];\n }\n}\n\n/**\n * Get the sort index (1-based) for a field in the sort model.\n * Returns undefined if the field is not in the sort model.\n *\n * @param sortModel - Current sort model\n * @param field - Field to check\n * @returns 1-based index or undefined\n */\nexport function getSortIndex(sortModel: SortModel[], field: string): number | undefined {\n const index = sortModel.findIndex((s) => s.field === field);\n return index >= 0 ? index + 1 : undefined;\n}\n\n/**\n * Get the sort direction for a field in the sort model.\n *\n * @param sortModel - Current sort model\n * @param field - Field to check\n * @returns Sort direction or undefined if not sorted\n */\nexport function getSortDirection(sortModel: SortModel[], field: string): 'asc' | 'desc' | undefined {\n return sortModel.find((s) => s.field === field)?.direction;\n}\n","/**\n * Multi-Sort Plugin (Class-based)\n *\n * Provides multi-column sorting capabilities for tbw-grid.\n * Supports shift+click for adding secondary sort columns.\n */\n\nimport { announce, getA11yMessage } from '../../core/internal/aria';\nimport { BaseGridPlugin, HeaderClickEvent, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { ColumnState, GridHost } from '../../core/types';\nimport { getSortDirection, getSortIndex, sortRowsInPlace, toggleSort } from './multi-sort';\nimport styles from './multi-sort.css?inline';\nimport type { MultiSortConfig, SortModel } from './types';\n\n/**\n * Multi-Sort Plugin for tbw-grid\n *\n * Enables sorting by multiple columns at once—hold Shift and click additional column\n * headers to build up a sort stack. Priority badges show the sort order, so users\n * always know which column takes precedence.\n *\n * ## Installation\n *\n * ```ts\n * import { MultiSortPlugin } from '@toolbox-web/grid/plugins/multi-sort';\n * ```\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Click header` | Sort by column (clears other sorts) |\n * | `Shift + Click` | Add column to multi-sort stack |\n * | `Ctrl + Click` | Toggle sort direction |\n *\n * ## Events\n *\n * | Event | Detail | Description |\n * |-------|--------|-------------|\n * | `sort-change` | `{ sortModel: SortModel[] }` | Fired when sort changes |\n *\n * @example Basic Multi-Column Sorting\n * ```ts\n * import { queryGrid } from '@toolbox-web/grid';\n * import { MultiSortPlugin } from '@toolbox-web/grid/plugins/multi-sort';\n *\n * const grid = queryGrid('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name', sortable: true },\n * { field: 'department', header: 'Department', sortable: true },\n * { field: 'salary', header: 'Salary', type: 'number', sortable: true },\n * ],\n * plugins: [new MultiSortPlugin({ maxSortColumns: 3, showSortIndex: true })],\n * };\n *\n * grid.on('sort-change', ({ sortModel }) => {\n * console.log('Active sorts:', sortModel);\n * });\n * ```\n *\n * @example Initial Sort Configuration\n * ```ts\n * new MultiSortPlugin({\n * initialSort: [\n * { field: 'department', direction: 'asc' },\n * { field: 'salary', direction: 'desc' },\n * ],\n * })\n * ```\n *\n * @see {@link MultiSortConfig} for all configuration options\n * @see {@link SortModel} for the sort model structure\n *\n * @internal Extends BaseGridPlugin\n */\nexport class MultiSortPlugin extends BaseGridPlugin<MultiSortConfig> {\n /**\n * Plugin manifest declaring query types this plugin responds to.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [\n { type: 'sort:get-model', description: 'Returns the current multi-sort model as SortModel[]' },\n { type: 'sort:set-model', description: 'Sets the multi-sort model from context (SortModel[])' },\n ],\n };\n\n /** @internal */\n readonly name = 'multiSort';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<MultiSortConfig> {\n return {\n maxSortColumns: 3,\n showSortIndex: true,\n };\n }\n\n // #region Internal State\n private sortModel: SortModel[] = [];\n /** Cached sort result — returned as-is while a row edit is active to prevent\n * the edited row from jumping to a new sorted position mid-edit. Row data\n * mutations are still visible because the array holds shared object refs. */\n private cachedSortResult: unknown[] | null = null;\n /** Guards deferred sort-change broadcast during applyColumnState batch. */\n #pendingStateBroadcast = false;\n /** Snapshot of sortModel taken at the start of an applyColumnState batch,\n * used by the deferred broadcast to skip when the model didn't change. */\n #preBatchSortModel: SortModel[] = [];\n\n /** Typed internal grid accessor. */\n get #internalGrid(): GridHost {\n return this.grid as unknown as GridHost;\n }\n\n /**\n * Clear the core `_sortState` so that only this plugin's `processRows`\n * sorting applies. `ConfigManager.applyState()` always sets the core sort\n * state when restoring from storage, even when a plugin handles sorting.\n * Without this, the stale core state leaks into `collectState()` and\n * `reapplyCoreSort()` after the plugin clears its own model.\n */\n private clearCoreSortState(): void {\n this.#internalGrid._sortState = null;\n }\n\n /**\n * Remove sorts on fields that are owned by the grouping plugin.\n * GroupingRowsPlugin handles group header ordering independently, so\n * multi-sort should only sort by non-grouped data columns.\n */\n #filterGroupedFields(model: SortModel[]): SortModel[] {\n const results = this.grid?.query?.('grouping:get-grouped-fields', null);\n if (!Array.isArray(results) || results.length === 0) return model;\n\n const groupedFields = results[0] as string[];\n if (!Array.isArray(groupedFields) || groupedFields.length === 0) return model;\n\n const groupedSet = new Set(groupedFields);\n const filtered = model.filter((s) => !groupedSet.has(s.field));\n return filtered.length === model.length ? model : filtered;\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.sortModel = [];\n this.cachedSortResult = null;\n }\n // #endregion\n\n // #region Query System\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n switch (query.type) {\n case 'sort:get-model':\n return [...this.sortModel];\n case 'sort:set-model': {\n const model = query.context;\n if (!Array.isArray(model)) return false;\n this.sortModel = [...model] as SortModel[];\n this.clearCoreSortState();\n this.broadcast('sort-change', { sortModel: [...this.sortModel] });\n this.requestRender();\n return true;\n }\n default:\n return undefined;\n }\n }\n\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processRows(rows: readonly unknown[]): unknown[] {\n if (this.sortModel.length === 0) {\n this.cachedSortResult = null;\n return [...rows];\n }\n\n // Freeze sort order while a row is actively being edited (row mode only).\n // Re-sorting mid-edit would move the edited row to a new index while the\n // editors remain at the old position, causing data/UI mismatch.\n // In grid mode (_isGridEditMode) sorting is safe — afterCellRender\n // re-injects editors into the re-sorted cells.\n // We return the cached previous sort result (same object references, so\n // in-place value mutations are already visible) instead of unsorted input.\n const grid = this.#internalGrid;\n if (!grid._isGridEditMode && typeof grid._activeEditRows === 'number' && grid._activeEditRows !== -1) {\n if (this.cachedSortResult && this.cachedSortResult.length === rows.length) {\n return [...this.cachedSortResult];\n }\n }\n\n // Sort in-place — the input array is already a mutable copy from plugin-manager.\n // Pre-resolved comparator chain avoids column lookup on every pair comparison.\n // Exclude fields owned by the grouping plugin — group header order is handled\n // by GroupingRowsPlugin, so multi-sort should only affect within-group data order.\n const effectiveModel = this.#filterGroupedFields(this.sortModel);\n\n const mutableRows = rows as unknown[];\n if (effectiveModel.length > 0) {\n sortRowsInPlace(mutableRows, effectiveModel, this.columns);\n }\n this.cachedSortResult = mutableRows;\n return mutableRows;\n }\n\n /** @internal */\n override onHeaderClick(event: HeaderClickEvent): boolean {\n const column = this.columns.find((c) => c.field === event.field);\n if (!column?.sortable) return false;\n\n const shiftKey = event.originalEvent.shiftKey;\n const maxColumns = this.config.maxSortColumns ?? 3;\n\n this.sortModel = toggleSort(this.sortModel, event.field, shiftKey, maxColumns);\n this.clearCoreSortState();\n\n this.broadcast('sort-change', { sortModel: [...this.sortModel] });\n this.requestRender();\n this.grid?.requestStateChange?.();\n\n // Announce for screen readers\n if (this.sortModel.length > 0) {\n const labels = this.sortModel.map((s) => {\n const col = this.columns.find((c) => c.field === s.field);\n return `${col?.header ?? s.field} ${s.direction === 'asc' ? 'ascending' : 'descending'}`;\n });\n announce(this.gridElement!, getA11yMessage(this.gridElement!, 'sortApplied', labels.join(', then '), ''));\n } else {\n announce(this.gridElement!, getA11yMessage(this.gridElement!, 'sortCleared'));\n }\n\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const showIndex = this.config.showSortIndex !== false;\n\n const headerCells = gridEl.querySelectorAll('.header-row .cell[data-field]');\n headerCells.forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (!field) return;\n\n const sortIndex = getSortIndex(this.sortModel, field);\n const sortDir = getSortDirection(this.sortModel, field);\n\n // Remove existing sort index badge (always clean up)\n cell.querySelector('.sort-index')?.remove();\n\n if (sortDir) {\n const indicator = this.updateSortIndicator(cell, sortDir);\n\n // Add sort index badge if multiple columns sorted and showSortIndex is enabled\n if (showIndex && this.sortModel.length > 1 && sortIndex !== undefined) {\n const badge = document.createElement('span');\n badge.className = 'sort-index';\n badge.textContent = String(sortIndex);\n if (indicator.nextSibling) {\n cell.insertBefore(badge, indicator.nextSibling);\n } else {\n cell.appendChild(badge);\n }\n }\n } else if (cell.classList.contains('sortable')) {\n this.updateSortIndicator(cell, null);\n }\n });\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the current sort model.\n * @returns Copy of the current sort model\n */\n getSortModel(): SortModel[] {\n return [...this.sortModel];\n }\n\n /**\n * Set the sort model programmatically.\n * @param model - New sort model to apply\n */\n setSortModel(model: SortModel[]): void {\n this.sortModel = [...model];\n this.clearCoreSortState();\n this.broadcast('sort-change', { sortModel: [...model] });\n this.requestRender();\n this.grid?.requestStateChange?.();\n if (model.length > 0) {\n const labels = model.map((s) => {\n const col = this.columns.find((c) => c.field === s.field);\n return `${col?.header ?? s.field} ${s.direction === 'asc' ? 'ascending' : 'descending'}`;\n });\n announce(this.gridElement!, getA11yMessage(this.gridElement!, 'sortApplied', labels.join(', then '), ''));\n }\n }\n\n /**\n * Clear all sorting.\n */\n clearSort(): void {\n this.sortModel = [];\n this.clearCoreSortState();\n this.broadcast('sort-change', { sortModel: [] });\n this.requestRender();\n this.grid?.requestStateChange?.();\n announce(this.gridElement!, getA11yMessage(this.gridElement!, 'sortCleared'));\n }\n\n /**\n * Get the sort index (1-based) for a specific field.\n * @param field - Field to check\n * @returns 1-based index or undefined if not sorted\n */\n getSortIndex(field: string): number | undefined {\n return getSortIndex(this.sortModel, field);\n }\n\n /**\n * Get the sort direction for a specific field.\n * @param field - Field to check\n * @returns Sort direction or undefined if not sorted\n */\n getSortDirection(field: string): 'asc' | 'desc' | undefined {\n return getSortDirection(this.sortModel, field);\n }\n // #endregion\n\n // #region Column State Hooks\n\n /**\n * Return sort state for a column if it's in the sort model.\n * @internal\n */\n override getColumnState(field: string): Partial<ColumnState> | undefined {\n const index = this.sortModel.findIndex((s) => s.field === field);\n if (index === -1) return undefined;\n\n const sortEntry = this.sortModel[index];\n return {\n sort: {\n direction: sortEntry.direction,\n priority: index,\n },\n };\n }\n\n /**\n * Apply sort state from column state.\n * Rebuilds the sort model from all column states.\n * @internal\n */\n override applyColumnState(field: string, state: ColumnState): void {\n // Snapshot model before mutation so the microtask can skip a no-op\n // broadcast/render when nothing actually changed.\n if (!this.#pendingStateBroadcast) {\n this.#preBatchSortModel = [...this.sortModel];\n }\n\n if (!state.sort) {\n // Remove this field from sortModel if it exists\n this.sortModel = this.sortModel.filter((s) => s.field !== field);\n } else {\n // Find existing entry or add new one\n const existingIndex = this.sortModel.findIndex((s) => s.field === field);\n const newEntry: SortModel = {\n field,\n direction: state.sort.direction,\n };\n\n if (existingIndex !== -1) {\n // Update existing entry\n this.sortModel[existingIndex] = newEntry;\n } else {\n // Add at the correct priority position\n this.sortModel.splice(state.sort.priority, 0, newEntry);\n }\n }\n\n // Clear core sort state — this plugin exclusively handles sorting via\n // processRows. The core _sortState is set by ConfigManager.applyState()\n // before plugins run; null it so reapplyCoreSort() is a no-op.\n this.clearCoreSortState();\n\n // Broadcast sort-change + force a row re-render after state restoration.\n // Both are deferred to a microtask so per-column calls coalesce into one\n // event and one render. The render handles the \"sort cleared\" case that\n // core's width-only fast path cannot detect (core only inspects the\n // *incoming* state, not what the plugin's model became). Skip entirely\n // when the model is unchanged so unrelated state restores stay cheap.\n if (!this.#pendingStateBroadcast) {\n this.#pendingStateBroadcast = true;\n queueMicrotask(() => {\n this.#pendingStateBroadcast = false;\n const prev = this.#preBatchSortModel;\n this.#preBatchSortModel = [];\n if (sortModelEquals(prev, this.sortModel)) return;\n this.broadcast('sort-change', { sortModel: [...this.sortModel] });\n this.requestRender();\n });\n }\n }\n // #endregion\n}\n\n/** Shallow equality for two sort models (order-sensitive). */\nfunction sortModelEquals(a: SortModel[], b: SortModel[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i].field !== b[i].field || a[i].direction !== b[i].direction) return false;\n }\n return true;\n}\n"],"names":["stringCollator","Intl","Collator","sensitivity","defaultComparator","a","b","Date","getTime","compare","String","getSortIndex","sortModel","field","index","findIndex","s","getSortDirection","find","direction","MultiSortPlugin","BaseGridPlugin","static","queries","type","description","name","styles","defaultConfig","maxSortColumns","showSortIndex","cachedSortResult","pendingStateBroadcast","preBatchSortModel","internalGrid","this","grid","clearCoreSortState","_sortState","filterGroupedFields","model","results","query","Array","isArray","length","groupedFields","groupedSet","Set","filtered","filter","has","detach","handleQuery","context","broadcast","requestRender","processRows","rows","_isGridEditMode","_activeEditRows","effectiveModel","mutableRows","sorts","columns","chain","map","sort","col","c","comparator","sortComparator","getValue","valueAccessor","row","resolveCellValue","asc","pinPlaceholders","needsPinScan","some","l","i","__loading","hasLoadingRow","n","k","keys","base","j","indices","Uint32Array","compareIndices","ia","ib","pinned","aLoading","pinLoadingRows","baseA","baseB","link","result","snapshot","slice","sortRowsInPlace","onHeaderClick","event","column","sortable","shiftKey","originalEvent","maxColumns","config","current","existing","toggleSort","requestStateChange","labels","header","announce","gridElement","getA11yMessage","join","afterRender","gridEl","showIndex","querySelectorAll","forEach","cell","getAttribute","sortIndex","sortDir","querySelector","remove","indicator","updateSortIndicator","badge","document","createElement","className","textContent","nextSibling","insertBefore","appendChild","classList","contains","getSortModel","setSortModel","clearSort","getColumnState","priority","applyColumnState","state","existingIndex","newEntry","splice","queueMicrotask","prev","sortModelEquals"],"mappings":"6fAcA,MAAMA,EAAiB,IAAIC,KAAKC,gBAAoB,CAAEC,YAAa,YAoJ5D,SAASC,EAAkBC,EAAYC,GAE5C,OAAS,MAALD,GAAkB,MAALC,EAAkB,EAC1B,MAALD,EAAkB,EACb,MAALC,GAAkB,EAGL,iBAAND,GAA+B,iBAANC,EAC3BD,EAAIC,EAGTD,aAAaE,MAAQD,aAAaC,KAC7BF,EAAEG,UAAYF,EAAEE,UAIR,kBAANH,GAAgC,kBAANC,EAC5BD,IAAMC,EAAI,EAAID,GAAI,EAAK,EAKzBL,EAAeS,QAAqB,iBAANJ,EAAiBA,EAAIK,OAAOL,GAAiB,iBAANC,EAAiBA,EAAII,OAAOJ,GAC1G,CAmDO,SAASK,EAAaC,EAAwBC,GACnD,MAAMC,EAAQF,EAAUG,UAAWC,GAAMA,EAAEH,QAAUA,GACrD,OAAOC,GAAS,EAAIA,EAAQ,OAAI,CAClC,CASO,SAASG,EAAiBL,EAAwBC,GACvD,OAAOD,EAAUM,KAAMF,GAAMA,EAAEH,QAAUA,IAAQM,SACnD,CC9KO,MAAMC,UAAwBC,EAAAA,eAKnCC,gBAAoD,CAClDC,QAAS,CACP,CAAEC,KAAM,iBAAkBC,YAAa,uDACvC,CAAED,KAAM,iBAAkBC,YAAa,0DAKlCC,KAAO,YAEEC,isBAGlB,iBAAuBC,GACrB,MAAO,CACLC,eAAgB,EAChBC,eAAe,EAEnB,CAGQ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A,GAC1D,QAAIC,EAAc,OAGlB,MAAO,CACLqD,KAAM,CACJhD,UAHcgB,KAAKvB,UAAUE,GAGRK,UACrBkI,SAAUvI,GAGhB,CAOS,gBAAAwI,CAAiBzI,EAAe0I,GAOvC,GAJKpH,MAAKH,IACRG,MAAKF,EAAqB,IAAIE,KAAKvB,YAGhC2I,EAAMpF,KAGJ,CAEL,MAAMqF,EAAgBrH,KAAKvB,UAAUG,UAAWC,GAAMA,EAAEH,QAAUA,GAC5D4I,EAAsB,CAC1B5I,QACAM,UAAWoI,EAAMpF,KAAKhD,YAGF,IAAlBqI,EAEFrH,KAAKvB,UAAU4I,GAAiBC,EAGhCtH,KAAKvB,UAAU8I,OAAOH,EAAMpF,KAAKkF,SAAU,EAAGI,EAElD,MAhBEtH,KAAKvB,UAAYuB,KAAKvB,UAAUsC,OAAQlC,GAAMA,EAAEH,QAAUA,GAqB5DsB,KAAKE,qBAQAF,MAAKH,IACRG,MAAKH,GAAyB,EAC9B2H,eAAe,KACbxH,MAAKH,GAAyB,EAC9B,MAAM4H,EAAOzH,MAAKF,EAClBE,MAAKF,EAAqB,GAWlC,SAAyB5B,EAAgBC,GACvC,GAAID,EAAEwC,SAAWvC,EAAEuC,OAAQ,OAAO,EAClC,IAAA,IAASoC,EAAI,EAAGA,EAAI5E,EAAEwC,OAAQoC,IAC5B,GAAI5E,EAAE4E,GAAGpE,QAAUP,EAAE2E,GAAGpE,OAASR,EAAE4E,GAAG9D,YAAcb,EAAE2E,GAAG9D,UAAW,OAAO,EAE7E,OAAO,CACT,CAhBY0I,CAAgBD,EAAMzH,KAAKvB,aAC/BuB,KAAKoB,UAAU,cAAe,CAAE3C,UAAW,IAAIuB,KAAKvB,aACpDuB,KAAKqB,mBAGX"}
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("../../core/constants"),require("../../core/internal/diagnostics"),require("../../core/internal/rows"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/constants","../../core/internal/diagnostics","../../core/internal/rows","../../core/plugin/base-plugin"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_undoRedo={},t.TbwGrid,t.TbwGrid,t.TbwGrid,t.TbwGrid)}(this,function(t,e,o,n,i){"use strict";function c(t,e,o){const n=[...t.undoStack,e];for(;n.length>o;)n.shift();return{undoStack:n,redoStack:[]}}function a(t){if(0===t.undoStack.length)return{newState:t,action:null};const e=[...t.undoStack],o=e.pop();return o?{newState:{undoStack:e,redoStack:[...t.redoStack,o]},action:o}:{newState:t,action:null}}function r(t){if(0===t.redoStack.length)return{newState:t,action:null};const e=[...t.redoStack],o=e.pop();return o?{newState:{undoStack:[...t.undoStack,o],redoStack:e},action:o}:{newState:t,action:null}}class d extends i.BaseGridPlugin{static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];#t=!1;#e=null;#o(t,e){const o=this.rows[t.rowIndex];if(o){try{const n=this.grid.getRowId(o);if(n)return void this.grid.updateRow(n,{[t.field]:e})}catch{}o[t.field]=e}}#n(t){const o=this.grid,i=o._visibleColumns?.findIndex(e=>e.field===t.field)??-1;if(i<0)return;o._focusRow=t.rowIndex,o._focusCol=i;const c=o.findRenderedRowElement?.(t.rowIndex);if(!c)return;const a=c.querySelector(`.cell[data-col="${i}"]`);if(a?.classList.contains(e.GridClasses.EDITING)){const t=a.querySelector(n.FOCUSABLE_EDITOR_SELECTOR);t?.focus({preventScroll:!0})}}#i(t,e){if(this.#t=!0,"compound"===t.type){const o="undo"===e?[...t.actions].reverse():t.actions;for(const t of o)this.#o(t,"undo"===e?t.oldValue:t.newValue)}else this.#o(t,"undo"===e?t.oldValue:t.newValue);this.#t=!1}#c(t){const e="compound"===t.type?t.actions[t.actions.length-1]:t;e&&this.#n(e)}attach(t){super.attach(t),this.on("cell-edit-committed",t=>{this.#t||this.recordEdit(t.rowIndex,t.field,t.oldValue,t.newValue)})}detach(){this.undoStack=[],this.redoStack=[],this.#e=null}onKeyDown(t){const e=(t.ctrlKey||t.metaKey)&&"z"===t.key&&!t.shiftKey,o=(t.ctrlKey||t.metaKey)&&("y"===t.key||"z"===t.key&&t.shiftKey);if(e){t.preventDefault();const e=a({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#i(e.action,"undo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.emit("undo",{action:e.action,type:"undo"}),this.#c(e.action),this.requestRenderWithFocus()),!0}if(o){t.preventDefault();const e=r({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#i(e.action,"redo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.emit("redo",{action:e.action,type:"redo"}),this.#c(e.action),this.requestRenderWithFocus()),!0}return!1}recordEdit(t,e,o,n){const i=function(t,e,o,n){return{type:"cell-edit",rowIndex:t,field:e,oldValue:o,newValue:n,timestamp:Date.now()}}(t,e,o,n);if(this.#e)return void this.#e.push(i);const a=c({undoStack:this.undoStack,redoStack:this.redoStack},i,this.config.maxHistorySize??100);this.undoStack=a.undoStack,this.redoStack=a.redoStack}beginTransaction(){this.#e&&o.throwDiagnostic(o.TRANSACTION_IN_PROGRESS,"Transaction already in progress. Call endTransaction() first."),this.#e=[]}endTransaction(){const t=this.#e;if(t||o.throwDiagnostic(o.NO_TRANSACTION,"No transaction in progress. Call beginTransaction() first."),this.#e=null,0===t.length)return;const e=1===t.length?t[0]:{type:"compound",actions:t,timestamp:Date.now()};const n=c({undoStack:this.undoStack,redoStack:this.redoStack},e,this.config.maxHistorySize??100);this.undoStack=n.undoStack,this.redoStack=n.redoStack}undo(){const t=a({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#i(t.action,"undo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.#c(t.action),this.requestRenderWithFocus()),t.action}redo(){const t=r({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#i(t.action,"redo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.#c(t.action),this.requestRenderWithFocus()),t.action}canUndo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.undoStack.length>0}canRedo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.redoStack.length>0}clearHistory(){const t={undoStack:[],redoStack:[]};this.undoStack=t.undoStack,this.redoStack=t.redoStack,this.#e=null}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}}t.UndoRedoPlugin=d,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("../../core/constants"),require("../../core/internal/diagnostics"),require("../../core/internal/rows"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/constants","../../core/internal/diagnostics","../../core/internal/rows","../../core/plugin/base-plugin"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_undoRedo={},t.TbwGrid,t.TbwGrid,t.TbwGrid,t.TbwGrid)}(this,function(t,e,o,n,i){"use strict";function r(t,e,o){const n=[...t.undoStack,e];for(;n.length>o;)n.shift();return{undoStack:n,redoStack:[]}}function a(t){if(0===t.undoStack.length)return{newState:t,action:null};const e=[...t.undoStack],o=e.pop();return o?{newState:{undoStack:e,redoStack:[...t.redoStack,o]},action:o}:{newState:t,action:null}}function c(t){if(0===t.redoStack.length)return{newState:t,action:null};const e=[...t.redoStack],o=e.pop();return o?{newState:{undoStack:[...t.undoStack,o],redoStack:e},action:o}:{newState:t,action:null}}class s extends i.BaseGridPlugin{static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];#t=!1;#e=null;#o(t,e){const o=this.rows[t.rowIndex];if(o){try{const n=this.grid.getRowId(o);if(n)return void this.grid.updateRow(n,{[t.field]:e})}catch{}o[t.field]=e}}#n(t){const o=this.grid,i=o._visibleColumns?.findIndex(e=>e.field===t.field)??-1;if(i<0)return;o._focusRow=t.rowIndex,o._focusCol=i;const r=o.findRenderedRowElement?.(t.rowIndex);if(!r)return;const a=r.querySelector(`.cell[data-col="${i}"]`);if(a?.classList.contains(e.GridClasses.EDITING)){const t=a.querySelector(n.FOCUSABLE_EDITOR_SELECTOR);t?.focus({preventScroll:!0})}}#i(t,e){if(this.#t=!0,"compound"===t.type){const o="undo"===e?[...t.actions].reverse():t.actions;for(const t of o)this.#o(t,"undo"===e?t.oldValue:t.newValue)}else this.#o(t,"undo"===e?t.oldValue:t.newValue);this.#t=!1}#r(t){const e="compound"===t.type?t.actions[t.actions.length-1]:t;e&&this.#n(e)}attach(t){super.attach(t),this.on("cell-edit-committed",t=>{this.#t||this.recordEdit(t.rowIndex,t.field,t.oldValue,t.newValue)})}detach(){this.undoStack=[],this.redoStack=[],this.#e=null}onKeyDown(t){const e=(t.ctrlKey||t.metaKey)&&"z"===t.key&&!t.shiftKey,o=(t.ctrlKey||t.metaKey)&&("y"===t.key||"z"===t.key&&t.shiftKey);if(!e&&!o)return!1;const n=e?"undo":"redo";return this.#a(t.target)?(this.#c(t.target,n),!0):(t.preventDefault(),this.#s(n),!0)}#s(t){const e={undoStack:this.undoStack,redoStack:this.redoStack},o="undo"===t?a(e):c(e);o.action&&(this.#i(o.action,t),this.undoStack=o.newState.undoStack,this.redoStack=o.newState.redoStack,this.emit(t,{action:o.action,type:t}),this.#r(o.action),this.requestRenderWithFocus())}#a(t){return t instanceof Element&&!!t.closest('input, textarea, [contenteditable=""], [contenteditable="true"]')}#c(t,e){const o="undo"===e?"historyUndo":"historyRedo";let n=!1;const i=t=>{t.inputType===o&&(n=!0)};t.addEventListener("beforeinput",i,{capture:!0}),queueMicrotask(()=>{t.removeEventListener("beforeinput",i,{capture:!0}),n||this.#s(e)})}recordEdit(t,e,o,n){const i=function(t,e,o,n){return{type:"cell-edit",rowIndex:t,field:e,oldValue:o,newValue:n,timestamp:Date.now()}}(t,e,o,n);if(this.#e)return void this.#e.push(i);const a=r({undoStack:this.undoStack,redoStack:this.redoStack},i,this.config.maxHistorySize??100);this.undoStack=a.undoStack,this.redoStack=a.redoStack}beginTransaction(){this.#e&&o.throwDiagnostic(o.TRANSACTION_IN_PROGRESS,"Transaction already in progress. Call endTransaction() first."),this.#e=[]}endTransaction(){const t=this.#e;if(t||o.throwDiagnostic(o.NO_TRANSACTION,"No transaction in progress. Call beginTransaction() first."),this.#e=null,0===t.length)return;const e=1===t.length?t[0]:{type:"compound",actions:t,timestamp:Date.now()};const n=r({undoStack:this.undoStack,redoStack:this.redoStack},e,this.config.maxHistorySize??100);this.undoStack=n.undoStack,this.redoStack=n.redoStack}undo(){const t=a({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#i(t.action,"undo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.#r(t.action),this.requestRenderWithFocus()),t.action}redo(){const t=c({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#i(t.action,"redo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.#r(t.action),this.requestRenderWithFocus()),t.action}canUndo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.undoStack.length>0}canRedo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.redoStack.length>0}clearHistory(){const t={undoStack:[],redoStack:[]};this.undoStack=t.undoStack,this.redoStack=t.redoStack,this.#e=null}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}}t.UndoRedoPlugin=s,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=undo-redo.umd.js.map