@toolbox-web/grid 1.13.0 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/all.js +1483 -1403
- package/all.js.map +1 -1
- package/index.js +11 -4
- package/index.js.map +1 -1
- package/lib/core/internal/row-animation.d.ts.map +1 -1
- package/lib/core/plugin/types.d.ts +1 -1
- package/lib/core/plugin/types.d.ts.map +1 -1
- package/lib/core/types.d.ts +44 -1
- package/lib/core/types.d.ts.map +1 -1
- package/lib/plugins/clipboard/ClipboardPlugin.d.ts +69 -8
- package/lib/plugins/clipboard/ClipboardPlugin.d.ts.map +1 -1
- package/lib/plugins/clipboard/index.d.ts +1 -1
- package/lib/plugins/clipboard/index.d.ts.map +1 -1
- package/lib/plugins/clipboard/index.js +257 -192
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/lib/plugins/clipboard/types.d.ts +31 -0
- package/lib/plugins/clipboard/types.d.ts.map +1 -1
- package/lib/plugins/column-virtualization/index.js.map +1 -1
- package/lib/plugins/context-menu/ContextMenuPlugin.d.ts +8 -0
- package/lib/plugins/context-menu/ContextMenuPlugin.d.ts.map +1 -1
- package/lib/plugins/context-menu/index.js +75 -60
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/context-menu/types.d.ts +7 -0
- package/lib/plugins/context-menu/types.d.ts.map +1 -1
- package/lib/plugins/editing/EditingPlugin.d.ts.map +1 -1
- package/lib/plugins/editing/editors.d.ts +2 -2
- package/lib/plugins/editing/editors.d.ts.map +1 -1
- package/lib/plugins/editing/index.js +420 -381
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/editing/types.d.ts +6 -23
- package/lib/plugins/editing/types.d.ts.map +1 -1
- package/lib/plugins/export/ExportPlugin.d.ts.map +1 -1
- package/lib/plugins/export/index.js +75 -66
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/filtering/index.d.ts +1 -1
- package/lib/plugins/filtering/index.d.ts.map +1 -1
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/multi-sort/index.js.map +1 -1
- package/lib/plugins/pinned-columns/index.js.map +1 -1
- package/lib/plugins/pinned-rows/PinnedRowsPlugin.d.ts +1 -0
- package/lib/plugins/pinned-rows/PinnedRowsPlugin.d.ts.map +1 -1
- package/lib/plugins/pinned-rows/index.js +118 -87
- package/lib/plugins/pinned-rows/index.js.map +1 -1
- package/lib/plugins/pinned-rows/pinned-rows.d.ts +2 -1
- package/lib/plugins/pinned-rows/pinned-rows.d.ts.map +1 -1
- package/lib/plugins/pinned-rows/types.d.ts +23 -2
- package/lib/plugins/pinned-rows/types.d.ts.map +1 -1
- package/lib/plugins/pivot/index.js.map +1 -1
- package/lib/plugins/print/index.js.map +1 -1
- package/lib/plugins/reorder/index.js.map +1 -1
- package/lib/plugins/responsive/index.js.map +1 -1
- package/lib/plugins/row-reorder/index.js.map +1 -1
- package/lib/plugins/selection/SelectionPlugin.d.ts.map +1 -1
- package/lib/plugins/selection/index.js +147 -139
- package/lib/plugins/selection/index.js.map +1 -1
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/shared/data-collection.d.ts +33 -0
- package/lib/plugins/shared/data-collection.d.ts.map +1 -0
- package/lib/plugins/tree/index.js.map +1 -1
- package/lib/plugins/undo-redo/index.js.map +1 -1
- package/lib/plugins/visibility/index.js.map +1 -1
- package/package.json +1 -1
- package/umd/grid.all.umd.js +23 -23
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +2 -2
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/clipboard.umd.js +5 -5
- package/umd/plugins/clipboard.umd.js.map +1 -1
- package/umd/plugins/context-menu.umd.js +1 -1
- package/umd/plugins/context-menu.umd.js.map +1 -1
- package/umd/plugins/editing.umd.js +1 -1
- package/umd/plugins/editing.umd.js.map +1 -1
- package/umd/plugins/export.umd.js +7 -7
- package/umd/plugins/export.umd.js.map +1 -1
- package/umd/plugins/pinned-rows.umd.js +1 -1
- package/umd/plugins/pinned-rows.umd.js.map +1 -1
- package/umd/plugins/selection.umd.js +2 -2
- package/umd/plugins/selection.umd.js.map +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
`,
|
|
1
|
+
(function(h,y){typeof exports=="object"&&typeof module<"u"?y(exports,require("../../core/plugin/base-plugin")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin"],y):(h=typeof globalThis<"u"?globalThis:h||self,y(h.TbwGridPlugin_clipboard={},h.TbwGrid))})(this,(function(h,y){"use strict";function C(c,e,t=!0){let n=c;if(t&&(n=n.filter(s=>!s.hidden&&!s.field.startsWith("__")&&s.meta?.utility!==!0)),e?.length){const s=new Set(e);n=n.filter(o=>s.has(o.field))}return n}function S(c,e){return e?.length?[...e].sort((t,n)=>t-n).map(t=>c[t]).filter(t=>t!=null):c}function T(c){return c==null?"":c instanceof Date?c.toISOString():typeof c=="object"?JSON.stringify(c):String(c)}async function I(c){try{return await navigator.clipboard.writeText(c),!0}catch{const e=document.createElement("textarea");e.value=c,e.style.position="fixed",e.style.opacity="0",e.style.pointerEvents="none",document.body.appendChild(e),e.select();const t=document.execCommand("copy");return document.body.removeChild(e),t}}function x(c,e){const t=e.delimiter??" ",n=e.newline??`
|
|
2
|
+
`,s=c.replace(/\r\n/g,`
|
|
3
3
|
`).replace(/\r/g,`
|
|
4
|
-
`),
|
|
5
|
-
`,quoteStrings:!1}}lastCopied=null;attach(
|
|
6
|
-
`,
|
|
4
|
+
`),o=[];let i=[],l="",a=!1;for(let r=0;r<s.length;r++){const d=s[r];d==='"'&&!a?a=!0:d==='"'&&a?s[r+1]==='"'?(l+='"',r++):a=!1:d===t&&!a?(i.push(l),l=""):d===n&&!a?(i.push(l),l="",(i.length>1||i.some(u=>u.trim()!==""))&&o.push(i),i=[]):l+=d}return i.push(l),(i.length>1||i.some(r=>r.trim()!==""))&&o.push(i),o}async function M(){try{return await navigator.clipboard.readText()}catch{return""}}function R(c,e){const{rows:t,target:n,fields:s}=c;if(!n)return;const o=e.rows,i=e.effectiveConfig.columns??[],l=i.map(u=>u.field),a=new Map;i.forEach(u=>{a.set(u.field,u.editable===!0)});const r=[...o],d=n.bounds?n.bounds.endRow:1/0;t.forEach((u,p)=>{const f=n.row+p;if(!(f>d)){if(n.bounds){if(f>=r.length)return}else for(;f>=r.length;){const g={};l.forEach(w=>g[w]=""),r.push(g)}r[f]={...r[f]},u.forEach((g,w)=>{const m=s[w];m&&a.get(m)&&(r[f][m]=g)})}}),e.rows=r}class P extends y.BaseGridPlugin{static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:" ",newline:`
|
|
5
|
+
`,quoteStrings:!1}}lastCopied=null;attach(e){super.attach(e),e.addEventListener("paste",t=>this.#o(t),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(e){return(e.ctrlKey||e.metaKey)&&e.key==="c"?(this.#s(e.target),!0):!1}#s(e){const t=this.#e();if(t&&t.ranges.length===0){const n=this.#i(e);if(!n)return;const s=this.columns[n.col];if(!s)return;this.copy({rowIndices:[n.row],columns:[s.field]});return}this.copy()}#o(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const n=x(t,this.config),s=this.#e(),o=s?.ranges?.[0],i=o?.from.row??0,l=o?.from.col??0,r=o&&(s?.mode==="range"||s?.mode==="row")&&(o.from.row!==o.to.row||o.from.col!==o.to.col)?{endRow:o.to.row,endCol:o.to.col}:null,d=r?.endCol??this.columns.length-1,u=this.columns[l],p=u?{row:i,col:l,field:u.field,bounds:r}:null,f=[],g=n[0]?.length??0;for(let m=0;m<g&&l+m<=d;m++){const b=this.columns[l+m];b&&!b.hidden&&f.push(b.field)}const w={rows:n,text:t,target:p,fields:f};this.emit("paste",w),this.#r(w)}#r(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(t===null)return;(t??R)(e,this.grid)}#e(){return this.grid?.query("getSelection")?.[0]}#t(e){const t=this.#e();let n;if(e?.columns)n=C(this.columns,e.columns);else if(t?.ranges.length&&t.mode!=="row"){const o=t.ranges[t.ranges.length-1],i=Math.min(o.from.col,o.to.col),l=Math.max(o.from.col,o.to.col);n=C(this.columns.slice(i,l+1))}else n=C(this.columns);let s;if(e?.rowIndices)s=S(this.rows,e.rowIndices);else if(t?.ranges.length){const o=t.ranges[t.ranges.length-1],i=Math.min(o.from.row,o.to.row),l=Math.max(o.from.row,o.to.row);s=[];for(let a=i;a<=l;a++){const r=this.rows[a];r&&s.push(r)}}else s=this.rows;return{columns:n,rows:s}}#n(e,t,n){const s=n?.delimiter??this.config.delimiter??" ",o=n?.newline??this.config.newline??`
|
|
6
|
+
`,i=n?.includeHeaders??this.config.includeHeaders??!1,l=n?.processCell??this.config.processCell,a=[];i&&a.push(e.map(r=>r.header||r.field).join(s));for(const r of t){const d=e.map(u=>{const p=r[u.field];return l?l(p,u.field,r):T(p)});a.push(d.join(s))}return a.join(o)}#i(e){const t=e.closest("[data-field-cache]");if(!t)return null;const n=t.dataset.fieldCache,s=t.dataset.row;if(!n||!s)return null;const o=parseInt(s,10);if(isNaN(o))return null;const i=this.columns.findIndex(l=>l.field===n);return i===-1?null:{row:o,col:i}}getSelectionAsText(e){const{columns:t,rows:n}=this.#t(e);return t.length===0||n.length===0?"":this.#n(t,n,e)}async copy(e){const{columns:t,rows:n}=this.#t(e);if(t.length===0||n.length===0)return"";const s=this.#n(t,n,e);return await I(s),this.lastCopied={text:s,timestamp:Date.now()},this.emit("copy",{text:s,rowCount:n.length,columnCount:t.length}),s}async copyRows(e,t){return e.length===0?"":this.copy({...t,rowIndices:e})}async paste(){const e=await M();return e?x(e,this.config):null}getLastCopied(){return this.lastCopied}}h.ClipboardPlugin=P,h.defaultPasteHandler=R,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));
|
|
7
7
|
//# sourceMappingURL=clipboard.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts","../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../libs/grid/src/lib/plugins/clipboard/ClipboardPlugin.ts"],"sourcesContent":["/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { ClipboardConfig } from './types';\n\n/** Parameters for building clipboard text */\nexport interface CopyParams {\n /** All grid rows */\n rows: unknown[];\n /** Column configurations */\n columns: ColumnConfig[];\n /** Selected row indices */\n selectedIndices: Set<number> | number[];\n /** Clipboard configuration */\n config: ClipboardConfig;\n}\n\n/**\n * Format a cell value for clipboard output.\n *\n * Uses custom processCell if provided, otherwise applies default formatting:\n * - null/undefined → empty string\n * - Date → ISO string\n * - Object → JSON string\n * - Other → String conversion with optional quoting\n *\n * @param value - The cell value to format\n * @param field - The field name\n * @param row - The full row object\n * @param config - Clipboard configuration\n * @returns Formatted string value\n */\nexport function formatCellValue(value: unknown, field: string, row: unknown, config: ClipboardConfig): string {\n if (config.processCell) {\n return config.processCell(value, field, row);\n }\n\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n\n const str = String(value);\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Quote if contains delimiter, newline, or quotes (or if quoteStrings is enabled)\n if (config.quoteStrings || str.includes(delimiter) || str.includes(newline) || str.includes('\"')) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build clipboard text from selected rows and columns.\n *\n * @param params - Copy parameters including rows, columns, selection, and config\n * @returns Tab-separated (or custom delimiter) text ready for clipboard\n */\nexport function buildClipboardText(params: CopyParams): string {\n const { rows, columns, selectedIndices, config } = params;\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Filter to visible columns (not hidden, not internal __ prefixed)\n const visibleColumns = columns.filter((c) => !c.hidden && !c.field.startsWith('__'));\n\n const lines: string[] = [];\n\n // Add header row if configured\n if (config.includeHeaders) {\n const headerCells = visibleColumns.map((c) => {\n const header = c.header || c.field;\n // Quote headers if they contain special characters\n if (header.includes(delimiter) || header.includes(newline) || header.includes('\"')) {\n return `\"${header.replace(/\"/g, '\"\"')}\"`;\n }\n return header;\n });\n lines.push(headerCells.join(delimiter));\n }\n\n // Convert indices to sorted array\n const indices = selectedIndices instanceof Set ? [...selectedIndices] : selectedIndices;\n const sortedIndices = [...indices].sort((a, b) => a - b);\n\n // Build data rows\n for (const idx of sortedIndices) {\n const row = rows[idx];\n if (!row) continue;\n\n const cells = visibleColumns.map((col) =>\n formatCellValue((row as Record<string, unknown>)[col.field], col.field, row, config)\n );\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n}\n\n/**\n * Copy text to the system clipboard.\n *\n * Uses the modern Clipboard API when available, with fallback\n * to execCommand for older browsers.\n *\n * @param text - The text to copy\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n // Fallback for older browsers or when Clipboard API is not available\n const textarea = document.createElement('textarea');\n textarea.value = text;\n textarea.style.position = 'fixed';\n textarea.style.opacity = '0';\n textarea.style.pointerEvents = 'none';\n document.body.appendChild(textarea);\n textarea.select();\n const success = document.execCommand('copy');\n document.body.removeChild(textarea);\n return success;\n }\n}\n","/**\n * Clipboard Paste Logic\n *\n * Pure functions for reading and parsing clipboard data.\n */\n\nimport type { ClipboardConfig } from './types';\n\n/**\n * Parse clipboard text into a 2D array of cell values.\n *\n * Handles:\n * - Quoted values (with escaped double quotes \"\")\n * - Multi-line quoted values (newlines within quotes are preserved)\n * - Custom delimiters and newlines\n * - Empty lines (filtered out only if they contain no data)\n *\n * @param text - Raw clipboard text\n * @param config - Clipboard configuration\n * @returns 2D array where each sub-array is a row of cell values\n */\nexport function parseClipboardText(text: string, config: ClipboardConfig): string[][] {\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Handle Windows CRLF line endings\n const normalizedText = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n // Parse the entire text handling quoted fields that may span multiple lines\n const rows: string[][] = [];\n let currentRow: string[] = [];\n let currentCell = '';\n let inQuotes = false;\n\n for (let i = 0; i < normalizedText.length; i++) {\n const char = normalizedText[i];\n\n if (char === '\"' && !inQuotes) {\n // Start of quoted field\n inQuotes = true;\n } else if (char === '\"' && inQuotes) {\n // Check for escaped quote (\"\")\n if (normalizedText[i + 1] === '\"') {\n currentCell += '\"';\n i++; // Skip the second quote\n } else {\n // End of quoted field\n inQuotes = false;\n }\n } else if (char === delimiter && !inQuotes) {\n // Field separator\n currentRow.push(currentCell);\n currentCell = '';\n } else if (char === newline && !inQuotes) {\n // Row separator (only if not inside quotes)\n currentRow.push(currentCell);\n currentCell = '';\n // Only add non-empty rows (at least one non-empty cell or multiple cells)\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n currentRow = [];\n } else {\n currentCell += char;\n }\n }\n\n // Handle the last cell and row\n currentRow.push(currentCell);\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n\n return rows;\n}\n\n/**\n * Read text from the system clipboard.\n *\n * Uses the modern Clipboard API. Returns empty string if\n * the API is not available or permission is denied.\n *\n * @returns Promise resolving to clipboard text or empty string\n */\nexport async function readFromClipboard(): Promise<string> {\n try {\n return await navigator.clipboard.readText();\n } catch {\n // Permission denied or API not available\n return '';\n }\n}\n","/**\n * Clipboard Plugin Types\n *\n * Type definitions for clipboard copy/paste functionality.\n */\n\nimport type { GridElement } from '../../core/plugin/base-plugin';\n\n/**\n * Custom paste handler function.\n *\n * @param detail - The parsed paste data with target and field info\n * @param grid - The grid element to update\n * @returns `false` to prevent the default paste behavior, or `void`/`true` to allow it\n *\n * @example\n * ```ts\n * // Custom handler that validates before pasting\n * new ClipboardPlugin({\n * pasteHandler: (detail, grid) => {\n * if (!detail.target) return false;\n * // Apply custom validation/transformation...\n * applyPasteData(detail, grid);\n * return false; // We handled it, skip default\n * }\n * })\n * ```\n */\nexport type PasteHandler = (detail: PasteDetail, grid: GridElement) => boolean | void;\n\n/** Configuration options for the clipboard plugin */\nexport interface ClipboardConfig {\n /** Include column headers in copied text (default: false) */\n includeHeaders?: boolean;\n /** Column delimiter character (default: '\\t' for tab) */\n delimiter?: string;\n /** Row delimiter/newline character (default: '\\n') */\n newline?: string;\n /** Wrap string values with quotes (default: false) */\n quoteStrings?: boolean;\n /** Custom cell value processor for copy operations */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n /**\n * Custom paste handler. By default, the plugin applies pasted data to `grid.rows`\n * starting at the target cell.\n *\n * - Set to a custom function to handle paste yourself\n * - Set to `null` to disable auto-paste (event still fires)\n * - Return `false` from handler to prevent default behavior\n *\n * @default defaultPasteHandler (auto-applies paste data)\n */\n pasteHandler?: PasteHandler | null;\n}\n\n/** Internal state managed by the clipboard plugin */\nexport interface ClipboardState {\n /** The last copied text (for reference/debugging) */\n lastCopied: string | null;\n}\n\n/** Event detail emitted after a successful copy operation */\nexport interface CopyDetail {\n /** The text that was copied to clipboard */\n text: string;\n /** Number of rows copied */\n rowCount: number;\n /** Number of columns copied */\n columnCount: number;\n}\n\n/** Target cell coordinates and bounds for paste operations */\nexport interface PasteTarget {\n /** Target row index (top-left of paste area) */\n row: number;\n /** Target column index (top-left of paste area) */\n col: number;\n /** Target column field name (for easy data mapping) */\n field: string;\n /**\n * Selection bounds that constrain the paste area.\n * If set, paste data will be clipped to fit within these bounds.\n * If null, paste expands freely from the target cell.\n */\n bounds: {\n /** End row index (inclusive) */\n endRow: number;\n /** End column index (inclusive) */\n endCol: number;\n } | null;\n}\n\n/** Event detail emitted after a paste operation */\nexport interface PasteDetail {\n /** Parsed rows from clipboard (2D array of cell values) */\n rows: string[][];\n /** Raw text that was pasted */\n text: string;\n /** The target cell where paste starts (top-left of paste area). Null if no cell is selected. */\n target: PasteTarget | null;\n /**\n * Column fields for each column in the paste range, starting from target.col.\n * Useful for mapping parsed cell values to data fields.\n * Length matches the width of the pasted data (or available columns, whichever is smaller).\n */\n fields: string[];\n}\n\n/**\n * Default paste handler that applies pasted data to grid.rows.\n *\n * This is the built-in handler used when no custom `pasteHandler` is configured.\n * It clones the rows array for immutability and applies values starting at the target cell.\n *\n * Behavior:\n * - Single cell selection: paste expands freely, adds new rows if needed\n * - Range/row selection: paste is clipped to fit within selection bounds\n * - Non-editable columns: values are skipped (column alignment preserved)\n *\n * @param detail - The parsed paste data from clipboard\n * @param grid - The grid element to update\n */\nexport function defaultPasteHandler(detail: PasteDetail, grid: GridElement): void {\n const { rows: pastedRows, target, fields } = detail;\n\n // No target = nothing to do\n if (!target) return;\n\n // Get current rows and columns from grid\n const currentRows = grid.rows as Record<string, unknown>[];\n const columns = grid.effectiveConfig.columns ?? [];\n const allFields = columns.map((col) => col.field);\n\n // Build a map of field -> editable for quick lookup\n const editableMap = new Map<string, boolean>();\n columns.forEach((col) => {\n editableMap.set(col.field, col.editable === true);\n });\n\n // Clone data for immutability\n const newRows = [...currentRows];\n\n // Calculate row bounds\n const maxPasteRow = target.bounds ? target.bounds.endRow : Infinity;\n\n // Apply pasted data starting at target cell\n pastedRows.forEach((rowData, rowOffset) => {\n const targetRowIndex = target.row + rowOffset;\n\n // Stop if we've exceeded the selection bounds\n if (targetRowIndex > maxPasteRow) return;\n\n // Only grow array if no bounds (single cell selection)\n if (!target.bounds) {\n while (targetRowIndex >= newRows.length) {\n const emptyRow: Record<string, unknown> = {};\n allFields.forEach((field) => (emptyRow[field] = ''));\n newRows.push(emptyRow);\n }\n } else if (targetRowIndex >= newRows.length) {\n // With bounds, don't paste beyond existing rows\n return;\n }\n\n // Clone the target row and apply values\n newRows[targetRowIndex] = { ...newRows[targetRowIndex] };\n rowData.forEach((cellValue, colOffset) => {\n // fields array is already constrained by bounds in ClipboardPlugin\n const field = fields[colOffset];\n if (field && editableMap.get(field)) {\n // Only paste into editable columns\n newRows[targetRowIndex][field] = cellValue;\n }\n });\n });\n\n // Update grid with new data\n grid.rows = newRows;\n}\n","/**\n * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport { isUtilityColumn } from '../../core/plugin/expander-column';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type PasteDetail,\n type PasteTarget,\n} from './types';\n\n/**\n * Clipboard Plugin for tbw-grid\n *\n * Brings familiar copy/cut/paste functionality with full keyboard shortcut support\n * (Ctrl+C, Ctrl+X, Ctrl+V). Handles single cells, multi-cell selections, and integrates\n * seamlessly with Excel and other spreadsheet applications via tab-delimited output.\n *\n * > **Optional Dependency:** Works best with SelectionPlugin for copying/pasting selected\n * > cells. Without SelectionPlugin, copies the entire grid and pastes at row 0, column 0.\n *\n * ## Installation\n *\n * ```ts\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `includeHeaders` | `boolean` | `false` | Include column headers in copied data |\n * | `delimiter` | `string` | `'\\t'` | Column delimiter (tab for Excel compatibility) |\n * | `newline` | `string` | `'\\n'` | Row delimiter |\n * | `quoteStrings` | `boolean` | `false` | Wrap string values in quotes |\n * | `processCell` | `(value, field, row) => string` | - | Custom cell value processor |\n * | `pasteHandler` | `PasteHandler \\| null` | `defaultPasteHandler` | Custom paste handler |\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `copy` | `(options?) => Promise<void>` | Copy selection to clipboard |\n * | `paste` | `() => Promise<void>` | Paste from clipboard |\n * | `getSelectionAsText` | `() => string` | Get clipboard text without copying |\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see {@link SelectionPlugin} for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n // Cast to HTMLElement since GridElement is an interface\n (grid as unknown as HTMLElement).addEventListener(\n 'paste',\n (e: Event) => this.#handleNativePaste(e as ClipboardEvent),\n { signal: this.disconnectSignal },\n );\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n this.#handleCopy(event.target as HTMLElement);\n return true; // Prevent default browser behavior\n }\n\n // For paste, we do NOT return true - let the native paste event fire\n // so we can access clipboardData synchronously in #handleNativePaste\n return false;\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Handle copy operation.\n *\n * Everything is treated as a range:\n * - With selection: copies the selected range\n * - Row mode: range spanning all columns for selected rows\n * - No selection plugin: entire grid as a range\n * - No selection: try to get focused cell from DOM as 1x1 range\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n const lastCol = this.columns.length - 1;\n const lastRow = this.rows.length - 1;\n\n let range: { startRow: number; startCol: number; endRow: number; endCol: number };\n\n if (selection && selection.ranges.length > 0) {\n const { mode, ranges } = selection;\n const activeRange = ranges[ranges.length - 1];\n\n if (mode === 'row') {\n // Row mode: use row bounds, but span all columns\n range = {\n startRow: activeRange.from.row,\n startCol: 0,\n endRow: activeRange.to.row,\n endCol: lastCol,\n };\n } else {\n // Cell or range mode: use the selection as-is\n range = {\n startRow: activeRange.from.row,\n startCol: activeRange.from.col,\n endRow: activeRange.to.row,\n endCol: activeRange.to.col,\n };\n }\n } else if (!selection) {\n // No selection plugin: copy entire grid\n range = { startRow: 0, startCol: 0, endRow: lastRow, endCol: lastCol };\n } else {\n // Selection plugin exists but no selection: try focused cell from DOM\n const focused = this.#getFocusedCellFromDOM(target);\n if (!focused) return;\n range = { startRow: focused.row, startCol: focused.col, endRow: focused.row, endCol: focused.col };\n }\n\n const result = this.#buildRangeText(range);\n\n copyToClipboard(result.text).then(() => {\n this.lastCopied = { text: result.text, timestamp: Date.now() };\n this.emit<CopyDetail>('copy', {\n text: result.text,\n rowCount: result.rowCount,\n columnCount: result.columnCount,\n });\n });\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection via query\n const selection = this.#getSelection();\n const firstRange = selection?.ranges?.[0];\n\n // Determine target cell and bounds\n const targetRow = firstRange?.from.row ?? 0;\n const targetCol = firstRange?.from.col ?? 0;\n\n // Check if multi-cell selection (range with different start/end)\n const isMultiCell =\n firstRange &&\n (selection?.mode === 'range' || selection?.mode === 'row') &&\n (firstRange.from.row !== firstRange.to.row || firstRange.from.col !== firstRange.to.col);\n\n const bounds = isMultiCell ? { endRow: firstRange.to.row, endCol: firstRange.to.col } : null;\n const maxCol = bounds?.endCol ?? this.columns.length - 1;\n\n // Build target info\n const column = this.columns[targetCol];\n const target: PasteTarget | null = column ? { row: targetRow, col: targetCol, field: column.field, bounds } : null;\n\n // Build field list for paste width (constrained by bounds if set)\n const fields: string[] = [];\n const pasteWidth = parsed[0]?.length ?? 0;\n for (let i = 0; i < pasteWidth && targetCol + i <= maxCol; i++) {\n const col = this.columns[targetCol + i];\n if (col && !col.hidden) {\n fields.push(col.field);\n }\n }\n\n const detail: PasteDetail = { rows: parsed, text, target, fields };\n\n // Emit the event for any listeners\n this.emit<PasteDetail>('paste', detail);\n\n // Apply paste data using the configured handler (or default)\n this.#applyPasteHandler(detail);\n }\n\n /**\n * Apply the paste handler to update grid data.\n *\n * Uses the configured `pasteHandler`, or the default handler if not specified.\n * Set `pasteHandler: null` in config to disable auto-paste.\n */\n #applyPasteHandler(detail: PasteDetail): void {\n if (!this.grid) return;\n\n const { pasteHandler } = this.config;\n\n // pasteHandler: null means explicitly disabled\n if (pasteHandler === null) return;\n\n // Use custom handler or default\n const handler = pasteHandler ?? defaultPasteHandler;\n handler(detail, this.grid);\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection', undefined);\n return responses?.[0];\n }\n\n /**\n * Build text for a rectangular range of cells.\n * Utility columns (like expander columns) are automatically excluded.\n */\n #buildRangeText(range: { startRow: number; startCol: number; endRow: number; endCol: number }): {\n text: string;\n rowCount: number;\n columnCount: number;\n } {\n const { startRow, startCol, endRow, endCol } = range;\n const minRow = Math.min(startRow, endRow);\n const maxRow = Math.max(startRow, endRow);\n const minCol = Math.min(startCol, endCol);\n const maxCol = Math.max(startCol, endCol);\n\n const delimiter = this.config.delimiter ?? '\\t';\n const newline = this.config.newline ?? '\\n';\n const lines: string[] = [];\n\n // Get columns in the range, excluding utility columns (expander, etc.)\n const rangeColumns = this.columns.slice(minCol, maxCol + 1).filter((col) => !isUtilityColumn(col));\n\n // Add header row if configured\n if (this.config.includeHeaders) {\n const headerCells = rangeColumns.map((c) => c.header || c.field);\n lines.push(headerCells.join(delimiter));\n }\n\n // Add data rows\n for (let r = minRow; r <= maxRow; r++) {\n const rowData = this.rows[r] as Record<string, unknown> | undefined;\n if (!rowData) continue;\n\n const cells = rangeColumns.map((col) => {\n const value = rowData[col.field];\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n return String(value);\n });\n lines.push(cells.join(delimiter));\n }\n\n return {\n text: lines.join(newline),\n rowCount: maxRow - minRow + 1,\n columnCount: maxCol - minCol + 1,\n };\n }\n\n /**\n * Get focused cell coordinates from DOM.\n * Used as fallback when SelectionPlugin has no selection.\n */\n #getFocusedCellFromDOM(target: HTMLElement): { row: number; col: number } | null {\n const cell = target.closest('[data-field-cache]') as HTMLElement | null;\n if (!cell) return null;\n\n const field = cell.dataset.fieldCache;\n const rowIndexStr = cell.dataset.row;\n if (!field || !rowIndexStr) return null;\n\n const row = parseInt(rowIndexStr, 10);\n if (isNaN(row)) return null;\n\n const col = this.columns.findIndex((c) => c.field === field);\n if (col === -1) return null;\n\n return { row, col };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Copy currently selected rows to clipboard.\n * @returns The copied text\n */\n async copy(): Promise<string> {\n const selection = this.#getSelection();\n const lastCol = this.columns.length - 1;\n\n // Default to entire grid if no selection\n let range = { startRow: 0, startCol: 0, endRow: this.rows.length - 1, endCol: lastCol };\n\n if (selection && selection.ranges.length > 0) {\n const activeRange = selection.ranges[selection.ranges.length - 1];\n if (selection.mode === 'row') {\n range = { startRow: activeRange.from.row, startCol: 0, endRow: activeRange.to.row, endCol: lastCol };\n } else {\n range = {\n startRow: activeRange.from.row,\n startCol: activeRange.from.col,\n endRow: activeRange.to.row,\n endCol: activeRange.to.col,\n };\n }\n }\n\n const result = this.#buildRangeText(range);\n await copyToClipboard(result.text);\n this.lastCopied = { text: result.text, timestamp: Date.now() };\n return result.text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n * @param indices - Array of row indices to copy\n * @returns The copied text\n */\n async copyRows(indices: number[]): Promise<string> {\n if (indices.length === 0) return '';\n\n const sortedIndices = [...indices].sort((a, b) => a - b);\n const lastCol = this.columns.length - 1;\n\n // For non-contiguous rows, we need to copy each row separately\n // For now, copy the range from first to last selected row\n const range = {\n startRow: sortedIndices[0],\n startCol: 0,\n endRow: sortedIndices[sortedIndices.length - 1],\n endCol: lastCol,\n };\n\n const result = this.#buildRangeText(range);\n await copyToClipboard(result.text);\n this.lastCopied = { text: result.text, timestamp: Date.now() };\n return result.text;\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, PasteDetail } from './types';\n"],"names":["copyToClipboard","text","textarea","success","parseClipboardText","config","delimiter","newline","normalizedText","rows","currentRow","currentCell","inQuotes","i","char","c","readFromClipboard","defaultPasteHandler","detail","grid","pastedRows","target","fields","currentRows","columns","allFields","col","editableMap","newRows","maxPasteRow","rowData","rowOffset","targetRowIndex","emptyRow","field","cellValue","colOffset","ClipboardPlugin","BaseGridPlugin","e","#handleNativePaste","event","#handleCopy","selection","#getSelection","lastCol","lastRow","range","mode","ranges","activeRange","focused","#getFocusedCellFromDOM","result","#buildRangeText","parsed","firstRange","targetRow","targetCol","bounds","maxCol","column","pasteWidth","#applyPasteHandler","pasteHandler","startRow","startCol","endRow","endCol","minRow","maxRow","minCol","lines","rangeColumns","isUtilityColumn","headerCells","r","cells","value","cell","rowIndexStr","row","indices","sortedIndices","a","b"],"mappings":"kaAiHA,eAAsBA,EAAgBC,EAAgC,CACpE,GAAI,CACF,aAAM,UAAU,UAAU,UAAUA,CAAI,EACjC,EACT,MAAQ,CAEN,MAAMC,EAAW,SAAS,cAAc,UAAU,EAClDA,EAAS,MAAQD,EACjBC,EAAS,MAAM,SAAW,QAC1BA,EAAS,MAAM,QAAU,IACzBA,EAAS,MAAM,cAAgB,OAC/B,SAAS,KAAK,YAAYA,CAAQ,EAClCA,EAAS,OAAA,EACT,MAAMC,EAAU,SAAS,YAAY,MAAM,EAC3C,gBAAS,KAAK,YAAYD,CAAQ,EAC3BC,CACT,CACF,CC7GO,SAASC,EAAmBH,EAAcI,EAAqC,CACpF,MAAMC,EAAYD,EAAO,WAAa,IAChCE,EAAUF,EAAO,SAAW;AAAA,EAG5BG,EAAiBP,EAAK,QAAQ,QAAS;AAAA,CAAI,EAAE,QAAQ,MAAO;AAAA,CAAI,EAGhEQ,EAAmB,CAAA,EACzB,IAAIC,EAAuB,CAAA,EACvBC,EAAc,GACdC,EAAW,GAEf,QAASC,EAAI,EAAGA,EAAIL,EAAe,OAAQK,IAAK,CAC9C,MAAMC,EAAON,EAAeK,CAAC,EAEzBC,IAAS,KAAO,CAACF,EAEnBA,EAAW,GACFE,IAAS,KAAOF,EAErBJ,EAAeK,EAAI,CAAC,IAAM,KAC5BF,GAAe,IACfE,KAGAD,EAAW,GAEJE,IAAS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,GAAIF,GAAaA,EAAU,OAAO,OAAS,EAAG,CAC5C,MAAMO,EAAcP,EAAU,OAAOA,EAAU,OAAO,OAAS,CAAC,EAC5DA,EAAU,OAAS,MACrBI,EAAQ,CAAE,SAAUG,EAAY,KAAK,IAAK,SAAU,EAAG,OAAQA,EAAY,GAAG,IAAK,OAAQL,CAAA,EAE3FE,EAAQ,CACN,SAAUG,EAAY,KAAK,IAC3B,SAAUA,EAAY,KAAK,IAC3B,OAAQA,EAAY,GAAG,IACvB,OAAQA,EAAY,GAAG,GAAA,CAG7B,CAEA,MAAMG,EAAS,KAAKC,GAAgBP,CAAK,EACzC,aAAM/C,EAAgBqD,EAAO,IAAI,EACjC,KAAK,WAAa,CAAE,KAAMA,EAAO,KAAM,UAAW,KAAK,KAAI,EACpDA,EAAO,IAChB,CAOA,MAAM,SAAS6B,EAAoC,CACjD,GAAIA,EAAQ,SAAW,EAAG,MAAO,GAEjC,MAAMC,EAAgB,CAAC,GAAGD,CAAO,EAAE,KAAK,CAACE,EAAGC,IAAMD,EAAIC,CAAC,EACjDxC,EAAU,KAAK,QAAQ,OAAS,EAIhCE,EAAQ,CACZ,SAAUoC,EAAc,CAAC,EACzB,SAAU,EACV,OAAQA,EAAcA,EAAc,OAAS,CAAC,EAC9C,OAAQtC,CAAA,EAGJQ,EAAS,KAAKC,GAAgBP,CAAK,EACzC,aAAM/C,EAAgBqD,EAAO,IAAI,EACjC,KAAK,WAAa,CAAE,KAAMA,EAAO,KAAM,UAAW,KAAK,KAAI,EACpDA,EAAO,IAChB,CAMA,MAAM,OAAoC,CACxC,MAAMpD,EAAO,MAAMe,EAAA,EACnB,OAAKf,EACEG,EAAmBH,EAAM,KAAK,MAAM,EADzB,IAEpB,CAMA,eAA4D,CAC1D,OAAO,KAAK,UACd,CAEF"}
|
|
1
|
+
{"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts","../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../libs/grid/src/lib/plugins/clipboard/ClipboardPlugin.ts"],"sourcesContent":["/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.meta?.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n","/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { ClipboardConfig } from './types';\n\n/** Parameters for building clipboard text */\nexport interface CopyParams {\n /** All grid rows */\n rows: unknown[];\n /** Column configurations */\n columns: ColumnConfig[];\n /** Selected row indices */\n selectedIndices: Set<number> | number[];\n /** Clipboard configuration */\n config: ClipboardConfig;\n}\n\n/**\n * Format a cell value for clipboard output.\n *\n * Uses custom processCell if provided, otherwise applies default formatting:\n * - null/undefined → empty string\n * - Date → ISO string\n * - Object → JSON string\n * - Other → String conversion with optional quoting\n *\n * @param value - The cell value to format\n * @param field - The field name\n * @param row - The full row object\n * @param config - Clipboard configuration\n * @returns Formatted string value\n */\nexport function formatCellValue(value: unknown, field: string, row: unknown, config: ClipboardConfig): string {\n if (config.processCell) {\n return config.processCell(value, field, row);\n }\n\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n\n const str = String(value);\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Quote if contains delimiter, newline, or quotes (or if quoteStrings is enabled)\n if (config.quoteStrings || str.includes(delimiter) || str.includes(newline) || str.includes('\"')) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build clipboard text from selected rows and columns.\n *\n * @param params - Copy parameters including rows, columns, selection, and config\n * @returns Tab-separated (or custom delimiter) text ready for clipboard\n */\nexport function buildClipboardText(params: CopyParams): string {\n const { rows, columns, selectedIndices, config } = params;\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Filter to visible columns (not hidden, not internal __ prefixed)\n const visibleColumns = columns.filter((c) => !c.hidden && !c.field.startsWith('__'));\n\n const lines: string[] = [];\n\n // Add header row if configured\n if (config.includeHeaders) {\n const headerCells = visibleColumns.map((c) => {\n const header = c.header || c.field;\n // Quote headers if they contain special characters\n if (header.includes(delimiter) || header.includes(newline) || header.includes('\"')) {\n return `\"${header.replace(/\"/g, '\"\"')}\"`;\n }\n return header;\n });\n lines.push(headerCells.join(delimiter));\n }\n\n // Convert indices to sorted array\n const indices = selectedIndices instanceof Set ? [...selectedIndices] : selectedIndices;\n const sortedIndices = [...indices].sort((a, b) => a - b);\n\n // Build data rows\n for (const idx of sortedIndices) {\n const row = rows[idx];\n if (!row) continue;\n\n const cells = visibleColumns.map((col) =>\n formatCellValue((row as Record<string, unknown>)[col.field], col.field, row, config)\n );\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n}\n\n/**\n * Copy text to the system clipboard.\n *\n * Uses the modern Clipboard API when available, with fallback\n * to execCommand for older browsers.\n *\n * @param text - The text to copy\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n // Fallback for older browsers or when Clipboard API is not available\n const textarea = document.createElement('textarea');\n textarea.value = text;\n textarea.style.position = 'fixed';\n textarea.style.opacity = '0';\n textarea.style.pointerEvents = 'none';\n document.body.appendChild(textarea);\n textarea.select();\n const success = document.execCommand('copy');\n document.body.removeChild(textarea);\n return success;\n }\n}\n","/**\n * Clipboard Paste Logic\n *\n * Pure functions for reading and parsing clipboard data.\n */\n\nimport type { ClipboardConfig } from './types';\n\n/**\n * Parse clipboard text into a 2D array of cell values.\n *\n * Handles:\n * - Quoted values (with escaped double quotes \"\")\n * - Multi-line quoted values (newlines within quotes are preserved)\n * - Custom delimiters and newlines\n * - Empty lines (filtered out only if they contain no data)\n *\n * @param text - Raw clipboard text\n * @param config - Clipboard configuration\n * @returns 2D array where each sub-array is a row of cell values\n */\nexport function parseClipboardText(text: string, config: ClipboardConfig): string[][] {\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Handle Windows CRLF line endings\n const normalizedText = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n // Parse the entire text handling quoted fields that may span multiple lines\n const rows: string[][] = [];\n let currentRow: string[] = [];\n let currentCell = '';\n let inQuotes = false;\n\n for (let i = 0; i < normalizedText.length; i++) {\n const char = normalizedText[i];\n\n if (char === '\"' && !inQuotes) {\n // Start of quoted field\n inQuotes = true;\n } else if (char === '\"' && inQuotes) {\n // Check for escaped quote (\"\")\n if (normalizedText[i + 1] === '\"') {\n currentCell += '\"';\n i++; // Skip the second quote\n } else {\n // End of quoted field\n inQuotes = false;\n }\n } else if (char === delimiter && !inQuotes) {\n // Field separator\n currentRow.push(currentCell);\n currentCell = '';\n } else if (char === newline && !inQuotes) {\n // Row separator (only if not inside quotes)\n currentRow.push(currentCell);\n currentCell = '';\n // Only add non-empty rows (at least one non-empty cell or multiple cells)\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n currentRow = [];\n } else {\n currentCell += char;\n }\n }\n\n // Handle the last cell and row\n currentRow.push(currentCell);\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n\n return rows;\n}\n\n/**\n * Read text from the system clipboard.\n *\n * Uses the modern Clipboard API. Returns empty string if\n * the API is not available or permission is denied.\n *\n * @returns Promise resolving to clipboard text or empty string\n */\nexport async function readFromClipboard(): Promise<string> {\n try {\n return await navigator.clipboard.readText();\n } catch {\n // Permission denied or API not available\n return '';\n }\n}\n","/**\n * Clipboard Plugin Types\n *\n * Type definitions for clipboard copy/paste functionality.\n */\n\nimport type { GridElement } from '../../core/plugin/base-plugin';\n\n/**\n * Custom paste handler function.\n *\n * @param detail - The parsed paste data with target and field info\n * @param grid - The grid element to update\n * @returns `false` to prevent the default paste behavior, or `void`/`true` to allow it\n *\n * @example\n * ```ts\n * // Custom handler that validates before pasting\n * new ClipboardPlugin({\n * pasteHandler: (detail, grid) => {\n * if (!detail.target) return false;\n * // Apply custom validation/transformation...\n * applyPasteData(detail, grid);\n * return false; // We handled it, skip default\n * }\n * })\n * ```\n */\nexport type PasteHandler = (detail: PasteDetail, grid: GridElement) => boolean | void;\n\n/**\n * Options for programmatic copy operations.\n *\n * Allows callers to control exactly which columns and rows are included\n * in a copy, independently of the current selection state.\n *\n * @example Copy specific columns from selected rows\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * // User selected rows 0, 2, 4 via a dialog, chose columns to include\n * const text = await clipboard.copy({\n * rowIndices: [0, 2, 4],\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * ```\n */\nexport interface CopyOptions {\n /** Specific column fields to include. If omitted, uses current selection or all visible columns. */\n columns?: string[];\n /** Specific row indices to copy. If omitted, uses current selection or all rows. */\n rowIndices?: number[];\n /** Include column headers in copied text. Defaults to the plugin config value. */\n includeHeaders?: boolean;\n /** Column delimiter override. Defaults to the plugin config value. */\n delimiter?: string;\n /** Row delimiter override. Defaults to the plugin config value. */\n newline?: string;\n /** Custom cell value processor for this operation. Overrides the plugin config's `processCell`. */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n}\n\n/** Configuration options for the clipboard plugin */\nexport interface ClipboardConfig {\n /** Include column headers in copied text (default: false) */\n includeHeaders?: boolean;\n /** Column delimiter character (default: '\\t' for tab) */\n delimiter?: string;\n /** Row delimiter/newline character (default: '\\n') */\n newline?: string;\n /** Wrap string values with quotes (default: false) */\n quoteStrings?: boolean;\n /** Custom cell value processor for copy operations */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n /**\n * Custom paste handler. By default, the plugin applies pasted data to `grid.rows`\n * starting at the target cell.\n *\n * - Set to a custom function to handle paste yourself\n * - Set to `null` to disable auto-paste (event still fires)\n * - Return `false` from handler to prevent default behavior\n *\n * @default defaultPasteHandler (auto-applies paste data)\n */\n pasteHandler?: PasteHandler | null;\n}\n\n/** Internal state managed by the clipboard plugin */\nexport interface ClipboardState {\n /** The last copied text (for reference/debugging) */\n lastCopied: string | null;\n}\n\n/** Event detail emitted after a successful copy operation */\nexport interface CopyDetail {\n /** The text that was copied to clipboard */\n text: string;\n /** Number of rows copied */\n rowCount: number;\n /** Number of columns copied */\n columnCount: number;\n}\n\n/** Target cell coordinates and bounds for paste operations */\nexport interface PasteTarget {\n /** Target row index (top-left of paste area) */\n row: number;\n /** Target column index (top-left of paste area) */\n col: number;\n /** Target column field name (for easy data mapping) */\n field: string;\n /**\n * Selection bounds that constrain the paste area.\n * If set, paste data will be clipped to fit within these bounds.\n * If null, paste expands freely from the target cell.\n */\n bounds: {\n /** End row index (inclusive) */\n endRow: number;\n /** End column index (inclusive) */\n endCol: number;\n } | null;\n}\n\n/** Event detail emitted after a paste operation */\nexport interface PasteDetail {\n /** Parsed rows from clipboard (2D array of cell values) */\n rows: string[][];\n /** Raw text that was pasted */\n text: string;\n /** The target cell where paste starts (top-left of paste area). Null if no cell is selected. */\n target: PasteTarget | null;\n /**\n * Column fields for each column in the paste range, starting from target.col.\n * Useful for mapping parsed cell values to data fields.\n * Length matches the width of the pasted data (or available columns, whichever is smaller).\n */\n fields: string[];\n}\n\n/**\n * Default paste handler that applies pasted data to grid.rows.\n *\n * This is the built-in handler used when no custom `pasteHandler` is configured.\n * It clones the rows array for immutability and applies values starting at the target cell.\n *\n * Behavior:\n * - Single cell selection: paste expands freely, adds new rows if needed\n * - Range/row selection: paste is clipped to fit within selection bounds\n * - Non-editable columns: values are skipped (column alignment preserved)\n *\n * @param detail - The parsed paste data from clipboard\n * @param grid - The grid element to update\n */\nexport function defaultPasteHandler(detail: PasteDetail, grid: GridElement): void {\n const { rows: pastedRows, target, fields } = detail;\n\n // No target = nothing to do\n if (!target) return;\n\n // Get current rows and columns from grid\n const currentRows = grid.rows as Record<string, unknown>[];\n const columns = grid.effectiveConfig.columns ?? [];\n const allFields = columns.map((col) => col.field);\n\n // Build a map of field -> editable for quick lookup\n const editableMap = new Map<string, boolean>();\n columns.forEach((col) => {\n editableMap.set(col.field, col.editable === true);\n });\n\n // Clone data for immutability\n const newRows = [...currentRows];\n\n // Calculate row bounds\n const maxPasteRow = target.bounds ? target.bounds.endRow : Infinity;\n\n // Apply pasted data starting at target cell\n pastedRows.forEach((rowData, rowOffset) => {\n const targetRowIndex = target.row + rowOffset;\n\n // Stop if we've exceeded the selection bounds\n if (targetRowIndex > maxPasteRow) return;\n\n // Only grow array if no bounds (single cell selection)\n if (!target.bounds) {\n while (targetRowIndex >= newRows.length) {\n const emptyRow: Record<string, unknown> = {};\n allFields.forEach((field) => (emptyRow[field] = ''));\n newRows.push(emptyRow);\n }\n } else if (targetRowIndex >= newRows.length) {\n // With bounds, don't paste beyond existing rows\n return;\n }\n\n // Clone the target row and apply values\n newRows[targetRowIndex] = { ...newRows[targetRowIndex] };\n rowData.forEach((cellValue, colOffset) => {\n // fields array is already constrained by bounds in ClipboardPlugin\n const field = fields[colOffset];\n if (field && editableMap.get(field)) {\n // Only paste into editable columns\n newRows[targetRowIndex][field] = cellValue;\n }\n });\n });\n\n // Update grid with new data\n grid.rows = newRows;\n}\n","/**\n * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatValueAsText, resolveColumns, resolveRows } from '../shared/data-collection';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type CopyOptions,\n type PasteDetail,\n type PasteTarget,\n} from './types';\n\n/**\n * Clipboard Plugin for tbw-grid\n *\n * Brings familiar copy/cut/paste functionality with full keyboard shortcut support\n * (Ctrl+C, Ctrl+X, Ctrl+V). Handles single cells, multi-cell selections, and integrates\n * seamlessly with Excel and other spreadsheet applications via tab-delimited output.\n *\n * > **Optional Dependency:** Works best with SelectionPlugin for copying/pasting selected\n * > cells. Without SelectionPlugin, copies the entire grid and pastes at row 0, column 0.\n *\n * ## Installation\n *\n * ```ts\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `includeHeaders` | `boolean` | `false` | Include column headers in copied data |\n * | `delimiter` | `string` | `'\\t'` | Column delimiter (tab for Excel compatibility) |\n * | `newline` | `string` | `'\\n'` | Row delimiter |\n * | `quoteStrings` | `boolean` | `false` | Wrap string values in quotes |\n * | `processCell` | `(value, field, row) => string` | - | Custom cell value processor |\n * | `pasteHandler` | `PasteHandler \\| null` | `defaultPasteHandler` | Custom paste handler |\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `copy` | `(options?: CopyOptions) => Promise<string>` | Copy to clipboard with optional column/row control |\n * | `copyRows` | `(indices, options?) => Promise<string>` | Copy specific rows to clipboard |\n * | `paste` | `() => Promise<string[][] \\| null>` | Read and parse clipboard content |\n * | `getSelectionAsText` | `(options?: CopyOptions) => string` | Get clipboard text without writing to clipboard |\n * | `getLastCopied` | `() => { text, timestamp } \\| null` | Get info about last copy operation |\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see {@link SelectionPlugin} for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n // Cast to HTMLElement since GridElement is an interface\n (grid as unknown as HTMLElement).addEventListener(\n 'paste',\n (e: Event) => this.#handleNativePaste(e as ClipboardEvent),\n { signal: this.disconnectSignal },\n );\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n this.#handleCopy(event.target as HTMLElement);\n return true; // Prevent default browser behavior\n }\n\n // For paste, we do NOT return true - let the native paste event fire\n // so we can access clipboardData synchronously in #handleNativePaste\n return false;\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Handle copy operation from keyboard shortcut.\n *\n * For keyboard-triggered copies, respects the current selection or\n * falls back to the focused cell from the DOM.\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n\n // Selection plugin exists but nothing selected → try focused cell from DOM\n if (selection && selection.ranges.length === 0) {\n const focused = this.#getFocusedCellFromDOM(target);\n if (!focused) return;\n const col = this.columns[focused.col];\n if (!col) return;\n this.copy({ rowIndices: [focused.row], columns: [col.field] });\n return;\n }\n\n // Delegate to the public copy() method (selection or full grid)\n this.copy();\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection via query\n const selection = this.#getSelection();\n const firstRange = selection?.ranges?.[0];\n\n // Determine target cell and bounds\n const targetRow = firstRange?.from.row ?? 0;\n const targetCol = firstRange?.from.col ?? 0;\n\n // Check if multi-cell selection (range with different start/end)\n const isMultiCell =\n firstRange &&\n (selection?.mode === 'range' || selection?.mode === 'row') &&\n (firstRange.from.row !== firstRange.to.row || firstRange.from.col !== firstRange.to.col);\n\n const bounds = isMultiCell ? { endRow: firstRange.to.row, endCol: firstRange.to.col } : null;\n const maxCol = bounds?.endCol ?? this.columns.length - 1;\n\n // Build target info\n const column = this.columns[targetCol];\n const target: PasteTarget | null = column ? { row: targetRow, col: targetCol, field: column.field, bounds } : null;\n\n // Build field list for paste width (constrained by bounds if set)\n const fields: string[] = [];\n const pasteWidth = parsed[0]?.length ?? 0;\n for (let i = 0; i < pasteWidth && targetCol + i <= maxCol; i++) {\n const col = this.columns[targetCol + i];\n if (col && !col.hidden) {\n fields.push(col.field);\n }\n }\n\n const detail: PasteDetail = { rows: parsed, text, target, fields };\n\n // Emit the event for any listeners\n this.emit<PasteDetail>('paste', detail);\n\n // Apply paste data using the configured handler (or default)\n this.#applyPasteHandler(detail);\n }\n\n /**\n * Apply the paste handler to update grid data.\n *\n * Uses the configured `pasteHandler`, or the default handler if not specified.\n * Set `pasteHandler: null` in config to disable auto-paste.\n */\n #applyPasteHandler(detail: PasteDetail): void {\n if (!this.grid) return;\n\n const { pasteHandler } = this.config;\n\n // pasteHandler: null means explicitly disabled\n if (pasteHandler === null) return;\n\n // Use custom handler or default\n const handler = pasteHandler ?? defaultPasteHandler;\n handler(detail, this.grid);\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection');\n return responses?.[0];\n }\n\n /**\n * Resolve columns and rows to include based on options and/or current selection.\n *\n * Priority for columns:\n * 1. `options.columns` (explicit field list)\n * 2. Selection range column bounds (range/cell mode only)\n * 3. All visible non-utility columns\n *\n * Priority for rows:\n * 1. `options.rowIndices` (explicit indices)\n * 2. Selection range row bounds\n * 3. All rows\n */\n #resolveData(options?: CopyOptions): { columns: ColumnConfig[]; rows: Record<string, unknown>[] } {\n const selection = this.#getSelection();\n\n // --- Columns ---\n let columns: ColumnConfig[];\n if (options?.columns) {\n // Caller specified exact fields\n columns = resolveColumns(this.columns, options.columns);\n } else if (selection?.ranges.length && selection.mode !== 'row') {\n // Range/cell selection: restrict to selection column bounds\n const range = selection.ranges[selection.ranges.length - 1];\n const minCol = Math.min(range.from.col, range.to.col);\n const maxCol = Math.max(range.from.col, range.to.col);\n columns = resolveColumns(this.columns.slice(minCol, maxCol + 1));\n } else {\n // Row selection or no selection: all visible columns\n columns = resolveColumns(this.columns);\n }\n\n // --- Rows ---\n let rows: Record<string, unknown>[];\n if (options?.rowIndices) {\n // Caller specified exact row indices\n rows = resolveRows(this.rows as Record<string, unknown>[], options.rowIndices);\n } else if (selection?.ranges.length) {\n // Selection range: extract contiguous row range\n const range = selection.ranges[selection.ranges.length - 1];\n const minRow = Math.min(range.from.row, range.to.row);\n const maxRow = Math.max(range.from.row, range.to.row);\n rows = [];\n for (let r = minRow; r <= maxRow; r++) {\n const row = this.rows[r] as Record<string, unknown> | undefined;\n if (row) rows.push(row);\n }\n } else {\n // No selection: all rows\n rows = this.rows as Record<string, unknown>[];\n }\n\n return { columns, rows };\n }\n\n /**\n * Build delimited text from resolved columns and rows.\n */\n #buildText(columns: ColumnConfig[], rows: Record<string, unknown>[], options?: CopyOptions): string {\n const delimiter = options?.delimiter ?? this.config.delimiter ?? '\\t';\n const newline = options?.newline ?? this.config.newline ?? '\\n';\n const includeHeaders = options?.includeHeaders ?? this.config.includeHeaders ?? false;\n const processCell = options?.processCell ?? this.config.processCell;\n\n const lines: string[] = [];\n\n // Header row\n if (includeHeaders) {\n lines.push(columns.map((c) => c.header || c.field).join(delimiter));\n }\n\n // Data rows\n for (const row of rows) {\n const cells = columns.map((col) => {\n const value = row[col.field];\n if (processCell) return processCell(value, col.field, row);\n return formatValueAsText(value);\n });\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n }\n\n /**\n * Get focused cell coordinates from DOM.\n * Used as fallback when SelectionPlugin has no selection.\n */\n #getFocusedCellFromDOM(target: HTMLElement): { row: number; col: number } | null {\n const cell = target.closest('[data-field-cache]') as HTMLElement | null;\n if (!cell) return null;\n\n const field = cell.dataset.fieldCache;\n const rowIndexStr = cell.dataset.row;\n if (!field || !rowIndexStr) return null;\n\n const row = parseInt(rowIndexStr, 10);\n if (isNaN(row)) return null;\n\n const col = this.columns.findIndex((c) => c.field === field);\n if (col === -1) return null;\n\n return { row, col };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the text representation of the current selection (or specified data)\n * without writing to the system clipboard.\n *\n * Useful for previewing what would be copied, or for feeding the text into\n * a custom UI (e.g., a \"copy with column picker\" dialog).\n *\n * @param options - Control which columns/rows to include\n * @returns Delimited text, or empty string if nothing to copy\n *\n * @example Get text for specific columns\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * const text = clipboard.getSelectionAsText({\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * console.log(text);\n * // \"Name\\tEmail\\nAlice\\talice@example.com\\n...\"\n * ```\n */\n getSelectionAsText(options?: CopyOptions): string {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) return '';\n return this.#buildText(columns, rows, options);\n }\n\n /**\n * Copy data to the system clipboard.\n *\n * Without options, copies the current selection (or entire grid if no selection).\n * With options, copies exactly the specified columns and/or rows — ideal for\n * \"copy with column picker\" workflows where the user selects rows first,\n * then chooses which columns to include via a dialog.\n *\n * @param options - Control which columns/rows to include\n * @returns The copied text\n *\n * @example Copy current selection (default)\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * await clipboard.copy();\n * ```\n *\n * @example Copy specific columns from specific rows\n * ```ts\n * // User selected rows in the grid, then picked columns in a dialog\n * const selectedRowIndices = [0, 3, 7];\n * const chosenColumns = ['name', 'department', 'salary'];\n * await clipboard.copy({\n * rowIndices: selectedRowIndices,\n * columns: chosenColumns,\n * includeHeaders: true,\n * });\n * ```\n */\n async copy(options?: CopyOptions): Promise<string> {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) return '';\n\n const text = this.#buildText(columns, rows, options);\n await copyToClipboard(text);\n this.lastCopied = { text, timestamp: Date.now() };\n this.emit<CopyDetail>('copy', {\n text,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n return text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n *\n * Convenience wrapper around {@link copy} for row-based workflows.\n * Supports non-contiguous row indices (e.g., `[0, 3, 7]`).\n *\n * @param indices - Array of row indices to copy\n * @param options - Additional copy options (columns, headers, etc.)\n * @returns The copied text\n *\n * @example\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * // Copy only rows 0 and 5, including just name and email columns\n * await clipboard.copyRows([0, 5], { columns: ['name', 'email'] });\n * ```\n */\n async copyRows(indices: number[], options?: Omit<CopyOptions, 'rowIndices'>): Promise<string> {\n if (indices.length === 0) return '';\n return this.copy({ ...options, rowIndices: indices });\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, CopyOptions, PasteDetail } from './types';\n"],"names":["resolveColumns","columns","fields","onlyVisible","result","c","fieldSet","resolveRows","rows","indices","a","b","i","r","formatValueAsText","value","copyToClipboard","text","textarea","success","parseClipboardText","config","delimiter","newline","normalizedText","currentRow","currentCell","inQuotes","char","readFromClipboard","defaultPasteHandler","detail","grid","pastedRows","target","currentRows","allFields","col","editableMap","newRows","maxPasteRow","rowData","rowOffset","targetRowIndex","emptyRow","field","cellValue","colOffset","ClipboardPlugin","BaseGridPlugin","e","#handleNativePaste","event","#handleCopy","selection","#getSelection","focused","#getFocusedCellFromDOM","parsed","firstRange","targetRow","targetCol","bounds","maxCol","column","pasteWidth","#applyPasteHandler","pasteHandler","#resolveData","options","range","minCol","minRow","maxRow","row","#buildText","includeHeaders","processCell","lines","cells","cell","rowIndexStr"],"mappings":"qUAwBO,SAASA,EACdC,EACAC,EACAC,EAAc,GACE,CAChB,IAAIC,EAASH,EAMb,GAJIE,IACFC,EAASA,EAAO,OAAQC,GAAM,CAACA,EAAE,QAAU,CAACA,EAAE,MAAM,WAAW,IAAI,GAAKA,EAAE,MAAM,UAAY,EAAI,GAG9FH,GAAQ,OAAQ,CAClB,MAAMI,EAAW,IAAI,IAAIJ,CAAM,EAC/BE,EAASA,EAAO,OAAQC,GAAMC,EAAS,IAAID,EAAE,KAAK,CAAC,CACrD,CAEA,OAAOD,CACT,CASO,SAASG,EAAeC,EAAoBC,EAAyB,CAC1E,OAAKA,GAAS,OAEP,CAAC,GAAGA,CAAO,EACf,KAAK,CAACC,EAAGC,IAAMD,EAAIC,CAAC,EACpB,IAAKC,GAAMJ,EAAKI,CAAC,CAAC,EAClB,OAAQC,GAAcA,GAAK,IAAI,EALLL,CAM/B,CAWO,SAASM,EAAkBC,EAAwB,CACxD,OAAIA,GAAS,KAAa,GACtBA,aAAiB,KAAaA,EAAM,YAAA,EACpC,OAAOA,GAAU,SAAiB,KAAK,UAAUA,CAAK,EACnD,OAAOA,CAAK,CACrB,CCwCA,eAAsBC,EAAgBC,EAAgC,CACpE,GAAI,CACF,aAAM,UAAU,UAAU,UAAUA,CAAI,EACjC,EACT,MAAQ,CAEN,MAAMC,EAAW,SAAS,cAAc,UAAU,EAClDA,EAAS,MAAQD,EACjBC,EAAS,MAAM,SAAW,QAC1BA,EAAS,MAAM,QAAU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G,EAAmBH,EAAM,KAAK,MAAM,EADzB,IAEpB,CAMA,eAA4D,CAC1D,OAAO,KAAK,UACd,CAEF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(m,
|
|
1
|
+
(function(m,p){typeof exports=="object"&&typeof module<"u"?p(exports,require("../../core/plugin/base-plugin"),require("../../core/types")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/types"],p):(m=typeof globalThis<"u"?globalThis:m||self,p(m.TbwGridPlugin_contextMenu={},m.TbwGrid,m.TbwGrid))})(this,(function(m,p,I){"use strict";const x="@layer tbw-plugins{.tbw-context-menu{position:fixed;background:var(--tbw-context-menu-bg, var(--tbw-color-panel-bg));color:var(--tbw-context-menu-fg, var(--tbw-color-fg));border:1px solid var(--tbw-context-menu-border, var(--tbw-color-border));border-radius:var(--tbw-context-menu-radius, var(--tbw-border-radius));box-shadow:var(--tbw-context-menu-shadow, 0 2px 10px var(--tbw-color-shadow));min-width:var(--tbw-context-menu-min-width, var(--tbw-menu-min-width));padding:var(--tbw-spacing-xs) 0;z-index:10000;font-size:var(--tbw-context-menu-font-size, var(--tbw-font-size-sm));font-family:var(--tbw-context-menu-font-family, var(--tbw-font-family))}.tbw-context-menu-item{display:flex;align-items:center;padding:var(--tbw-context-menu-item-padding, var(--tbw-menu-item-padding));cursor:pointer;gap:var(--tbw-context-menu-item-gap, var(--tbw-menu-item-gap))}.tbw-context-menu-item:hover:not(.disabled){background:var(--tbw-context-menu-hover, var(--tbw-color-row-hover))}.tbw-context-menu-item.disabled{opacity:.5;cursor:default}.tbw-context-menu-item.danger{color:var(--tbw-context-menu-danger, var(--tbw-color-danger))}.tbw-context-menu-icon{width:var(--tbw-context-menu-icon-size, var(--tbw-icon-size));text-align:center}.tbw-context-menu-label{flex:1}.tbw-context-menu-shortcut{color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted));font-size:var(--tbw-context-menu-shortcut-size, var(--tbw-font-size-xs))}.tbw-context-menu-arrow{font-size:var(--tbw-context-menu-arrow-size, var(--tbw-font-size-2xs));color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted))}.tbw-context-menu-separator{height:1px;background:var(--tbw-context-menu-border, var(--tbw-color-border));margin:var(--tbw-spacing-xs) 0}}";function g(s,n){return(typeof s=="function"?s(n):s).filter(e=>!(e.hidden===!0||typeof e.hidden=="function"&&e.hidden(n)))}function z(s,n){return s.disabled===!0?!0:typeof s.disabled=="function"?s.disabled(n):!1}function v(s,n,r,e=I.DEFAULT_GRID_ICONS.submenuArrow){const i=document.createElement("div");i.className="tbw-context-menu",i.setAttribute("role","menu");for(const o of s){if(o.separator){const l=document.createElement("div");l.className="tbw-context-menu-separator",l.setAttribute("role","separator"),i.appendChild(l);continue}const t=document.createElement("div");t.className="tbw-context-menu-item",o.cssClass&&t.classList.add(o.cssClass),t.setAttribute("role","menuitem"),t.setAttribute("data-id",o.id);const u=z(o,n);if(u&&(t.classList.add("disabled"),t.setAttribute("aria-disabled","true")),o.icon){const l=document.createElement("span");l.className="tbw-context-menu-icon",l.innerHTML=o.icon,t.appendChild(l)}const a=document.createElement("span");if(a.className="tbw-context-menu-label",a.textContent=o.name,t.appendChild(a),o.shortcut){const l=document.createElement("span");l.className="tbw-context-menu-shortcut",l.textContent=o.shortcut,t.appendChild(l)}if(o.subMenu?.length){const l=document.createElement("span");l.className="tbw-context-menu-arrow",typeof e=="string"?l.innerHTML=e:e instanceof HTMLElement&&l.appendChild(e.cloneNode(!0)),t.appendChild(l),t.addEventListener("mouseenter",()=>{if(t.querySelector(".tbw-context-menu")||!o.subMenu)return;const f=g(o.subMenu,n),d=v(f,n,r,e);d.classList.add("tbw-context-submenu"),d.style.position="absolute",d.style.left="100%",d.style.top="0",t.style.position="relative",t.appendChild(d)}),t.addEventListener("mouseleave",()=>{const c=t.querySelector(".tbw-context-menu");c&&c.remove()})}!u&&o.action&&!o.subMenu&&t.addEventListener("click",l=>{l.stopPropagation(),r(o)}),i.appendChild(t)}return i}function S(s,n,r){s.style.position="fixed",s.style.left=`${n}px`,s.style.top=`${r}px`,s.style.visibility="hidden",s.style.zIndex="10000";const e=s.getBoundingClientRect(),i=window.innerWidth,o=window.innerHeight;let t=n,u=r;n+e.width>i&&(t=n-e.width),r+e.height>o&&(u=r-e.height),t=Math.max(0,t),u=Math.max(0,u),s.style.left=`${t}px`,s.style.top=`${u}px`,s.style.visibility="visible"}let w=null,h=null,b=null,y=0;const E=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:s=>{s.grid?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:s=>{s.grid?.plugins?.export?.exportCsv?.()}}];class C extends p.BaseGridPlugin{name="contextMenu";get defaultConfig(){return{items:E}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(n){super.attach(n),this.installGlobalHandlers(),y++}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,this.uninstallGlobalHandlers()}syncSelectionOnContextMenu(n){if(n<0)return[];const e=this.grid?.query("getSelectedRowIndices")?.[0];return e?e.includes(n)?e:(this.grid?.query("selectRows",[n]),[n]):[n]}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size"];copyGridStyles(n){const r=this.gridElement;if(!r)return;const e=getComputedStyle(r),i=[],o=e.getPropertyValue("color-scheme").trim();o&&i.push(`color-scheme: ${o}`);for(const t of C.CSS_VARS_TO_COPY){const u=e.getPropertyValue(t).trim();u&&i.push(`${t}: ${u}`)}if(i.length>0){const t=n.getAttribute("style")||"";n.setAttribute("style",t+i.join("; ")+";")}}installGlobalHandlers(){!b&&typeof document<"u"&&typeof x=="string"&&x&&(b=document.createElement("style"),b.id="tbw-context-menu-styles",b.textContent=x,document.head.appendChild(b)),w||(w=()=>{document.querySelectorAll(".tbw-context-menu").forEach(r=>r.remove())},document.addEventListener("click",w)),h||(h=n=>{n.key==="Escape"&&document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())},document.addEventListener("keydown",h))}uninstallGlobalHandlers(){y--,!(y>0)&&(w&&(document.removeEventListener("click",w),w=null),h&&(document.removeEventListener("keydown",h),h=null),b&&(b.remove(),b=null))}afterRender(){const n=this.gridElement;if(!n)return;const r=n.querySelector(".tbw-grid-root");r&&r.getAttribute("data-context-menu-bound")!=="true"&&(r.setAttribute("data-context-menu-bound","true"),r.addEventListener("contextmenu",e=>{const i=e;i.preventDefault();const o=i.target,t=o.closest("[data-row][data-col]"),u=o.closest(".header-cell");let a;if(t){const c=parseInt(t.getAttribute("data-row")??"-1",10),f=parseInt(t.getAttribute("data-col")??"-1",10),d=this.columns[f],M=this.rows[c],O=this.syncSelectionOnContextMenu(c);a={row:M,rowIndex:c,column:d,columnIndex:f,field:d?.field??"",value:M?.[d?.field]??null,isHeader:!1,event:i,selectedRows:O}}else if(u){const c=parseInt(u.getAttribute("data-col")??"-1",10),f=this.columns[c];a={row:null,rowIndex:-1,column:f,columnIndex:c,field:f?.field??"",value:null,isHeader:!0,event:i,selectedRows:[]}}else return;this.params=a,this.position={x:i.clientX,y:i.clientY};const l=g(this.config.items??E,a);l.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=v(l,a,c=>{c.action&&c.action(a),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),S(this.menuElement,i.clientX,i.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:a,items:l}))}))}showMenu(n,r,e){const i={row:e.row??null,rowIndex:e.rowIndex??-1,column:e.column??null,columnIndex:e.columnIndex??-1,field:e.field??"",value:e.value??null,isHeader:e.isHeader??!1,event:e.event??new MouseEvent("contextmenu"),selectedRows:e.selectedRows??[]},o=g(this.config.items??E,i);this.menuElement&&this.menuElement.remove(),this.menuElement=v(o,i,t=>{t.action&&t.action(i),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),S(this.menuElement,n,r),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}m.ContextMenuPlugin=C,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
|
|
2
2
|
//# sourceMappingURL=context-menu.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-menu.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/context-menu/menu.ts","../../../../../libs/grid/src/lib/plugins/context-menu/ContextMenuPlugin.ts"],"sourcesContent":["/**\n * Context Menu Rendering Logic\n *\n * Pure functions for building and positioning context menus.\n */\n\nimport type { IconValue } from '../../core/types';\nimport { DEFAULT_GRID_ICONS } from '../../core/types';\nimport type { ContextMenuItem, ContextMenuParams } from './types';\n\n/**\n * Build the visible menu items by resolving dynamic items and filtering hidden ones.\n *\n * @param items - Menu items configuration (array or factory function)\n * @param params - Context menu parameters for evaluating dynamic properties\n * @returns Filtered array of visible menu items\n */\nexport function buildMenuItems(\n items: ContextMenuItem[] | ((params: ContextMenuParams) => ContextMenuItem[]),\n params: ContextMenuParams\n): ContextMenuItem[] {\n const menuItems = typeof items === 'function' ? items(params) : items;\n\n return menuItems.filter((item) => {\n if (item.hidden === true) return false;\n if (typeof item.hidden === 'function' && item.hidden(params)) return false;\n return true;\n });\n}\n\n/**\n * Check if a menu item is disabled.\n *\n * @param item - The menu item to check\n * @param params - Context menu parameters for evaluating dynamic disabled state\n * @returns True if the item is disabled\n */\nexport function isItemDisabled(item: ContextMenuItem, params: ContextMenuParams): boolean {\n if (item.disabled === true) return true;\n if (typeof item.disabled === 'function') return item.disabled(params);\n return false;\n}\n\n/**\n * Create the menu DOM element from a list of menu items.\n *\n * @param items - Array of menu items to render\n * @param params - Context menu parameters for evaluating dynamic properties\n * @param onAction - Callback when a menu item action is triggered\n * @param submenuArrow - Optional custom submenu arrow icon\n * @returns The created menu element\n */\nexport function createMenuElement(\n items: ContextMenuItem[],\n params: ContextMenuParams,\n onAction: (item: ContextMenuItem) => void,\n submenuArrow: IconValue = DEFAULT_GRID_ICONS.submenuArrow\n): HTMLElement {\n const menu = document.createElement('div');\n menu.className = 'tbw-context-menu';\n menu.setAttribute('role', 'menu');\n\n for (const item of items) {\n if (item.separator) {\n const separator = document.createElement('div');\n separator.className = 'tbw-context-menu-separator';\n separator.setAttribute('role', 'separator');\n menu.appendChild(separator);\n continue;\n }\n\n const menuItem = document.createElement('div');\n menuItem.className = 'tbw-context-menu-item';\n if (item.cssClass) menuItem.classList.add(item.cssClass);\n menuItem.setAttribute('role', 'menuitem');\n menuItem.setAttribute('data-id', item.id);\n\n const disabled = isItemDisabled(item, params);\n if (disabled) {\n menuItem.classList.add('disabled');\n menuItem.setAttribute('aria-disabled', 'true');\n }\n\n if (item.icon) {\n const icon = document.createElement('span');\n icon.className = 'tbw-context-menu-icon';\n icon.innerHTML = item.icon;\n menuItem.appendChild(icon);\n }\n\n const label = document.createElement('span');\n label.className = 'tbw-context-menu-label';\n label.textContent = item.name;\n menuItem.appendChild(label);\n\n if (item.shortcut) {\n const shortcut = document.createElement('span');\n shortcut.className = 'tbw-context-menu-shortcut';\n shortcut.textContent = item.shortcut;\n menuItem.appendChild(shortcut);\n }\n\n if (item.subMenu?.length) {\n const arrow = document.createElement('span');\n arrow.className = 'tbw-context-menu-arrow';\n // Use provided submenu arrow icon (string or HTMLElement)\n if (typeof submenuArrow === 'string') {\n arrow.innerHTML = submenuArrow;\n } else if (submenuArrow instanceof HTMLElement) {\n arrow.appendChild(submenuArrow.cloneNode(true));\n }\n menuItem.appendChild(arrow);\n\n // Add submenu on hover\n menuItem.addEventListener('mouseenter', () => {\n const existingSubMenu = menuItem.querySelector('.tbw-context-menu');\n if (existingSubMenu) return;\n if (!item.subMenu) return;\n\n const subMenuItems = buildMenuItems(item.subMenu, params);\n const subMenu = createMenuElement(subMenuItems, params, onAction, submenuArrow);\n subMenu.classList.add('tbw-context-submenu');\n subMenu.style.position = 'absolute';\n subMenu.style.left = '100%';\n subMenu.style.top = '0';\n menuItem.style.position = 'relative';\n menuItem.appendChild(subMenu);\n });\n\n menuItem.addEventListener('mouseleave', () => {\n const subMenu = menuItem.querySelector('.tbw-context-menu');\n if (subMenu) subMenu.remove();\n });\n }\n\n if (!disabled && item.action && !item.subMenu) {\n menuItem.addEventListener('click', (e) => {\n e.stopPropagation();\n onAction(item);\n });\n }\n\n menu.appendChild(menuItem);\n }\n\n return menu;\n}\n\n/**\n * Position the menu at the given viewport coordinates.\n * Menu is rendered in document.body with fixed positioning for top-layer behavior.\n *\n * @param menu - The menu element to position\n * @param x - Desired X coordinate (viewport)\n * @param y - Desired Y coordinate (viewport)\n */\nexport function positionMenu(menu: HTMLElement, x: number, y: number): void {\n // Use fixed positioning for top-layer behavior\n menu.style.position = 'fixed';\n menu.style.left = `${x}px`;\n menu.style.top = `${y}px`;\n menu.style.visibility = 'hidden';\n menu.style.zIndex = '10000';\n\n // Force layout to get dimensions\n const menuRect = menu.getBoundingClientRect();\n\n // Calculate visible area within viewport\n const viewportWidth = window.innerWidth;\n const viewportHeight = window.innerHeight;\n\n let left = x;\n let top = y;\n\n // Check if menu overflows right edge of viewport\n if (x + menuRect.width > viewportWidth) {\n left = x - menuRect.width;\n }\n // Check if menu overflows bottom edge of viewport\n if (y + menuRect.height > viewportHeight) {\n top = y - menuRect.height;\n }\n\n // Ensure we don't go negative\n left = Math.max(0, left);\n top = Math.max(0, top);\n\n menu.style.left = `${left}px`;\n menu.style.top = `${top}px`;\n menu.style.visibility = 'visible';\n}\n","/**\n * Context Menu Plugin (Class-based)\n *\n * Provides right-click context menu functionality for tbw-grid.\n * Supports custom menu items, submenus, icons, shortcuts, and dynamic item generation.\n */\n\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport contextMenuStyles from './context-menu.css?inline';\nimport { buildMenuItems, createMenuElement, positionMenu } from './menu';\nimport type { ContextMenuConfig, ContextMenuItem, ContextMenuParams } from './types';\n\n/** Global click handler reference for cleanup */\nlet globalClickHandler: ((e: Event) => void) | null = null;\n/** Global keydown handler reference for cleanup */\nlet globalKeydownHandler: ((e: KeyboardEvent) => void) | null = null;\n/** Global stylesheet for context menu (injected once) */\nlet globalStyleSheet: HTMLStyleElement | null = null;\n/** Reference count for instances using global handlers */\nlet globalHandlerRefCount = 0;\n\n/** Default menu items when none are configured */\nconst defaultItems: ContextMenuItem[] = [\n {\n id: 'copy',\n name: 'Copy',\n shortcut: 'Ctrl+C',\n action: (params) => {\n const grid = (params as ContextMenuParams & { grid?: { plugins?: { clipboard?: { copy?: () => void } } } }).grid;\n grid?.plugins?.clipboard?.copy?.();\n },\n },\n { separator: true, id: 'sep1', name: '' },\n {\n id: 'export-csv',\n name: 'Export CSV',\n action: (params) => {\n const grid = (params as ContextMenuParams & { grid?: { plugins?: { export?: { exportCsv?: () => void } } } })\n .grid;\n grid?.plugins?.export?.exportCsv?.();\n },\n },\n];\n\n/**\n * Context Menu Plugin for tbw-grid\n *\n * Adds a customizable right-click menu to grid cells. Build anything from simple\n * copy/paste actions to complex nested menus with conditional visibility, icons,\n * and keyboard shortcuts.\n *\n * ## Installation\n *\n * ```ts\n * import { ContextMenuPlugin } from '@toolbox-web/grid/plugins/context-menu';\n * ```\n *\n * ## Menu Item Structure\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `id` | `string` | Unique item identifier |\n * | `name` | `string` | Display label |\n * | `icon` | `string` | Icon class or HTML |\n * | `shortcut` | `string` | Keyboard shortcut hint |\n * | `action` | `(params) => void` | Click handler |\n * | `disabled` | `boolean \\| (params) => boolean` | Disable condition |\n * | `visible` | `boolean \\| (params) => boolean` | Visibility condition |\n * | `items` | `MenuItem[]` | Submenu items |\n * | `separator` | `boolean` | Create a divider line |\n *\n * ## Menu Context (params)\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `rowIndex` | `number` | Clicked row index |\n * | `colIndex` | `number` | Clicked column index |\n * | `field` | `string` | Column field name |\n * | `value` | `any` | Cell value |\n * | `row` | `any` | Full row data |\n * | `column` | `ColumnConfig` | Column configuration |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-context-menu-bg` | `var(--tbw-color-panel-bg)` | Menu background |\n * | `--tbw-context-menu-fg` | `var(--tbw-color-fg)` | Menu text color |\n * | `--tbw-context-menu-hover` | `var(--tbw-color-row-hover)` | Item hover background |\n *\n * @example Basic Context Menu\n * ```ts\n * import '@toolbox-web/grid';\n * import { ContextMenuPlugin } from '@toolbox-web/grid/plugins/context-menu';\n *\n * grid.gridConfig = {\n * plugins: [\n * new ContextMenuPlugin({\n * items: [\n * { id: 'copy', name: 'Copy', shortcut: 'Ctrl+C', action: (ctx) => navigator.clipboard.writeText(ctx.value) },\n * { separator: true, id: 'sep1', name: '' },\n * { id: 'delete', name: 'Delete', action: (ctx) => removeRow(ctx.rowIndex) },\n * ],\n * }),\n * ],\n * };\n * ```\n *\n * @example Conditional Menu Items\n * ```ts\n * new ContextMenuPlugin({\n * items: [\n * { id: 'edit', name: 'Edit', visible: (ctx) => ctx.column.editable === true },\n * { id: 'delete', name: 'Delete', disabled: (ctx) => ctx.row.locked === true },\n * ],\n * })\n * ```\n *\n * @see {@link ContextMenuConfig} for configuration options\n * @see {@link ContextMenuItem} for menu item structure\n * @see {@link ContextMenuParams} for action callback parameters\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ContextMenuPlugin extends BaseGridPlugin<ContextMenuConfig> {\n /** @internal */\n readonly name = 'contextMenu';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ContextMenuConfig> {\n return {\n items: defaultItems,\n };\n }\n\n // #region Internal State\n private isOpen = false;\n private position = { x: 0, y: 0 };\n private params: ContextMenuParams | null = null;\n private menuElement: HTMLElement | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n this.installGlobalHandlers();\n globalHandlerRefCount++;\n }\n\n /** @internal */\n override detach(): void {\n if (this.menuElement) {\n this.menuElement.remove();\n this.menuElement = null;\n }\n this.isOpen = false;\n this.params = null;\n this.uninstallGlobalHandlers();\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * CSS variables to copy from the grid element to the context menu.\n * Includes both base variables and context-menu specific overrides.\n */\n private static readonly CSS_VARS_TO_COPY = [\n // Base palette (for themes that only set base vars)\n '--tbw-color-panel-bg',\n '--tbw-color-fg',\n '--tbw-color-fg-muted',\n '--tbw-color-border',\n '--tbw-color-row-hover',\n '--tbw-color-shadow',\n '--tbw-color-danger',\n '--tbw-border-radius',\n '--tbw-font-family',\n '--tbw-font-size-sm',\n '--tbw-font-size-xs',\n '--tbw-font-size-2xs',\n '--tbw-spacing-xs',\n '--tbw-icon-size',\n '--tbw-menu-min-width',\n '--tbw-menu-item-padding',\n '--tbw-menu-item-gap',\n // Context menu specific overrides\n '--tbw-context-menu-bg',\n '--tbw-context-menu-fg',\n '--tbw-context-menu-border',\n '--tbw-context-menu-radius',\n '--tbw-context-menu-shadow',\n '--tbw-context-menu-hover',\n '--tbw-context-menu-danger',\n '--tbw-context-menu-muted',\n '--tbw-context-menu-min-width',\n '--tbw-context-menu-font-size',\n '--tbw-context-menu-font-family',\n '--tbw-context-menu-item-padding',\n '--tbw-context-menu-item-gap',\n '--tbw-context-menu-icon-size',\n '--tbw-context-menu-shortcut-size',\n '--tbw-context-menu-arrow-size',\n ];\n\n /**\n * Copy CSS custom properties from the grid element to the menu element.\n * This allows the context menu (appended to document.body) to inherit\n * theme variables set on tbw-grid.\n */\n private copyGridStyles(menuElement: HTMLElement): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const computed = getComputedStyle(gridEl);\n const styles: string[] = [];\n\n // Copy color-scheme so light-dark() can resolve in the context menu\n const colorScheme = computed.getPropertyValue('color-scheme').trim();\n if (colorScheme) {\n styles.push(`color-scheme: ${colorScheme}`);\n }\n\n for (const varName of ContextMenuPlugin.CSS_VARS_TO_COPY) {\n const value = computed.getPropertyValue(varName).trim();\n if (value) {\n styles.push(`${varName}: ${value}`);\n }\n }\n\n if (styles.length > 0) {\n // Append to existing inline styles (don't overwrite)\n const existing = menuElement.getAttribute('style') || '';\n menuElement.setAttribute('style', existing + styles.join('; ') + ';');\n }\n }\n\n private installGlobalHandlers(): void {\n // Inject global stylesheet for context menu (once)\n // Only inject if we have valid CSS text (Vite's ?inline import)\n // When importing from source without Vite, the import is a module object, not a string\n if (\n !globalStyleSheet &&\n typeof document !== 'undefined' &&\n typeof contextMenuStyles === 'string' &&\n contextMenuStyles\n ) {\n globalStyleSheet = document.createElement('style');\n globalStyleSheet.id = 'tbw-context-menu-styles';\n globalStyleSheet.textContent = contextMenuStyles;\n document.head.appendChild(globalStyleSheet);\n }\n\n // Close menu on click outside\n if (!globalClickHandler) {\n globalClickHandler = () => {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n };\n document.addEventListener('click', globalClickHandler);\n }\n\n // Close on escape\n if (!globalKeydownHandler) {\n globalKeydownHandler = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n }\n };\n document.addEventListener('keydown', globalKeydownHandler);\n }\n }\n\n /**\n * Clean up global handlers when the last instance detaches.\n * Uses reference counting to ensure handlers persist while any grid uses the plugin.\n */\n private uninstallGlobalHandlers(): void {\n globalHandlerRefCount--;\n if (globalHandlerRefCount > 0) return;\n\n // Last instance - clean up all global resources\n if (globalClickHandler) {\n document.removeEventListener('click', globalClickHandler);\n globalClickHandler = null;\n }\n if (globalKeydownHandler) {\n document.removeEventListener('keydown', globalKeydownHandler);\n globalKeydownHandler = null;\n }\n if (globalStyleSheet) {\n globalStyleSheet.remove();\n globalStyleSheet = null;\n }\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override afterRender(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n // Use querySelector instead of children[0] because light DOM children\n // (e.g. <tbw-grid-column>) are re-appended before .tbw-grid-root, making\n // children[0] point to a declarative element instead of the data container.\n const container = gridEl.querySelector('.tbw-grid-root');\n if (!container) return;\n\n // Check if handler already attached\n if (container.getAttribute('data-context-menu-bound') === 'true') return;\n container.setAttribute('data-context-menu-bound', 'true');\n\n container.addEventListener('contextmenu', (e: Event) => {\n const event = e as MouseEvent;\n event.preventDefault();\n\n const target = event.target as HTMLElement;\n const cell = target.closest('[data-row][data-col]');\n const header = target.closest('.header-cell');\n\n let params: ContextMenuParams;\n\n if (cell) {\n const rowIndex = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n const column = this.columns[colIndex];\n const row = this.rows[rowIndex];\n\n params = {\n row,\n rowIndex,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: row?.[column?.field as keyof typeof row] ?? null,\n isHeader: false,\n event,\n };\n } else if (header) {\n const colIndex = parseInt(header.getAttribute('data-col') ?? '-1', 10);\n const column = this.columns[colIndex];\n\n params = {\n row: null,\n rowIndex: -1,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: null,\n isHeader: true,\n event,\n };\n } else {\n return;\n }\n\n this.params = params;\n this.position = { x: event.clientX, y: event.clientY };\n\n const items = buildMenuItems(this.config.items ?? defaultItems, params);\n if (!items.length) return;\n\n if (this.menuElement) {\n this.menuElement.remove();\n }\n\n this.menuElement = createMenuElement(\n items,\n params,\n (item) => {\n if (item.action) {\n item.action(params);\n }\n this.menuElement?.remove();\n this.menuElement = null;\n this.isOpen = false;\n },\n this.gridIcons.submenuArrow,\n );\n\n document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, event.clientX, event.clientY);\n this.isOpen = true;\n\n this.emit('context-menu-open', { params, items });\n });\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Programmatically show the context menu at the specified position.\n * @param x - X coordinate\n * @param y - Y coordinate\n * @param params - Partial context menu parameters\n */\n showMenu(x: number, y: number, params: Partial<ContextMenuParams>): void {\n const fullParams: ContextMenuParams = {\n row: params.row ?? null,\n rowIndex: params.rowIndex ?? -1,\n column: params.column ?? null,\n columnIndex: params.columnIndex ?? -1,\n field: params.field ?? '',\n value: params.value ?? null,\n isHeader: params.isHeader ?? false,\n event: params.event ?? new MouseEvent('contextmenu'),\n };\n\n const items = buildMenuItems(this.config.items ?? defaultItems, fullParams);\n\n if (this.menuElement) {\n this.menuElement.remove();\n }\n\n this.menuElement = createMenuElement(\n items,\n fullParams,\n (item) => {\n if (item.action) item.action(fullParams);\n this.menuElement?.remove();\n this.menuElement = null;\n this.isOpen = false;\n },\n this.gridIcons.submenuArrow,\n );\n\n document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, x, y);\n this.isOpen = true;\n }\n\n /**\n * Hide the context menu.\n */\n hideMenu(): void {\n if (this.menuElement) {\n this.menuElement.remove();\n this.menuElement = null;\n this.isOpen = false;\n }\n }\n\n /**\n * Check if the context menu is currently open.\n * @returns Whether the menu is open\n */\n isMenuOpen(): boolean {\n return this.isOpen;\n }\n // #endregion\n\n // Styles are injected globally via installGlobalHandlers() since menu renders in document.body\n}\n"],"names":["buildMenuItems","items","params","item","isItemDisabled","createMenuElement","onAction","submenuArrow","DEFAULT_GRID_ICONS","menu","separator","menuItem","disabled","icon","label","shortcut","arrow","subMenuItems","subMenu","e","positionMenu","x","y","menuRect","viewportWidth","viewportHeight","left","top","globalClickHandler","globalKeydownHandler","globalStyleSheet","globalHandlerRefCount","defaultItems","ContextMenuPlugin","BaseGridPlugin","grid","menuElement","gridEl","computed","styles","colorScheme","varName","value","existing","contextMenuStyles","container","event","target","cell","header","rowIndex","colIndex","column","row","fullParams"],"mappings":"gkEAiBO,SAASA,EACdC,EACAC,EACmB,CAGnB,OAFkB,OAAOD,GAAU,WAAaA,EAAMC,CAAM,EAAID,GAE/C,OAAQE,GACnB,EAAAA,EAAK,SAAW,IAChB,OAAOA,EAAK,QAAW,YAAcA,EAAK,OAAOD,CAAM,EAE5D,CACH,CASO,SAASE,EAAeD,EAAuBD,EAAoC,CACxF,OAAIC,EAAK,WAAa,GAAa,GAC/B,OAAOA,EAAK,UAAa,WAAmBA,EAAK,SAASD,CAAM,EAC7D,EACT,CAWO,SAASG,EACdJ,EACAC,EACAI,EACAC,EAA0BC,EAAAA,mBAAmB,aAChC,CACb,MAAMC,EAAO,SAAS,cAAc,KAAK,EACzCA,EAAK,UAAY,mBACjBA,EAAK,aAAa,OAAQ,MAAM,EAEhC,UAAWN,KAAQF,EAAO,CACxB,GAAIE,EAAK,UAAW,CAClB,MAAMO,EAAY,SAAS,cAAc,KAAK,EAC9CA,EAAU,UAAY,6BACtBA,EAAU,aAAa,OAAQ,WAAW,EAC1CD,EAAK,YAAYC,CAAS,EAC1B,QACF,CAEA,MAAMC,EAAW,SAAS,cAAc,KAAK,EAC7CA,EAAS,UAAY,wBACjBR,EAAK,UAAUQ,EAAS,UAAU,IAAIR,EAAK,QAAQ,EACvDQ,EAAS,aAAa,OAAQ,UAAU,EACxCA,EAAS,aAAa,UAAWR,EAAK,EA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AAY,OAAA,EAGnB,KAAK,YAAcjD,EACjBJ,EACAqD,EACCnD,GAAS,CACJA,EAAK,QAAQA,EAAK,OAAOmD,CAAU,EACvC,KAAK,aAAa,OAAA,EAClB,KAAK,YAAc,KACnB,KAAK,OAAS,EAChB,EACA,KAAK,UAAU,YAAA,EAGjB,SAAS,KAAK,YAAY,KAAK,WAAW,EAC1C,KAAK,eAAe,KAAK,WAAW,EACpClC,EAAa,KAAK,YAAaC,EAAGC,CAAC,EACnC,KAAK,OAAS,EAChB,CAKA,UAAiB,CACX,KAAK,cACP,KAAK,YAAY,OAAA,EACjB,KAAK,YAAc,KACnB,KAAK,OAAS,GAElB,CAMA,YAAsB,CACpB,OAAO,KAAK,MACd,CAIF"}
|
|
1
|
+
{"version":3,"file":"context-menu.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/context-menu/menu.ts","../../../../../libs/grid/src/lib/plugins/context-menu/ContextMenuPlugin.ts"],"sourcesContent":["/**\n * Context Menu Rendering Logic\n *\n * Pure functions for building and positioning context menus.\n */\n\nimport type { IconValue } from '../../core/types';\nimport { DEFAULT_GRID_ICONS } from '../../core/types';\nimport type { ContextMenuItem, ContextMenuParams } from './types';\n\n/**\n * Build the visible menu items by resolving dynamic items and filtering hidden ones.\n *\n * @param items - Menu items configuration (array or factory function)\n * @param params - Context menu parameters for evaluating dynamic properties\n * @returns Filtered array of visible menu items\n */\nexport function buildMenuItems(\n items: ContextMenuItem[] | ((params: ContextMenuParams) => ContextMenuItem[]),\n params: ContextMenuParams\n): ContextMenuItem[] {\n const menuItems = typeof items === 'function' ? items(params) : items;\n\n return menuItems.filter((item) => {\n if (item.hidden === true) return false;\n if (typeof item.hidden === 'function' && item.hidden(params)) return false;\n return true;\n });\n}\n\n/**\n * Check if a menu item is disabled.\n *\n * @param item - The menu item to check\n * @param params - Context menu parameters for evaluating dynamic disabled state\n * @returns True if the item is disabled\n */\nexport function isItemDisabled(item: ContextMenuItem, params: ContextMenuParams): boolean {\n if (item.disabled === true) return true;\n if (typeof item.disabled === 'function') return item.disabled(params);\n return false;\n}\n\n/**\n * Create the menu DOM element from a list of menu items.\n *\n * @param items - Array of menu items to render\n * @param params - Context menu parameters for evaluating dynamic properties\n * @param onAction - Callback when a menu item action is triggered\n * @param submenuArrow - Optional custom submenu arrow icon\n * @returns The created menu element\n */\nexport function createMenuElement(\n items: ContextMenuItem[],\n params: ContextMenuParams,\n onAction: (item: ContextMenuItem) => void,\n submenuArrow: IconValue = DEFAULT_GRID_ICONS.submenuArrow\n): HTMLElement {\n const menu = document.createElement('div');\n menu.className = 'tbw-context-menu';\n menu.setAttribute('role', 'menu');\n\n for (const item of items) {\n if (item.separator) {\n const separator = document.createElement('div');\n separator.className = 'tbw-context-menu-separator';\n separator.setAttribute('role', 'separator');\n menu.appendChild(separator);\n continue;\n }\n\n const menuItem = document.createElement('div');\n menuItem.className = 'tbw-context-menu-item';\n if (item.cssClass) menuItem.classList.add(item.cssClass);\n menuItem.setAttribute('role', 'menuitem');\n menuItem.setAttribute('data-id', item.id);\n\n const disabled = isItemDisabled(item, params);\n if (disabled) {\n menuItem.classList.add('disabled');\n menuItem.setAttribute('aria-disabled', 'true');\n }\n\n if (item.icon) {\n const icon = document.createElement('span');\n icon.className = 'tbw-context-menu-icon';\n icon.innerHTML = item.icon;\n menuItem.appendChild(icon);\n }\n\n const label = document.createElement('span');\n label.className = 'tbw-context-menu-label';\n label.textContent = item.name;\n menuItem.appendChild(label);\n\n if (item.shortcut) {\n const shortcut = document.createElement('span');\n shortcut.className = 'tbw-context-menu-shortcut';\n shortcut.textContent = item.shortcut;\n menuItem.appendChild(shortcut);\n }\n\n if (item.subMenu?.length) {\n const arrow = document.createElement('span');\n arrow.className = 'tbw-context-menu-arrow';\n // Use provided submenu arrow icon (string or HTMLElement)\n if (typeof submenuArrow === 'string') {\n arrow.innerHTML = submenuArrow;\n } else if (submenuArrow instanceof HTMLElement) {\n arrow.appendChild(submenuArrow.cloneNode(true));\n }\n menuItem.appendChild(arrow);\n\n // Add submenu on hover\n menuItem.addEventListener('mouseenter', () => {\n const existingSubMenu = menuItem.querySelector('.tbw-context-menu');\n if (existingSubMenu) return;\n if (!item.subMenu) return;\n\n const subMenuItems = buildMenuItems(item.subMenu, params);\n const subMenu = createMenuElement(subMenuItems, params, onAction, submenuArrow);\n subMenu.classList.add('tbw-context-submenu');\n subMenu.style.position = 'absolute';\n subMenu.style.left = '100%';\n subMenu.style.top = '0';\n menuItem.style.position = 'relative';\n menuItem.appendChild(subMenu);\n });\n\n menuItem.addEventListener('mouseleave', () => {\n const subMenu = menuItem.querySelector('.tbw-context-menu');\n if (subMenu) subMenu.remove();\n });\n }\n\n if (!disabled && item.action && !item.subMenu) {\n menuItem.addEventListener('click', (e) => {\n e.stopPropagation();\n onAction(item);\n });\n }\n\n menu.appendChild(menuItem);\n }\n\n return menu;\n}\n\n/**\n * Position the menu at the given viewport coordinates.\n * Menu is rendered in document.body with fixed positioning for top-layer behavior.\n *\n * @param menu - The menu element to position\n * @param x - Desired X coordinate (viewport)\n * @param y - Desired Y coordinate (viewport)\n */\nexport function positionMenu(menu: HTMLElement, x: number, y: number): void {\n // Use fixed positioning for top-layer behavior\n menu.style.position = 'fixed';\n menu.style.left = `${x}px`;\n menu.style.top = `${y}px`;\n menu.style.visibility = 'hidden';\n menu.style.zIndex = '10000';\n\n // Force layout to get dimensions\n const menuRect = menu.getBoundingClientRect();\n\n // Calculate visible area within viewport\n const viewportWidth = window.innerWidth;\n const viewportHeight = window.innerHeight;\n\n let left = x;\n let top = y;\n\n // Check if menu overflows right edge of viewport\n if (x + menuRect.width > viewportWidth) {\n left = x - menuRect.width;\n }\n // Check if menu overflows bottom edge of viewport\n if (y + menuRect.height > viewportHeight) {\n top = y - menuRect.height;\n }\n\n // Ensure we don't go negative\n left = Math.max(0, left);\n top = Math.max(0, top);\n\n menu.style.left = `${left}px`;\n menu.style.top = `${top}px`;\n menu.style.visibility = 'visible';\n}\n","/**\n * Context Menu Plugin (Class-based)\n *\n * Provides right-click context menu functionality for tbw-grid.\n * Supports custom menu items, submenus, icons, shortcuts, and dynamic item generation.\n */\n\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport contextMenuStyles from './context-menu.css?inline';\nimport { buildMenuItems, createMenuElement, positionMenu } from './menu';\nimport type { ContextMenuConfig, ContextMenuItem, ContextMenuParams } from './types';\n\n/** Global click handler reference for cleanup */\nlet globalClickHandler: ((e: Event) => void) | null = null;\n/** Global keydown handler reference for cleanup */\nlet globalKeydownHandler: ((e: KeyboardEvent) => void) | null = null;\n/** Global stylesheet for context menu (injected once) */\nlet globalStyleSheet: HTMLStyleElement | null = null;\n/** Reference count for instances using global handlers */\nlet globalHandlerRefCount = 0;\n\n/** Default menu items when none are configured */\nconst defaultItems: ContextMenuItem[] = [\n {\n id: 'copy',\n name: 'Copy',\n shortcut: 'Ctrl+C',\n action: (params) => {\n const grid = (params as ContextMenuParams & { grid?: { plugins?: { clipboard?: { copy?: () => void } } } }).grid;\n grid?.plugins?.clipboard?.copy?.();\n },\n },\n { separator: true, id: 'sep1', name: '' },\n {\n id: 'export-csv',\n name: 'Export CSV',\n action: (params) => {\n const grid = (params as ContextMenuParams & { grid?: { plugins?: { export?: { exportCsv?: () => void } } } })\n .grid;\n grid?.plugins?.export?.exportCsv?.();\n },\n },\n];\n\n/**\n * Context Menu Plugin for tbw-grid\n *\n * Adds a customizable right-click menu to grid cells. Build anything from simple\n * copy/paste actions to complex nested menus with conditional visibility, icons,\n * and keyboard shortcuts.\n *\n * ## Installation\n *\n * ```ts\n * import { ContextMenuPlugin } from '@toolbox-web/grid/plugins/context-menu';\n * ```\n *\n * ## Menu Item Structure\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `id` | `string` | Unique item identifier |\n * | `name` | `string` | Display label |\n * | `icon` | `string` | Icon class or HTML |\n * | `shortcut` | `string` | Keyboard shortcut hint |\n * | `action` | `(params) => void` | Click handler |\n * | `disabled` | `boolean \\| (params) => boolean` | Disable condition |\n * | `visible` | `boolean \\| (params) => boolean` | Visibility condition |\n * | `items` | `MenuItem[]` | Submenu items |\n * | `separator` | `boolean` | Create a divider line |\n *\n * ## Menu Context (params)\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `rowIndex` | `number` | Clicked row index |\n * | `colIndex` | `number` | Clicked column index |\n * | `field` | `string` | Column field name |\n * | `value` | `any` | Cell value |\n * | `row` | `any` | Full row data |\n * | `column` | `ColumnConfig` | Column configuration |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-context-menu-bg` | `var(--tbw-color-panel-bg)` | Menu background |\n * | `--tbw-context-menu-fg` | `var(--tbw-color-fg)` | Menu text color |\n * | `--tbw-context-menu-hover` | `var(--tbw-color-row-hover)` | Item hover background |\n *\n * @example Basic Context Menu\n * ```ts\n * import '@toolbox-web/grid';\n * import { ContextMenuPlugin } from '@toolbox-web/grid/plugins/context-menu';\n *\n * grid.gridConfig = {\n * plugins: [\n * new ContextMenuPlugin({\n * items: [\n * { id: 'copy', name: 'Copy', shortcut: 'Ctrl+C', action: (ctx) => navigator.clipboard.writeText(ctx.value) },\n * { separator: true, id: 'sep1', name: '' },\n * { id: 'delete', name: 'Delete', action: (ctx) => removeRow(ctx.rowIndex) },\n * ],\n * }),\n * ],\n * };\n * ```\n *\n * @example Conditional Menu Items\n * ```ts\n * new ContextMenuPlugin({\n * items: [\n * { id: 'edit', name: 'Edit', visible: (ctx) => ctx.column.editable === true },\n * { id: 'delete', name: 'Delete', disabled: (ctx) => ctx.row.locked === true },\n * ],\n * })\n * ```\n *\n * @see {@link ContextMenuConfig} for configuration options\n * @see {@link ContextMenuItem} for menu item structure\n * @see {@link ContextMenuParams} for action callback parameters\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ContextMenuPlugin extends BaseGridPlugin<ContextMenuConfig> {\n /** @internal */\n readonly name = 'contextMenu';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ContextMenuConfig> {\n return {\n items: defaultItems,\n };\n }\n\n // #region Internal State\n private isOpen = false;\n private position = { x: 0, y: 0 };\n private params: ContextMenuParams | null = null;\n private menuElement: HTMLElement | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n this.installGlobalHandlers();\n globalHandlerRefCount++;\n }\n\n /** @internal */\n override detach(): void {\n if (this.menuElement) {\n this.menuElement.remove();\n this.menuElement = null;\n }\n this.isOpen = false;\n this.params = null;\n this.uninstallGlobalHandlers();\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Sync selection with the right-clicked row.\n * If the right-clicked row is already selected, keeps the multi-selection.\n * If not, selects only the right-clicked row (standard behavior in file managers / spreadsheets).\n *\n * @returns Sorted array of selected row indices after sync\n */\n private syncSelectionOnContextMenu(rowIndex: number): number[] {\n if (rowIndex < 0) return [];\n\n // Use the query system for loose coupling — no import of SelectionPlugin needed\n const selectionResult = this.grid?.query<number[]>('getSelectedRowIndices');\n const currentSelection = selectionResult?.[0];\n\n // No selection plugin loaded\n if (!currentSelection) return [rowIndex];\n\n if (currentSelection.includes(rowIndex)) {\n // Right-clicked row is already selected — preserve multi-selection\n return currentSelection;\n }\n\n // Right-clicked row is NOT selected — select only this row\n this.grid?.query('selectRows', [rowIndex]);\n return [rowIndex];\n }\n\n /**\n * CSS variables to copy from the grid element to the context menu.\n * Includes both base variables and context-menu specific overrides.\n */\n private static readonly CSS_VARS_TO_COPY = [\n // Base palette (for themes that only set base vars)\n '--tbw-color-panel-bg',\n '--tbw-color-fg',\n '--tbw-color-fg-muted',\n '--tbw-color-border',\n '--tbw-color-row-hover',\n '--tbw-color-shadow',\n '--tbw-color-danger',\n '--tbw-border-radius',\n '--tbw-font-family',\n '--tbw-font-size-sm',\n '--tbw-font-size-xs',\n '--tbw-font-size-2xs',\n '--tbw-spacing-xs',\n '--tbw-icon-size',\n '--tbw-menu-min-width',\n '--tbw-menu-item-padding',\n '--tbw-menu-item-gap',\n // Context menu specific overrides\n '--tbw-context-menu-bg',\n '--tbw-context-menu-fg',\n '--tbw-context-menu-border',\n '--tbw-context-menu-radius',\n '--tbw-context-menu-shadow',\n '--tbw-context-menu-hover',\n '--tbw-context-menu-danger',\n '--tbw-context-menu-muted',\n '--tbw-context-menu-min-width',\n '--tbw-context-menu-font-size',\n '--tbw-context-menu-font-family',\n '--tbw-context-menu-item-padding',\n '--tbw-context-menu-item-gap',\n '--tbw-context-menu-icon-size',\n '--tbw-context-menu-shortcut-size',\n '--tbw-context-menu-arrow-size',\n ];\n\n /**\n * Copy CSS custom properties from the grid element to the menu element.\n * This allows the context menu (appended to document.body) to inherit\n * theme variables set on tbw-grid.\n */\n private copyGridStyles(menuElement: HTMLElement): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const computed = getComputedStyle(gridEl);\n const styles: string[] = [];\n\n // Copy color-scheme so light-dark() can resolve in the context menu\n const colorScheme = computed.getPropertyValue('color-scheme').trim();\n if (colorScheme) {\n styles.push(`color-scheme: ${colorScheme}`);\n }\n\n for (const varName of ContextMenuPlugin.CSS_VARS_TO_COPY) {\n const value = computed.getPropertyValue(varName).trim();\n if (value) {\n styles.push(`${varName}: ${value}`);\n }\n }\n\n if (styles.length > 0) {\n // Append to existing inline styles (don't overwrite)\n const existing = menuElement.getAttribute('style') || '';\n menuElement.setAttribute('style', existing + styles.join('; ') + ';');\n }\n }\n\n private installGlobalHandlers(): void {\n // Inject global stylesheet for context menu (once)\n // Only inject if we have valid CSS text (Vite's ?inline import)\n // When importing from source without Vite, the import is a module object, not a string\n if (\n !globalStyleSheet &&\n typeof document !== 'undefined' &&\n typeof contextMenuStyles === 'string' &&\n contextMenuStyles\n ) {\n globalStyleSheet = document.createElement('style');\n globalStyleSheet.id = 'tbw-context-menu-styles';\n globalStyleSheet.textContent = contextMenuStyles;\n document.head.appendChild(globalStyleSheet);\n }\n\n // Close menu on click outside\n if (!globalClickHandler) {\n globalClickHandler = () => {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n };\n document.addEventListener('click', globalClickHandler);\n }\n\n // Close on escape\n if (!globalKeydownHandler) {\n globalKeydownHandler = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n }\n };\n document.addEventListener('keydown', globalKeydownHandler);\n }\n }\n\n /**\n * Clean up global handlers when the last instance detaches.\n * Uses reference counting to ensure handlers persist while any grid uses the plugin.\n */\n private uninstallGlobalHandlers(): void {\n globalHandlerRefCount--;\n if (globalHandlerRefCount > 0) return;\n\n // Last instance - clean up all global resources\n if (globalClickHandler) {\n document.removeEventListener('click', globalClickHandler);\n globalClickHandler = null;\n }\n if (globalKeydownHandler) {\n document.removeEventListener('keydown', globalKeydownHandler);\n globalKeydownHandler = null;\n }\n if (globalStyleSheet) {\n globalStyleSheet.remove();\n globalStyleSheet = null;\n }\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override afterRender(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n // Use querySelector instead of children[0] because light DOM children\n // (e.g. <tbw-grid-column>) are re-appended before .tbw-grid-root, making\n // children[0] point to a declarative element instead of the data container.\n const container = gridEl.querySelector('.tbw-grid-root');\n if (!container) return;\n\n // Check if handler already attached\n if (container.getAttribute('data-context-menu-bound') === 'true') return;\n container.setAttribute('data-context-menu-bound', 'true');\n\n container.addEventListener('contextmenu', (e: Event) => {\n const event = e as MouseEvent;\n event.preventDefault();\n\n const target = event.target as HTMLElement;\n const cell = target.closest('[data-row][data-col]');\n const header = target.closest('.header-cell');\n\n let params: ContextMenuParams;\n\n if (cell) {\n const rowIndex = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n const column = this.columns[colIndex];\n const row = this.rows[rowIndex];\n\n // Sync selection: if the right-clicked row is not already selected,\n // select it (clearing multi-selection). If it IS selected, keep all.\n const selectedRows = this.syncSelectionOnContextMenu(rowIndex);\n\n params = {\n row,\n rowIndex,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: row?.[column?.field as keyof typeof row] ?? null,\n isHeader: false,\n event,\n selectedRows,\n };\n } else if (header) {\n const colIndex = parseInt(header.getAttribute('data-col') ?? '-1', 10);\n const column = this.columns[colIndex];\n\n params = {\n row: null,\n rowIndex: -1,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: null,\n isHeader: true,\n event,\n selectedRows: [],\n };\n } else {\n return;\n }\n\n this.params = params;\n this.position = { x: event.clientX, y: event.clientY };\n\n const items = buildMenuItems(this.config.items ?? defaultItems, params);\n if (!items.length) return;\n\n if (this.menuElement) {\n this.menuElement.remove();\n }\n\n this.menuElement = createMenuElement(\n items,\n params,\n (item) => {\n if (item.action) {\n item.action(params);\n }\n this.menuElement?.remove();\n this.menuElement = null;\n this.isOpen = false;\n },\n this.gridIcons.submenuArrow,\n );\n\n document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, event.clientX, event.clientY);\n this.isOpen = true;\n\n this.emit('context-menu-open', { params, items });\n });\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Programmatically show the context menu at the specified position.\n * @param x - X coordinate\n * @param y - Y coordinate\n * @param params - Partial context menu parameters\n */\n showMenu(x: number, y: number, params: Partial<ContextMenuParams>): void {\n const fullParams: ContextMenuParams = {\n row: params.row ?? null,\n rowIndex: params.rowIndex ?? -1,\n column: params.column ?? null,\n columnIndex: params.columnIndex ?? -1,\n field: params.field ?? '',\n value: params.value ?? null,\n isHeader: params.isHeader ?? false,\n event: params.event ?? new MouseEvent('contextmenu'),\n selectedRows: params.selectedRows ?? [],\n };\n\n const items = buildMenuItems(this.config.items ?? defaultItems, fullParams);\n\n if (this.menuElement) {\n this.menuElement.remove();\n }\n\n this.menuElement = createMenuElement(\n items,\n fullParams,\n (item) => {\n if (item.action) item.action(fullParams);\n this.menuElement?.remove();\n this.menuElement = null;\n this.isOpen = false;\n },\n this.gridIcons.submenuArrow,\n );\n\n document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, x, y);\n this.isOpen = true;\n }\n\n /**\n * Hide the context menu.\n */\n hideMenu(): void {\n if (this.menuElement) {\n this.menuElement.remove();\n this.menuElement = null;\n this.isOpen = false;\n }\n }\n\n /**\n * Check if the context menu is currently open.\n * @returns Whether the menu is open\n */\n isMenuOpen(): boolean {\n return this.isOpen;\n }\n // #endregion\n\n // Styles are injected globally via installGlobalHandlers() since menu renders in document.body\n}\n"],"names":["buildMenuItems","items","params","item","isItemDisabled","createMenuElement","onAction","submenuArrow","DEFAULT_GRID_ICONS","menu","separator","menuItem","disabled","icon","label","shortcut","arrow","subMenuItems","subMenu","e","positionMenu","x","y","menuRect","viewportWidth","viewportHeight","left","top","globalClickHandler","globalKeydownHandler","globalStyleSheet","globalHandlerRefCount","defaultItems","ContextMenuPlugin","BaseGridPlugin","grid","rowIndex","currentSelection","menuElement","gridEl","computed","styles","colorScheme","varName","value","existing","contextMenuStyles","container","event","target","cell","header","colIndex","column","row","selectedRows","fullParams"],"mappings":"gkEAiBO,SAASA,EACdC,EACAC,EACmB,CAGnB,OAFkB,OAAOD,GAAU,WAAaA,EAAMC,CAAM,EAAID,GAE/C,OAAQE,GACnB,EAAAA,EAAK,SAAW,IAChB,OAAOA,EAAK,QAAW,YAAcA,EAAK,OAAOD,CAAM,EAE5D,CACH,CASO,SAASE,EAAeD,EAAuBD,EAAoC,CACxF,OAAIC,EAAK,WAAa,GAAa,GAC/B,OAAOA,EAAK,UAAa,WAAmBA,EAAK,SAASD,CAAM,EAC7D,EACT,CAWO,SAASG,EACdJ,EACAC,EACAI,EACAC,EAA0BC,EAAAA,mBAAmB,aAChC,CACb,MAAMC,EAAO,SAAS,cAAc,KAAK,EACzCA,EAAK,UAAY,mBACjBA,EAAK,aAAa,OAAQ,MAAM,EAEhC,UAAWN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