@toolbox-web/grid 1.21.2 → 1.22.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/README.md +6 -8
- package/all.js +1 -1
- package/all.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/lib/core/grid.d.ts +53 -2
- package/lib/core/grid.d.ts.map +1 -1
- package/lib/core/internal/rows.d.ts.map +1 -1
- package/lib/core/plugin/base-plugin.d.ts +8 -2
- package/lib/core/plugin/base-plugin.d.ts.map +1 -1
- package/lib/core/types.d.ts +84 -2
- package/lib/core/types.d.ts.map +1 -1
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/lib/plugins/clipboard/types.d.ts +5 -0
- package/lib/plugins/clipboard/types.d.ts.map +1 -1
- package/lib/plugins/column-virtualization/index.js.map +1 -1
- package/lib/plugins/column-virtualization/types.d.ts +5 -0
- package/lib/plugins/column-virtualization/types.d.ts.map +1 -1
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/context-menu/types.d.ts +5 -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/index.js +1 -1
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/editing/types.d.ts +26 -0
- package/lib/plugins/editing/types.d.ts.map +1 -1
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/export/types.d.ts +5 -0
- package/lib/plugins/export/types.d.ts.map +1 -1
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/filtering/types.d.ts +3 -0
- package/lib/plugins/filtering/types.d.ts.map +1 -1
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-columns/types.d.ts +3 -0
- package/lib/plugins/grouping-columns/types.d.ts.map +1 -1
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/grouping-rows/types.d.ts +5 -0
- package/lib/plugins/grouping-rows/types.d.ts.map +1 -1
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/master-detail/types.d.ts +5 -0
- package/lib/plugins/master-detail/types.d.ts.map +1 -1
- package/lib/plugins/multi-sort/index.js.map +1 -1
- package/lib/plugins/multi-sort/types.d.ts +5 -0
- package/lib/plugins/multi-sort/types.d.ts.map +1 -1
- package/lib/plugins/pinned-columns/index.js.map +1 -1
- package/lib/plugins/pinned-columns/types.d.ts +3 -0
- package/lib/plugins/pinned-columns/types.d.ts.map +1 -1
- package/lib/plugins/pinned-rows/index.js.map +1 -1
- package/lib/plugins/pinned-rows/types.d.ts +5 -0
- package/lib/plugins/pinned-rows/types.d.ts.map +1 -1
- package/lib/plugins/pivot/index.js.map +1 -1
- package/lib/plugins/pivot/types.d.ts +5 -0
- package/lib/plugins/pivot/types.d.ts.map +1 -1
- package/lib/plugins/print/index.js.map +1 -1
- package/lib/plugins/print/types.d.ts +3 -0
- package/lib/plugins/print/types.d.ts.map +1 -1
- package/lib/plugins/reorder/index.js.map +1 -1
- package/lib/plugins/reorder/types.d.ts +5 -0
- package/lib/plugins/reorder/types.d.ts.map +1 -1
- package/lib/plugins/responsive/index.js.map +1 -1
- package/lib/plugins/responsive/types.d.ts +5 -0
- package/lib/plugins/responsive/types.d.ts.map +1 -1
- package/lib/plugins/row-reorder/index.js.map +1 -1
- package/lib/plugins/row-reorder/types.d.ts +5 -0
- package/lib/plugins/row-reorder/types.d.ts.map +1 -1
- package/lib/plugins/selection/index.js.map +1 -1
- package/lib/plugins/selection/types.d.ts +3 -0
- package/lib/plugins/selection/types.d.ts.map +1 -1
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/server-side/types.d.ts +5 -0
- package/lib/plugins/server-side/types.d.ts.map +1 -1
- package/lib/plugins/tree/index.js.map +1 -1
- package/lib/plugins/tree/types.d.ts +5 -0
- package/lib/plugins/tree/types.d.ts.map +1 -1
- package/lib/plugins/undo-redo/index.js.map +1 -1
- package/lib/plugins/undo-redo/types.d.ts +5 -0
- package/lib/plugins/undo-redo/types.d.ts.map +1 -1
- package/lib/plugins/visibility/index.js.map +1 -1
- package/lib/plugins/visibility/types.d.ts +5 -0
- package/lib/plugins/visibility/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/umd/grid.all.umd.js +1 -1
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +1 -1
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/clipboard.umd.js.map +1 -1
- package/umd/plugins/editing.umd.js +1 -1
- package/umd/plugins/editing.umd.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../libs/grid/src/lib/plugins/clipboard/ClipboardPlugin.ts","../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts"],"sourcesContent":["/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.meta?.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n","/**\n * Clipboard Paste Logic\n *\n * Pure functions for reading and parsing clipboard data.\n */\n\nimport type { ClipboardConfig } from './types';\n\n/**\n * Parse clipboard text into a 2D array of cell values.\n *\n * Handles:\n * - Quoted values (with escaped double quotes \"\")\n * - Multi-line quoted values (newlines within quotes are preserved)\n * - Custom delimiters and newlines\n * - Empty lines (filtered out only if they contain no data)\n *\n * @param text - Raw clipboard text\n * @param config - Clipboard configuration\n * @returns 2D array where each sub-array is a row of cell values\n */\nexport function parseClipboardText(text: string, config: ClipboardConfig): string[][] {\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Handle Windows CRLF line endings\n const normalizedText = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n // Parse the entire text handling quoted fields that may span multiple lines\n const rows: string[][] = [];\n let currentRow: string[] = [];\n let currentCell = '';\n let inQuotes = false;\n\n for (let i = 0; i < normalizedText.length; i++) {\n const char = normalizedText[i];\n\n if (char === '\"' && !inQuotes) {\n // Start of quoted field\n inQuotes = true;\n } else if (char === '\"' && inQuotes) {\n // Check for escaped quote (\"\")\n if (normalizedText[i + 1] === '\"') {\n currentCell += '\"';\n i++; // Skip the second quote\n } else {\n // End of quoted field\n inQuotes = false;\n }\n } else if (char === delimiter && !inQuotes) {\n // Field separator\n currentRow.push(currentCell);\n currentCell = '';\n } else if (char === newline && !inQuotes) {\n // Row separator (only if not inside quotes)\n currentRow.push(currentCell);\n currentCell = '';\n // Only add non-empty rows (at least one non-empty cell or multiple cells)\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n currentRow = [];\n } else {\n currentCell += char;\n }\n }\n\n // Handle the last cell and row\n currentRow.push(currentCell);\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n\n return rows;\n}\n\n/**\n * Read text from the system clipboard.\n *\n * Uses the modern Clipboard API. Returns empty string if\n * the API is not available or permission is denied.\n *\n * @returns Promise resolving to clipboard text or empty string\n */\nexport async function readFromClipboard(): Promise<string> {\n try {\n return await navigator.clipboard.readText();\n } catch {\n // Permission denied or API not available\n return '';\n }\n}\n","/**\n * Clipboard Plugin Types\n *\n * Type definitions for clipboard copy/paste functionality.\n */\n\nimport type { GridElement } from '../../core/plugin/base-plugin';\n\n/**\n * Custom paste handler function.\n *\n * @param detail - The parsed paste data with target and field info\n * @param grid - The grid element to update\n * @returns `false` to prevent the default paste behavior, or `void`/`true` to allow it\n *\n * @example\n * ```ts\n * // Custom handler that validates before pasting\n * new ClipboardPlugin({\n * pasteHandler: (detail, grid) => {\n * if (!detail.target) return false;\n * // Apply custom validation/transformation...\n * applyPasteData(detail, grid);\n * return false; // We handled it, skip default\n * }\n * })\n * ```\n */\nexport type PasteHandler = (detail: PasteDetail, grid: GridElement) => boolean | void;\n\n/**\n * Options for programmatic copy operations.\n *\n * Allows callers to control exactly which columns and rows are included\n * in a copy, independently of the current selection state.\n *\n * @example Copy specific columns from selected rows\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * // User selected rows 0, 2, 4 via a dialog, chose columns to include\n * const text = await clipboard.copy({\n * rowIndices: [0, 2, 4],\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * ```\n */\nexport interface CopyOptions {\n /** Specific column fields to include. If omitted, uses current selection or all visible columns. */\n columns?: string[];\n /** Specific row indices to copy. If omitted, uses current selection or all rows. */\n rowIndices?: number[];\n /** Include column headers in copied text. Defaults to the plugin config value. */\n includeHeaders?: boolean;\n /** Column delimiter override. Defaults to the plugin config value. */\n delimiter?: string;\n /** Row delimiter override. Defaults to the plugin config value. */\n newline?: string;\n /** Custom cell value processor for this operation. Overrides the plugin config's `processCell`. */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n}\n\n/** Configuration options for the clipboard plugin */\nexport interface ClipboardConfig {\n /** Include column headers in copied text (default: false) */\n includeHeaders?: boolean;\n /** Column delimiter character (default: '\\t' for tab) */\n delimiter?: string;\n /** Row delimiter/newline character (default: '\\n') */\n newline?: string;\n /** Wrap string values with quotes (default: false) */\n quoteStrings?: boolean;\n /** Custom cell value processor for copy operations */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n /**\n * Custom paste handler. By default, the plugin applies pasted data to `grid.rows`\n * starting at the target cell.\n *\n * - Set to a custom function to handle paste yourself\n * - Set to `null` to disable auto-paste (event still fires)\n * - Return `false` from handler to prevent default behavior\n *\n * @default defaultPasteHandler (auto-applies paste data)\n */\n pasteHandler?: PasteHandler | null;\n}\n\n/** Internal state managed by the clipboard plugin */\nexport interface ClipboardState {\n /** The last copied text (for reference/debugging) */\n lastCopied: string | null;\n}\n\n/** Event detail emitted after a successful copy operation */\nexport interface CopyDetail {\n /** The text that was copied to clipboard */\n text: string;\n /** Number of rows copied */\n rowCount: number;\n /** Number of columns copied */\n columnCount: number;\n}\n\n/** Target cell coordinates and bounds for paste operations */\nexport interface PasteTarget {\n /** Target row index (top-left of paste area) */\n row: number;\n /** Target column index (top-left of paste area) */\n col: number;\n /** Target column field name (for easy data mapping) */\n field: string;\n /**\n * Selection bounds that constrain the paste area.\n * If set, paste data will be clipped to fit within these bounds.\n * If null, paste expands freely from the target cell.\n */\n bounds: {\n /** End row index (inclusive) */\n endRow: number;\n /** End column index (inclusive) */\n endCol: number;\n } | null;\n}\n\n/** Event detail emitted after a paste operation */\nexport interface PasteDetail {\n /** Parsed rows from clipboard (2D array of cell values) */\n rows: string[][];\n /** Raw text that was pasted */\n text: string;\n /** The target cell where paste starts (top-left of paste area). Null if no cell is selected. */\n target: PasteTarget | null;\n /**\n * Column fields for each column in the paste range, starting from target.col.\n * Useful for mapping parsed cell values to data fields.\n * Length matches the width of the pasted data (or available columns, whichever is smaller).\n */\n fields: string[];\n}\n\n/**\n * Default paste handler that applies pasted data to grid.rows.\n *\n * This is the built-in handler used when no custom `pasteHandler` is configured.\n * It clones the rows array for immutability and applies values starting at the target cell.\n *\n * Behavior:\n * - Single cell selection: paste expands freely, adds new rows if needed\n * - Range/row selection: paste is clipped to fit within selection bounds\n * - Non-editable columns: values are skipped (column alignment preserved)\n *\n * @param detail - The parsed paste data from clipboard\n * @param grid - The grid element to update\n */\nexport function defaultPasteHandler(detail: PasteDetail, grid: GridElement): void {\n const { rows: pastedRows, target, fields } = detail;\n\n // No target = nothing to do\n if (!target) return;\n\n // Get current rows and columns from grid\n const currentRows = grid.rows as Record<string, unknown>[];\n const columns = grid.effectiveConfig.columns ?? [];\n const allFields = columns.map((col) => col.field);\n\n // Build a map of field -> editable for quick lookup\n const editableMap = new Map<string, boolean>();\n columns.forEach((col) => {\n editableMap.set(col.field, col.editable === true);\n });\n\n // Clone data for immutability\n const newRows = [...currentRows];\n\n // Calculate row bounds\n const maxPasteRow = target.bounds ? target.bounds.endRow : Infinity;\n\n // Apply pasted data starting at target cell\n pastedRows.forEach((rowData, rowOffset) => {\n const targetRowIndex = target.row + rowOffset;\n\n // Stop if we've exceeded the selection bounds\n if (targetRowIndex > maxPasteRow) return;\n\n // Only grow array if no bounds (single cell selection)\n if (!target.bounds) {\n while (targetRowIndex >= newRows.length) {\n const emptyRow: Record<string, unknown> = {};\n allFields.forEach((field) => (emptyRow[field] = ''));\n newRows.push(emptyRow);\n }\n } else if (targetRowIndex >= newRows.length) {\n // With bounds, don't paste beyond existing rows\n return;\n }\n\n // Clone the target row and apply values\n newRows[targetRowIndex] = { ...newRows[targetRowIndex] };\n rowData.forEach((cellValue, colOffset) => {\n // fields array is already constrained by bounds in ClipboardPlugin\n const field = fields[colOffset];\n if (field && editableMap.get(field)) {\n // Only paste into editable columns\n newRows[targetRowIndex][field] = cellValue;\n }\n });\n });\n\n // Update grid with new data\n grid.rows = newRows;\n}\n","/**\n * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatValueAsText, resolveColumns, resolveRows } from '../shared/data-collection';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type CopyOptions,\n type PasteDetail,\n type PasteTarget,\n} from './types';\n\n/**\n * Clipboard Plugin for tbw-grid\n *\n * Brings familiar copy/cut/paste functionality with full keyboard shortcut support\n * (Ctrl+C, Ctrl+X, Ctrl+V). Handles single cells, multi-cell selections, and integrates\n * seamlessly with Excel and other spreadsheet applications via tab-delimited output.\n *\n * > **Optional Dependency:** Works best with SelectionPlugin for copying/pasting selected\n * > cells. Without SelectionPlugin, copies the entire grid and pastes at row 0, column 0.\n *\n * ## Installation\n *\n * ```ts\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `includeHeaders` | `boolean` | `false` | Include column headers in copied data |\n * | `delimiter` | `string` | `'\\t'` | Column delimiter (tab for Excel compatibility) |\n * | `newline` | `string` | `'\\n'` | Row delimiter |\n * | `quoteStrings` | `boolean` | `false` | Wrap string values in quotes |\n * | `processCell` | `(value, field, row) => string` | - | Custom cell value processor |\n * | `pasteHandler` | `PasteHandler \\| null` | `defaultPasteHandler` | Custom paste handler |\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `copy` | `(options?: CopyOptions) => Promise<string>` | Copy to clipboard with optional column/row control |\n * | `copyRows` | `(indices, options?) => Promise<string>` | Copy specific rows to clipboard |\n * | `paste` | `() => Promise<string[][] \\| null>` | Read and parse clipboard content |\n * | `getSelectionAsText` | `(options?: CopyOptions) => string` | Get clipboard text without writing to clipboard |\n * | `getLastCopied` | `() => { text, timestamp } \\| null` | Get info about last copy operation |\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see {@link SelectionPlugin} for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n const el = grid as unknown as HTMLElement;\n el.addEventListener('paste', (e: Event) => this.#handleNativePaste(e as ClipboardEvent), {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n // Prevent the browser's default copy action so it doesn't overwrite\n // our clipboard write with whatever text is selected in the DOM.\n event.preventDefault();\n this.#handleCopy(event.target as HTMLElement);\n return true;\n }\n\n // For paste, we do NOT return true - let the native paste event fire\n // so we can access clipboardData synchronously in #handleNativePaste\n return false;\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Handle copy operation from keyboard shortcut.\n *\n * For keyboard-triggered copies, respects the current selection or\n * falls back to the focused cell from the DOM.\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n\n // Selection plugin exists but nothing selected → try focused cell from DOM\n if (selection && selection.ranges.length === 0) {\n const focused = this.#getFocusedCellFromDOM(target);\n if (!focused) return;\n const col = this.columns[focused.col];\n if (!col) return;\n this.copy({ rowIndices: [focused.row], columns: [col.field] });\n return;\n }\n\n // Delegate to the public copy() method (selection or full grid)\n this.copy();\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection via query\n const selection = this.#getSelection();\n const firstRange = selection?.ranges?.[0];\n\n // Determine target cell and bounds\n const targetRow = firstRange?.from.row ?? 0;\n const targetCol = firstRange?.from.col ?? 0;\n\n // Check if multi-cell selection (range with different start/end)\n const isMultiCell =\n firstRange &&\n (selection?.mode === 'range' || selection?.mode === 'row') &&\n (firstRange.from.row !== firstRange.to.row || firstRange.from.col !== firstRange.to.col);\n\n const bounds = isMultiCell ? { endRow: firstRange.to.row, endCol: firstRange.to.col } : null;\n // Selection range indices are visible-column indices (from data-col)\n const maxCol = bounds?.endCol ?? this.visibleColumns.length - 1;\n\n // Build target info\n const column = this.visibleColumns[targetCol];\n const target: PasteTarget | null = column ? { row: targetRow, col: targetCol, field: column.field, bounds } : null;\n\n // Build field list for paste width (constrained by bounds if set)\n const fields: string[] = [];\n const pasteWidth = parsed[0]?.length ?? 0;\n for (let i = 0; i < pasteWidth && targetCol + i <= maxCol; i++) {\n const col = this.visibleColumns[targetCol + i];\n if (col) {\n fields.push(col.field);\n }\n }\n\n const detail: PasteDetail = { rows: parsed, text, target, fields };\n\n // Emit the event for any listeners\n this.emit<PasteDetail>('paste', detail);\n\n // Apply paste data using the configured handler (or default)\n this.#applyPasteHandler(detail);\n }\n\n /**\n * Apply the paste handler to update grid data.\n *\n * Uses the configured `pasteHandler`, or the default handler if not specified.\n * Set `pasteHandler: null` in config to disable auto-paste.\n */\n #applyPasteHandler(detail: PasteDetail): void {\n if (!this.grid) return;\n\n const { pasteHandler } = this.config;\n\n // pasteHandler: null means explicitly disabled\n if (pasteHandler === null) return;\n\n // Use custom handler or default\n const handler = pasteHandler ?? defaultPasteHandler;\n handler(detail, this.grid);\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection');\n return responses?.[0];\n }\n\n /**\n * Resolve columns and rows to include based on options and/or current selection.\n *\n * Priority for columns:\n * 1. `options.columns` (explicit field list)\n * 2. Selection range column bounds (range/cell mode only)\n * 3. All visible non-utility columns\n *\n * Priority for rows:\n * 1. `options.rowIndices` (explicit indices)\n * 2. Selection range row bounds\n * 3. All rows\n */\n #resolveData(options?: CopyOptions): { columns: ColumnConfig[]; rows: Record<string, unknown>[] } {\n const selection = this.#getSelection();\n\n // --- Columns ---\n let columns: ColumnConfig[];\n if (options?.columns) {\n // Caller specified exact fields\n columns = resolveColumns(this.columns, options.columns);\n } else if (selection?.ranges.length && selection.mode !== 'row') {\n // Range/cell selection: restrict to selection column bounds\n // Selection indices are visible-column indices (from data-col)\n const range = selection.ranges[selection.ranges.length - 1];\n const minCol = Math.min(range.from.col, range.to.col);\n const maxCol = Math.max(range.from.col, range.to.col);\n columns = resolveColumns(this.visibleColumns.slice(minCol, maxCol + 1));\n } else {\n // Row selection or no selection: all visible columns\n columns = resolveColumns(this.columns);\n }\n\n // --- Rows ---\n let rows: Record<string, unknown>[];\n if (options?.rowIndices) {\n // Caller specified exact row indices\n rows = resolveRows(this.rows as Record<string, unknown>[], options.rowIndices);\n } else if (selection?.ranges.length) {\n // Selection range: extract contiguous row range\n const range = selection.ranges[selection.ranges.length - 1];\n const minRow = Math.min(range.from.row, range.to.row);\n const maxRow = Math.max(range.from.row, range.to.row);\n rows = [];\n for (let r = minRow; r <= maxRow; r++) {\n const row = this.rows[r] as Record<string, unknown> | undefined;\n if (row) rows.push(row);\n }\n } else {\n // No selection: all rows\n rows = this.rows as Record<string, unknown>[];\n }\n\n return { columns, rows };\n }\n\n /**\n * Build delimited text from resolved columns and rows.\n */\n #buildText(columns: ColumnConfig[], rows: Record<string, unknown>[], options?: CopyOptions): string {\n const delimiter = options?.delimiter ?? this.config.delimiter ?? '\\t';\n const newline = options?.newline ?? this.config.newline ?? '\\n';\n const includeHeaders = options?.includeHeaders ?? this.config.includeHeaders ?? false;\n const processCell = options?.processCell ?? this.config.processCell;\n\n const lines: string[] = [];\n\n // Header row\n if (includeHeaders) {\n lines.push(columns.map((c) => c.header || c.field).join(delimiter));\n }\n\n // Data rows\n for (const row of rows) {\n const cells = columns.map((col) => {\n const value = row[col.field];\n if (processCell) return processCell(value, col.field, row);\n return formatValueAsText(value);\n });\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n }\n\n /**\n * Get focused cell coordinates from DOM.\n * Used as fallback when SelectionPlugin has no selection.\n */\n #getFocusedCellFromDOM(target: HTMLElement): { row: number; col: number } | null {\n const cell = target.closest('[data-field-cache]') as HTMLElement | null;\n if (!cell) return null;\n\n const field = cell.dataset.fieldCache;\n const rowIndexStr = cell.dataset.row;\n if (!field || !rowIndexStr) return null;\n\n const row = parseInt(rowIndexStr, 10);\n if (isNaN(row)) return null;\n\n const col = this.columns.findIndex((c) => c.field === field);\n if (col === -1) return null;\n\n return { row, col };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the text representation of the current selection (or specified data)\n * without writing to the system clipboard.\n *\n * Useful for previewing what would be copied, or for feeding the text into\n * a custom UI (e.g., a \"copy with column picker\" dialog).\n *\n * @param options - Control which columns/rows to include\n * @returns Delimited text, or empty string if nothing to copy\n *\n * @example Get text for specific columns\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * const text = clipboard.getSelectionAsText({\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * console.log(text);\n * // \"Name\\tEmail\\nAlice\\talice@example.com\\n...\"\n * ```\n */\n getSelectionAsText(options?: CopyOptions): string {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) return '';\n return this.#buildText(columns, rows, options);\n }\n\n /**\n * Copy data to the system clipboard.\n *\n * Without options, copies the current selection (or entire grid if no selection).\n * With options, copies exactly the specified columns and/or rows — ideal for\n * \"copy with column picker\" workflows where the user selects rows first,\n * then chooses which columns to include via a dialog.\n *\n * @param options - Control which columns/rows to include\n * @returns The copied text\n *\n * @example Copy current selection (default)\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * await clipboard.copy();\n * ```\n *\n * @example Copy specific columns from specific rows\n * ```ts\n * // User selected rows in the grid, then picked columns in a dialog\n * const selectedRowIndices = [0, 3, 7];\n * const chosenColumns = ['name', 'department', 'salary'];\n * await clipboard.copy({\n * rowIndices: selectedRowIndices,\n * columns: chosenColumns,\n * includeHeaders: true,\n * });\n * ```\n */\n async copy(options?: CopyOptions): Promise<string> {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) {\n return '';\n }\n\n const text = this.#buildText(columns, rows, options);\n await copyToClipboard(text);\n this.lastCopied = { text, timestamp: Date.now() };\n this.emit<CopyDetail>('copy', {\n text,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n return text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n *\n * Convenience wrapper around {@link copy} for row-based workflows.\n * Supports non-contiguous row indices (e.g., `[0, 3, 7]`).\n *\n * @param indices - Array of row indices to copy\n * @param options - Additional copy options (columns, headers, etc.)\n * @returns The copied text\n *\n * @example\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * // Copy only rows 0 and 5, including just name and email columns\n * await clipboard.copyRows([0, 5], { columns: ['name', 'email'] });\n * ```\n */\n async copyRows(indices: number[], options?: Omit<CopyOptions, 'rowIndices'>): Promise<string> {\n if (indices.length === 0) return '';\n return this.copy({ ...options, rowIndices: indices });\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, CopyOptions, PasteDetail } from './types';\n","/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { ClipboardConfig } from './types';\n\n/** Parameters for building clipboard text */\nexport interface CopyParams {\n /** All grid rows */\n rows: unknown[];\n /** Column configurations */\n columns: ColumnConfig[];\n /** Selected row indices */\n selectedIndices: Set<number> | number[];\n /** Clipboard configuration */\n config: ClipboardConfig;\n}\n\n/**\n * Format a cell value for clipboard output.\n *\n * Uses custom processCell if provided, otherwise applies default formatting:\n * - null/undefined → empty string\n * - Date → ISO string\n * - Object → JSON string\n * - Other → String conversion with optional quoting\n *\n * @param value - The cell value to format\n * @param field - The field name\n * @param row - The full row object\n * @param config - Clipboard configuration\n * @returns Formatted string value\n */\nexport function formatCellValue(value: unknown, field: string, row: unknown, config: ClipboardConfig): string {\n if (config.processCell) {\n return config.processCell(value, field, row);\n }\n\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n\n const str = String(value);\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Quote if contains delimiter, newline, or quotes (or if quoteStrings is enabled)\n if (config.quoteStrings || str.includes(delimiter) || str.includes(newline) || str.includes('\"')) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build clipboard text from selected rows and columns.\n *\n * @param params - Copy parameters including rows, columns, selection, and config\n * @returns Tab-separated (or custom delimiter) text ready for clipboard\n */\nexport function buildClipboardText(params: CopyParams): string {\n const { rows, columns, selectedIndices, config } = params;\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Filter to visible columns (not hidden, not internal __ prefixed)\n const visibleColumns = columns.filter((c) => !c.hidden && !c.field.startsWith('__'));\n\n const lines: string[] = [];\n\n // Add header row if configured\n if (config.includeHeaders) {\n const headerCells = visibleColumns.map((c) => {\n const header = c.header || c.field;\n // Quote headers if they contain special characters\n if (header.includes(delimiter) || header.includes(newline) || header.includes('\"')) {\n return `\"${header.replace(/\"/g, '\"\"')}\"`;\n }\n return header;\n });\n lines.push(headerCells.join(delimiter));\n }\n\n // Convert indices to sorted array\n const indices = selectedIndices instanceof Set ? [...selectedIndices] : selectedIndices;\n const sortedIndices = [...indices].sort((a, b) => a - b);\n\n // Build data rows\n for (const idx of sortedIndices) {\n const row = rows[idx];\n if (!row) continue;\n\n const cells = visibleColumns.map((col) =>\n formatCellValue((row as Record<string, unknown>)[col.field], col.field, row, config),\n );\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n}\n\n/**\n * Copy text to the system clipboard.\n *\n * Uses the modern Clipboard API when available, with fallback\n * to execCommand for older browsers.\n *\n * @param text - The text to copy\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch (err) {\n console.warn('[copyToClipboard] Clipboard API failed:', err);\n // Fallback for older browsers or when Clipboard API is not available\n const textarea = document.createElement('textarea');\n textarea.value = text;\n textarea.style.position = 'fixed';\n textarea.style.opacity = '0';\n textarea.style.pointerEvents = 'none';\n document.body.appendChild(textarea);\n textarea.select();\n const success = document.execCommand('copy');\n document.body.removeChild(textarea);\n return success;\n }\n}\n"],"names":["resolveColumns","columns","fields","onlyVisible","result","filter","c","hidden","field","startsWith","meta","utility","length","fieldSet","Set","has","formatValueAsText","value","Date","toISOString","JSON","stringify","String","parseClipboardText","text","config","delimiter","newline","normalizedText","replace","rows","currentRow","currentCell","inQuotes","i","char","push","some","trim","defaultPasteHandler","detail","grid","pastedRows","target","currentRows","effectiveConfig","allFields","map","col","editableMap","Map","forEach","set","editable","newRows","maxPasteRow","bounds","endRow","Infinity","rowData","rowOffset","targetRowIndex","row","emptyRow","cellValue","colOffset","get","ClipboardPlugin","BaseGridPlugin","static","name","required","reason","defaultConfig","includeHeaders","quoteStrings","lastCopied","attach","super","addEventListener","e","this","handleNativePaste","signal","disconnectSignal","detach","onKeyDown","event","ctrlKey","metaKey","key","preventDefault","handleCopy","selection","getSelection","ranges","focused","getFocusedCellFromDOM","copy","rowIndices","clipboardData","getData","parsed","firstRange","targetRow","from","targetCol","mode","to","endCol","maxCol","visibleColumns","column","pasteWidth","emit","applyPasteHandler","pasteHandler","responses","query","resolveData","options","range","minCol","Math","min","max","slice","indices","sort","a","b","r","resolveRows","minRow","maxRow","buildText","processCell","lines","header","join","cells","cell","closest","dataset","fieldCache","rowIndexStr","parseInt","isNaN","findIndex","getSelectionAsText","async","navigator","clipboard","writeText","err","console","warn","textarea","document","createElement","style","position","opacity","pointerEvents","body","appendChild","select","success","execCommand","removeChild","copyToClipboard","timestamp","now","rowCount","columnCount","copyRows","paste","readText","readFromClipboard","getLastCopied"],"mappings":"mVAwBO,SAASA,EACdC,EACAC,EACAC,GAAc,GAEd,IAAIC,EAASH,EAMb,GAJIE,IACFC,EAASA,EAAOC,OAAQC,IAAOA,EAAEC,SAAWD,EAAEE,MAAMC,WAAW,QAA6B,IAApBH,EAAEI,MAAMC,UAG9ET,GAAQU,OAAQ,CAClB,MAAMC,EAAW,IAAIC,IAAIZ,GACzBE,EAASA,EAAOC,OAAQC,GAAMO,EAASE,IAAIT,EAAEE,OAC/C,CAEA,OAAOJ,CACT,CA2BO,SAASY,EAAkBC,GAChC,OAAa,MAATA,EAAsB,GACtBA,aAAiBC,KAAaD,EAAME,cACnB,iBAAVF,EAA2BG,KAAKC,UAAUJ,GAC9CK,OAAOL,EAChB,CCpDO,SAASM,EAAmBC,EAAcC,GAC/C,MAAMC,EAAYD,EAAOC,WAAa,KAChCC,EAAUF,EAAOE,SAAW,KAG5BC,EAAiBJ,EAAKK,QAAQ,QAAS,MAAMA,QAAQ,MAAO,MAG5DC,EAAmB,GACzB,IAAIC,EAAuB,GACvBC,EAAc,GACdC,GAAW,EAEf,IAAA,IAASC,EAAI,EAAGA,EAAIN,EAAehB,OAAQsB,IAAK,CAC9C,MAAMC,EAAOP,EAAeM,GAEf,MAATC,GAAiBF,EAGD,MAATE,GAAgBF,EAEK,MAA1BL,EAAeM,EAAI,IACrBF,GAAe,IACfE,KAGAD,GAAW,EAEJE,IAAST,GAAcO,EAIvBE,IAASR,GAAYM,EAU9BD,GAAeG,GARfJ,EAAWK,KAAKJ,GAChBA,EAAc,IAEVD,EAAWnB,OAAS,GAAKmB,EAAWM,KAAM/B,GAAmB,KAAbA,EAAEgC,UACpDR,EAAKM,KAAKL,GAEZA,EAAa,KAVbA,EAAWK,KAAKJ,GAChBA,EAAc,I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,cAAgB,OAC/BL,SAASM,KAAKC,YAAYR,GAC1BA,EAASS,SACT,MAAMC,EAAUT,SAASU,YAAY,QAErC,OADAV,SAASM,KAAKK,YAAYZ,GACnBU,CACT,CACF,CDwVUG,CAAgBlJ,GACtByD,KAAKL,WAAa,CAAEpD,OAAMmJ,UAAWzJ,KAAK0J,OAC1C3F,KAAKiC,KAAiB,OAAQ,CAC5B1F,OACAqJ,SAAU/I,EAAKlB,OACfkK,YAAa7K,EAAQW,SAEhBY,CACT,CAmBA,cAAMuJ,CAAShD,EAAmBP,GAChC,OAAuB,IAAnBO,EAAQnH,OAAqB,GAC1BqE,KAAKiB,KAAK,IAAKsB,EAASrB,WAAY4B,GAC7C,CAMA,WAAMiD,GACJ,MAAMxJ,QF5aV8H,iBACE,IACE,aAAaC,UAAUC,UAAUyB,UACnC,CAAA,MAEE,MAAO,EACT,CACF,CEqauBC,GACnB,OAAK1J,EACED,EAAmBC,EAAMyD,KAAKxD,QADnB,IAEpB,CAMA,aAAA0J,GACE,OAAOlG,KAAKL,UACd"}
|
|
1
|
+
{"version":3,"file":"clipboard.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../libs/grid/src/lib/plugins/clipboard/ClipboardPlugin.ts","../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts"],"sourcesContent":["/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.meta?.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n","/**\n * Clipboard Paste Logic\n *\n * Pure functions for reading and parsing clipboard data.\n */\n\nimport type { ClipboardConfig } from './types';\n\n/**\n * Parse clipboard text into a 2D array of cell values.\n *\n * Handles:\n * - Quoted values (with escaped double quotes \"\")\n * - Multi-line quoted values (newlines within quotes are preserved)\n * - Custom delimiters and newlines\n * - Empty lines (filtered out only if they contain no data)\n *\n * @param text - Raw clipboard text\n * @param config - Clipboard configuration\n * @returns 2D array where each sub-array is a row of cell values\n */\nexport function parseClipboardText(text: string, config: ClipboardConfig): string[][] {\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Handle Windows CRLF line endings\n const normalizedText = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n // Parse the entire text handling quoted fields that may span multiple lines\n const rows: string[][] = [];\n let currentRow: string[] = [];\n let currentCell = '';\n let inQuotes = false;\n\n for (let i = 0; i < normalizedText.length; i++) {\n const char = normalizedText[i];\n\n if (char === '\"' && !inQuotes) {\n // Start of quoted field\n inQuotes = true;\n } else if (char === '\"' && inQuotes) {\n // Check for escaped quote (\"\")\n if (normalizedText[i + 1] === '\"') {\n currentCell += '\"';\n i++; // Skip the second quote\n } else {\n // End of quoted field\n inQuotes = false;\n }\n } else if (char === delimiter && !inQuotes) {\n // Field separator\n currentRow.push(currentCell);\n currentCell = '';\n } else if (char === newline && !inQuotes) {\n // Row separator (only if not inside quotes)\n currentRow.push(currentCell);\n currentCell = '';\n // Only add non-empty rows (at least one non-empty cell or multiple cells)\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n currentRow = [];\n } else {\n currentCell += char;\n }\n }\n\n // Handle the last cell and row\n currentRow.push(currentCell);\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n\n return rows;\n}\n\n/**\n * Read text from the system clipboard.\n *\n * Uses the modern Clipboard API. Returns empty string if\n * the API is not available or permission is denied.\n *\n * @returns Promise resolving to clipboard text or empty string\n */\nexport async function readFromClipboard(): Promise<string> {\n try {\n return await navigator.clipboard.readText();\n } catch {\n // Permission denied or API not available\n return '';\n }\n}\n","/**\n * Clipboard Plugin Types\n *\n * Type definitions for clipboard copy/paste functionality.\n */\n\nimport type { GridElement } from '../../core/plugin/base-plugin';\n\n/**\n * Custom paste handler function.\n *\n * @param detail - The parsed paste data with target and field info\n * @param grid - The grid element to update\n * @returns `false` to prevent the default paste behavior, or `void`/`true` to allow it\n *\n * @example\n * ```ts\n * // Custom handler that validates before pasting\n * new ClipboardPlugin({\n * pasteHandler: (detail, grid) => {\n * if (!detail.target) return false;\n * // Apply custom validation/transformation...\n * applyPasteData(detail, grid);\n * return false; // We handled it, skip default\n * }\n * })\n * ```\n */\nexport type PasteHandler = (detail: PasteDetail, grid: GridElement) => boolean | void;\n\n/**\n * Options for programmatic copy operations.\n *\n * Allows callers to control exactly which columns and rows are included\n * in a copy, independently of the current selection state.\n *\n * @example Copy specific columns from selected rows\n * ```ts\n * const clipboard = grid.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// Module Augmentation - Register plugin name for type-safe getPluginByName()\ndeclare module '../../core/types' {\n interface PluginNameMap {\n clipboard: import('./ClipboardPlugin').ClipboardPlugin;\n }\n}\n","/**\n * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatValueAsText, resolveColumns, resolveRows } from '../shared/data-collection';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type CopyOptions,\n type PasteDetail,\n type PasteTarget,\n} from './types';\n\n/**\n * Clipboard Plugin for tbw-grid\n *\n * Brings familiar copy/cut/paste functionality with full keyboard shortcut support\n * (Ctrl+C, Ctrl+X, Ctrl+V). Handles single cells, multi-cell selections, and integrates\n * seamlessly with Excel and other spreadsheet applications via tab-delimited output.\n *\n * > **Optional Dependency:** Works best with SelectionPlugin for copying/pasting selected\n * > cells. Without SelectionPlugin, copies the entire grid and pastes at row 0, column 0.\n *\n * ## Installation\n *\n * ```ts\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `includeHeaders` | `boolean` | `false` | Include column headers in copied data |\n * | `delimiter` | `string` | `'\\t'` | Column delimiter (tab for Excel compatibility) |\n * | `newline` | `string` | `'\\n'` | Row delimiter |\n * | `quoteStrings` | `boolean` | `false` | Wrap string values in quotes |\n * | `processCell` | `(value, field, row) => string` | - | Custom cell value processor |\n * | `pasteHandler` | `PasteHandler \\| null` | `defaultPasteHandler` | Custom paste handler |\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `copy` | `(options?: CopyOptions) => Promise<string>` | Copy to clipboard with optional column/row control |\n * | `copyRows` | `(indices, options?) => Promise<string>` | Copy specific rows to clipboard |\n * | `paste` | `() => Promise<string[][] \\| null>` | Read and parse clipboard content |\n * | `getSelectionAsText` | `(options?: CopyOptions) => string` | Get clipboard text without writing to clipboard |\n * | `getLastCopied` | `() => { text, timestamp } \\| null` | Get info about last copy operation |\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see {@link SelectionPlugin} for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n const el = grid as unknown as HTMLElement;\n el.addEventListener('paste', (e: Event) => this.#handleNativePaste(e as ClipboardEvent), {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n // Prevent the browser's default copy action so it doesn't overwrite\n // our clipboard write with whatever text is selected in the DOM.\n event.preventDefault();\n this.#handleCopy(event.target as HTMLElement);\n return true;\n }\n\n // For paste, we do NOT return true - let the native paste event fire\n // so we can access clipboardData synchronously in #handleNativePaste\n return false;\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Handle copy operation from keyboard shortcut.\n *\n * For keyboard-triggered copies, respects the current selection or\n * falls back to the focused cell from the DOM.\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n\n // Selection plugin exists but nothing selected → try focused cell from DOM\n if (selection && selection.ranges.length === 0) {\n const focused = this.#getFocusedCellFromDOM(target);\n if (!focused) return;\n const col = this.columns[focused.col];\n if (!col) return;\n this.copy({ rowIndices: [focused.row], columns: [col.field] });\n return;\n }\n\n // Delegate to the public copy() method (selection or full grid)\n this.copy();\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection via query\n const selection = this.#getSelection();\n const firstRange = selection?.ranges?.[0];\n\n // Determine target cell and bounds\n const targetRow = firstRange?.from.row ?? 0;\n const targetCol = firstRange?.from.col ?? 0;\n\n // Check if multi-cell selection (range with different start/end)\n const isMultiCell =\n firstRange &&\n (selection?.mode === 'range' || selection?.mode === 'row') &&\n (firstRange.from.row !== firstRange.to.row || firstRange.from.col !== firstRange.to.col);\n\n const bounds = isMultiCell ? { endRow: firstRange.to.row, endCol: firstRange.to.col } : null;\n // Selection range indices are visible-column indices (from data-col)\n const maxCol = bounds?.endCol ?? this.visibleColumns.length - 1;\n\n // Build target info\n const column = this.visibleColumns[targetCol];\n const target: PasteTarget | null = column ? { row: targetRow, col: targetCol, field: column.field, bounds } : null;\n\n // Build field list for paste width (constrained by bounds if set)\n const fields: string[] = [];\n const pasteWidth = parsed[0]?.length ?? 0;\n for (let i = 0; i < pasteWidth && targetCol + i <= maxCol; i++) {\n const col = this.visibleColumns[targetCol + i];\n if (col) {\n fields.push(col.field);\n }\n }\n\n const detail: PasteDetail = { rows: parsed, text, target, fields };\n\n // Emit the event for any listeners\n this.emit<PasteDetail>('paste', detail);\n\n // Apply paste data using the configured handler (or default)\n this.#applyPasteHandler(detail);\n }\n\n /**\n * Apply the paste handler to update grid data.\n *\n * Uses the configured `pasteHandler`, or the default handler if not specified.\n * Set `pasteHandler: null` in config to disable auto-paste.\n */\n #applyPasteHandler(detail: PasteDetail): void {\n if (!this.grid) return;\n\n const { pasteHandler } = this.config;\n\n // pasteHandler: null means explicitly disabled\n if (pasteHandler === null) return;\n\n // Use custom handler or default\n const handler = pasteHandler ?? defaultPasteHandler;\n handler(detail, this.grid);\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection');\n return responses?.[0];\n }\n\n /**\n * Resolve columns and rows to include based on options and/or current selection.\n *\n * Priority for columns:\n * 1. `options.columns` (explicit field list)\n * 2. Selection range column bounds (range/cell mode only)\n * 3. All visible non-utility columns\n *\n * Priority for rows:\n * 1. `options.rowIndices` (explicit indices)\n * 2. Selection range row bounds\n * 3. All rows\n */\n #resolveData(options?: CopyOptions): { columns: ColumnConfig[]; rows: Record<string, unknown>[] } {\n const selection = this.#getSelection();\n\n // --- Columns ---\n let columns: ColumnConfig[];\n if (options?.columns) {\n // Caller specified exact fields\n columns = resolveColumns(this.columns, options.columns);\n } else if (selection?.ranges.length && selection.mode !== 'row') {\n // Range/cell selection: restrict to selection column bounds\n // Selection indices are visible-column indices (from data-col)\n const range = selection.ranges[selection.ranges.length - 1];\n const minCol = Math.min(range.from.col, range.to.col);\n const maxCol = Math.max(range.from.col, range.to.col);\n columns = resolveColumns(this.visibleColumns.slice(minCol, maxCol + 1));\n } else {\n // Row selection or no selection: all visible columns\n columns = resolveColumns(this.columns);\n }\n\n // --- Rows ---\n let rows: Record<string, unknown>[];\n if (options?.rowIndices) {\n // Caller specified exact row indices\n rows = resolveRows(this.rows as Record<string, unknown>[], options.rowIndices);\n } else if (selection?.ranges.length) {\n // Selection range: extract contiguous row range\n const range = selection.ranges[selection.ranges.length - 1];\n const minRow = Math.min(range.from.row, range.to.row);\n const maxRow = Math.max(range.from.row, range.to.row);\n rows = [];\n for (let r = minRow; r <= maxRow; r++) {\n const row = this.rows[r] as Record<string, unknown> | undefined;\n if (row) rows.push(row);\n }\n } else {\n // No selection: all rows\n rows = this.rows as Record<string, unknown>[];\n }\n\n return { columns, rows };\n }\n\n /**\n * Build delimited text from resolved columns and rows.\n */\n #buildText(columns: ColumnConfig[], rows: Record<string, unknown>[], options?: CopyOptions): string {\n const delimiter = options?.delimiter ?? this.config.delimiter ?? '\\t';\n const newline = options?.newline ?? this.config.newline ?? '\\n';\n const includeHeaders = options?.includeHeaders ?? this.config.includeHeaders ?? false;\n const processCell = options?.processCell ?? this.config.processCell;\n\n const lines: string[] = [];\n\n // Header row\n if (includeHeaders) {\n lines.push(columns.map((c) => c.header || c.field).join(delimiter));\n }\n\n // Data rows\n for (const row of rows) {\n const cells = columns.map((col) => {\n const value = row[col.field];\n if (processCell) return processCell(value, col.field, row);\n return formatValueAsText(value);\n });\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n }\n\n /**\n * Get focused cell coordinates from DOM.\n * Used as fallback when SelectionPlugin has no selection.\n */\n #getFocusedCellFromDOM(target: HTMLElement): { row: number; col: number } | null {\n const cell = target.closest('[data-field-cache]') as HTMLElement | null;\n if (!cell) return null;\n\n const field = cell.dataset.fieldCache;\n const rowIndexStr = cell.dataset.row;\n if (!field || !rowIndexStr) return null;\n\n const row = parseInt(rowIndexStr, 10);\n if (isNaN(row)) return null;\n\n const col = this.columns.findIndex((c) => c.field === field);\n if (col === -1) return null;\n\n return { row, col };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the text representation of the current selection (or specified data)\n * without writing to the system clipboard.\n *\n * Useful for previewing what would be copied, or for feeding the text into\n * a custom UI (e.g., a \"copy with column picker\" dialog).\n *\n * @param options - Control which columns/rows to include\n * @returns Delimited text, or empty string if nothing to copy\n *\n * @example Get text for specific columns\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * const text = clipboard.getSelectionAsText({\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * console.log(text);\n * // \"Name\\tEmail\\nAlice\\talice@example.com\\n...\"\n * ```\n */\n getSelectionAsText(options?: CopyOptions): string {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) return '';\n return this.#buildText(columns, rows, options);\n }\n\n /**\n * Copy data to the system clipboard.\n *\n * Without options, copies the current selection (or entire grid if no selection).\n * With options, copies exactly the specified columns and/or rows — ideal for\n * \"copy with column picker\" workflows where the user selects rows first,\n * then chooses which columns to include via a dialog.\n *\n * @param options - Control which columns/rows to include\n * @returns The copied text\n *\n * @example Copy current selection (default)\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * await clipboard.copy();\n * ```\n *\n * @example Copy specific columns from specific rows\n * ```ts\n * // User selected rows in the grid, then picked columns in a dialog\n * const selectedRowIndices = [0, 3, 7];\n * const chosenColumns = ['name', 'department', 'salary'];\n * await clipboard.copy({\n * rowIndices: selectedRowIndices,\n * columns: chosenColumns,\n * includeHeaders: true,\n * });\n * ```\n */\n async copy(options?: CopyOptions): Promise<string> {\n const { columns, rows } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) {\n return '';\n }\n\n const text = this.#buildText(columns, rows, options);\n await copyToClipboard(text);\n this.lastCopied = { text, timestamp: Date.now() };\n this.emit<CopyDetail>('copy', {\n text,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n return text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n *\n * Convenience wrapper around {@link copy} for row-based workflows.\n * Supports non-contiguous row indices (e.g., `[0, 3, 7]`).\n *\n * @param indices - Array of row indices to copy\n * @param options - Additional copy options (columns, headers, etc.)\n * @returns The copied text\n *\n * @example\n * ```ts\n * const clipboard = grid.getPlugin(ClipboardPlugin);\n * // Copy only rows 0 and 5, including just name and email columns\n * await clipboard.copyRows([0, 5], { columns: ['name', 'email'] });\n * ```\n */\n async copyRows(indices: number[], options?: Omit<CopyOptions, 'rowIndices'>): Promise<string> {\n if (indices.length === 0) return '';\n return this.copy({ ...options, rowIndices: indices });\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, CopyOptions, PasteDetail } from './types';\n","/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { ClipboardConfig } from './types';\n\n/** Parameters for building clipboard text */\nexport interface CopyParams {\n /** All grid rows */\n rows: unknown[];\n /** Column configurations */\n columns: ColumnConfig[];\n /** Selected row indices */\n selectedIndices: Set<number> | number[];\n /** Clipboard configuration */\n config: ClipboardConfig;\n}\n\n/**\n * Format a cell value for clipboard output.\n *\n * Uses custom processCell if provided, otherwise applies default formatting:\n * - null/undefined → empty string\n * - Date → ISO string\n * - Object → JSON string\n * - Other → String conversion with optional quoting\n *\n * @param value - The cell value to format\n * @param field - The field name\n * @param row - The full row object\n * @param config - Clipboard configuration\n * @returns Formatted string value\n */\nexport function formatCellValue(value: unknown, field: string, row: unknown, config: ClipboardConfig): string {\n if (config.processCell) {\n return config.processCell(value, field, row);\n }\n\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n\n const str = String(value);\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Quote if contains delimiter, newline, or quotes (or if quoteStrings is enabled)\n if (config.quoteStrings || str.includes(delimiter) || str.includes(newline) || str.includes('\"')) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n\n return str;\n}\n\n/**\n * Build clipboard text from selected rows and columns.\n *\n * @param params - Copy parameters including rows, columns, selection, and config\n * @returns Tab-separated (or custom delimiter) text ready for clipboard\n */\nexport function buildClipboardText(params: CopyParams): string {\n const { rows, columns, selectedIndices, config } = params;\n const delimiter = config.delimiter ?? '\\t';\n const newline = config.newline ?? '\\n';\n\n // Filter to visible columns (not hidden, not internal __ prefixed)\n const visibleColumns = columns.filter((c) => !c.hidden && !c.field.startsWith('__'));\n\n const lines: string[] = [];\n\n // Add header row if configured\n if (config.includeHeaders) {\n const headerCells = visibleColumns.map((c) => {\n const header = c.header || c.field;\n // Quote headers if they contain special characters\n if (header.includes(delimiter) || header.includes(newline) || header.includes('\"')) {\n return `\"${header.replace(/\"/g, '\"\"')}\"`;\n }\n return header;\n });\n lines.push(headerCells.join(delimiter));\n }\n\n // Convert indices to sorted array\n const indices = selectedIndices instanceof Set ? [...selectedIndices] : selectedIndices;\n const sortedIndices = [...indices].sort((a, b) => a - b);\n\n // Build data rows\n for (const idx of sortedIndices) {\n const row = rows[idx];\n if (!row) continue;\n\n const cells = visibleColumns.map((col) =>\n formatCellValue((row as Record<string, unknown>)[col.field], col.field, row, config),\n );\n lines.push(cells.join(delimiter));\n }\n\n return lines.join(newline);\n}\n\n/**\n * Copy text to the system clipboard.\n *\n * Uses the modern Clipboard API when available, with fallback\n * to execCommand for older browsers.\n *\n * @param text - The text to copy\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch (err) {\n console.warn('[copyToClipboard] Clipboard API failed:', err);\n // Fallback for older browsers or when Clipboard API is not available\n const textarea = document.createElement('textarea');\n textarea.value = text;\n textarea.style.position = 'fixed';\n textarea.style.opacity = '0';\n textarea.style.pointerEvents = 'none';\n document.body.appendChild(textarea);\n textarea.select();\n const success = document.execCommand('copy');\n document.body.removeChild(textarea);\n return success;\n }\n}\n"],"names":["resolveColumns","columns","fields","onlyVisible","result","filter","c","hidden","field","startsWith","meta","utility","length","fieldSet","Set","has","formatValueAsText","value","Date","toISOString","JSON","stringify","String","parseClipboardText","text","config","delimiter","newline","normalizedText","replace","rows","currentRow","currentCell","inQuotes","i","char","push","some","trim","defaultPasteHandler","detail","grid","pastedRows","target","currentRows","effectiveConfig","allFields","map","col","editableMap","Map","forEach","set","editable","newRows","maxPasteRow","bounds","endRow","Infinity","rowData","rowOffset","targetRowIndex","row","emptyRow","cellValue","colOffset","get","ClipboardPlugin","BaseGridPlugin","static","name","required","reason","defaultConfig","includeHeaders","quoteStrings","lastCopied","attach","super","addEventListener","e","this","handleNativePaste","signal","disconnectSignal","detach","onKeyDown","event","ctrlKey","metaKey","key","preventDefault","handleCopy","selection","getSelection","ranges","focused","getFocusedCellFromDOM","copy","rowIndices","clipboardData","getData","parsed","firstRange","targetRow","from","targetCol","mode","to","endCol","maxCol","visibleColumns","column","pasteWidth","emit","applyPasteHandler","pasteHandler","responses","query","resolveData","options","range","minCol","Math","min","max","slice","indices","sort","a","b","r","resolveRows","minRow","maxRow","buildText","processCell","lines","header","join","cells","cell","closest","dataset","fieldCache","rowIndexStr","parseInt","isNaN","findIndex","getSelectionAsText","async","navigator","clipboard","writeText","err","console","warn","textarea","document","createElement","style","position","opacity","pointerEvents","body","appendChild","select","success","execCommand","removeChild","copyToClipboard","timestamp","now","rowCount","columnCount","copyRows","paste","readText","readFromClipboard","getLastCopied"],"mappings":"mVAwBO,SAASA,EACdC,EACAC,EACAC,GAAc,GAEd,IAAIC,EAASH,EAMb,GAJIE,IACFC,EAASA,EAAOC,OAAQC,IAAOA,EAAEC,SAAWD,EAAEE,MAAMC,WAAW,QAA6B,IAApBH,EAAEI,MAAMC,UAG9ET,GAAQU,OAAQ,CAClB,MAAMC,EAAW,IAAIC,IAAIZ,GACzBE,EAASA,EAAOC,OAAQC,GAAMO,EAASE,IAAIT,EAAEE,OAC/C,CAEA,OAAOJ,CACT,CA2BO,SAASY,EAAkBC,GAChC,OAAa,MAATA,EAAsB,GACtBA,aAAiBC,KAAaD,EAAME,cACnB,iBAAVF,EAA2BG,KAAKC,UAAUJ,GAC9CK,OAAOL,EAChB,CCpDO,SAASM,EAAmBC,EAAcC,GAC/C,MAAMC,EAAYD,EAAOC,WAAa,KAChCC,EAAUF,EAAOE,SAAW,KAG5BC,EAAiBJ,EAAKK,QAAQ,QAAS,MAAMA,QAAQ,MAAO,MAG5DC,EAAmB,GACzB,IAAIC,EAAuB,GACvBC,EAAc,GACdC,GAAW,EAEf,IAAA,IAASC,EAAI,EAAGA,E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D,MAAKsC,EAAaC,GAC5C,GAAuB,IAAnBvH,EAAQW,QAAgC,IAAhBkB,EAAKlB,OAC/B,MAAO,GAGT,MAAMY,EAAOyD,MAAKsD,EAAWtI,EAAS6B,EAAM0F,GAQ5C,aCjXJ8B,eAAsC9H,GACpC,IAEE,aADM+H,UAAUC,UAAUC,UAAUjI,IAC7B,CACT,OAASkI,GACPC,QAAQC,KAAK,0CAA2CF,GAExD,MAAMG,EAAWC,SAASC,cAAc,YACxCF,EAAS5I,MAAQO,EACjBqI,EAASG,MAAMC,SAAW,QAC1BJ,EAASG,MAAME,QAAU,IACzBL,EAASG,MAAMG,cAAgB,OAC/BL,SAASM,KAAKC,YAAYR,GAC1BA,EAASS,SACT,MAAMC,EAAUT,SAASU,YAAY,QAErC,OADAV,SAASM,KAAKK,YAAYZ,GACnBU,CACT,CACF,CDwVUG,CAAgBlJ,GACtByD,KAAKL,WAAa,CAAEpD,OAAMmJ,UAAWzJ,KAAK0J,OAC1C3F,KAAKiC,KAAiB,OAAQ,CAC5B1F,OACAqJ,SAAU/I,EAAKlB,OACfkK,YAAa7K,EAAQW,SAEhBY,CACT,CAmBA,cAAMuJ,CAAShD,EAAmBP,GAChC,OAAuB,IAAnBO,EAAQnH,OAAqB,GAC1BqE,KAAKiB,KAAK,IAAKsB,EAASrB,WAAY4B,GAC7C,CAMA,WAAMiD,GACJ,MAAMxJ,QF5aV8H,iBACE,IACE,aAAaC,UAAUC,UAAUyB,UACnC,CAAA,MAEE,MAAO,EACT,CACF,CEqauBC,GACnB,OAAK1J,EACED,EAAmBC,EAAMyD,KAAKxD,QADnB,IAEpB,CAMA,aAAA0J,GACE,OAAOlG,KAAKL,UACd"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/keyboard"),require("../../core/internal/rows"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/keyboard","../../core/internal/rows","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_editing={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,i,n){"use strict";function o(e){switch(e.type){case"number":return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");n.type="number",n.value=null!=t.value?String(t.value):"",void 0!==i?.min&&(n.min=String(i.min)),void 0!==i?.max&&(n.max=String(i.max)),void 0!==i?.step&&(n.step=String(i.step)),i?.placeholder&&(n.placeholder=i.placeholder);const o=()=>t.commit(""===n.value?null:Number(n.value));return n.addEventListener("blur",o),n.addEventListener("keydown",e=>{"Enter"===e.key&&o(),"Escape"===e.key&&t.cancel()}),n}}(e);case"boolean":return e=>{const t=document.createElement("input");return t.type="checkbox",t.checked=!!e.value,t.addEventListener("change",()=>e.commit(t.checked)),t};case"date":return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");return n.type="date",t.value instanceof Date?n.valueAsDate=t.value:"string"==typeof t.value&&t.value&&(n.value=t.value.split("T")[0]),i?.min&&(n.min=i.min),i?.max&&(n.max=i.max),i?.placeholder&&(n.placeholder=i.placeholder),n.addEventListener("change",()=>{"string"==typeof t.value?t.commit(n.value):t.commit(n.valueAsDate)}),n.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),n}}(e);case"select":return function(e){return t=>{const i=e.editorParams,n=document.createElement("select");if(e.multi&&(n.multiple=!0),i?.includeEmpty){const e=document.createElement("option");e.value="",e.textContent=i.emptyLabel??"",n.appendChild(e)}const o=function(e){const t=e.options;return t?"function"==typeof t?t():t:[]}(e);o.forEach(i=>{const o=document.createElement("option");o.value=String(i.value),o.textContent=i.label,e.multi&&Array.isArray(t.value)&&t.value.includes(i.value)?o.selected=!0:e.multi||t.value!==i.value||(o.selected=!0),n.appendChild(o)});const r=()=>{if(e.multi){const e=Array.from(n.selectedOptions).map(e=>e.value);t.commit(e)}else t.commit(n.value)};return n.addEventListener("change",r),n.addEventListener("blur",r),n.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),n}}(e);default:return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");n.type="text",n.value=null!=t.value?String(t.value):"",void 0!==i?.maxLength&&(n.maxLength=i.maxLength),i?.pattern&&(n.pattern=i.pattern),i?.placeholder&&(n.placeholder=i.placeholder);const o=()=>{const e=n.value;(null!==t.value&&void 0!==t.value||""!==e)&&("string"==typeof t.value&&e===t.value.replace(/[\n\r]/g,"")||("number"==typeof t.value&&""!==e?t.commit(Number(e)):t.commit(e)))};return n.addEventListener("blur",o),n.addEventListener("keydown",e=>{"Enter"===e.key&&o(),"Escape"===e.key&&t.cancel()}),n}}(e)}}function r(e){return"string"==typeof e&&("__proto__"!==e&&"constructor"!==e&&"prototype"!==e)}function s(e,t,i){return e instanceof HTMLInputElement?"checkbox"===e.type?e.checked:"number"===e.type?""===e.value?null:Number(e.value):"date"===e.type?"string"==typeof i?e.value:e.valueAsDate:"number"==typeof i?""===e.value?null:Number(e.value):null==i&&""===e.value||"string"==typeof i&&e.value===i.replace(/[\n\r]/g,"")?i:e.value:"number"===t?.type&&""!==e.value||"number"==typeof i&&""!==e.value?Number(e.value):null==i&&""===e.value?i:e.value}function d(e){}class l extends n.BaseGridPlugin{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>!0===e},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'}],events:[{type:"cell-edit-committed",description:"Emitted when a cell edit is committed (for plugin-to-plugin coordination)"}],queries:[{type:"isEditing",description:"Returns whether any cell is currently being edited"}]};name="editing";styles="@layer tbw-plugins{tbw-grid{--tbw-editing-bg: var(--tbw-color-selection);--tbw-editing-row-bg: var(--tbw-editing-bg);--tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));--tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);--tbw-font-size-editor: inherit;--tbw-editing-row-outline-color: var(--tbw-color-accent);--tbw-editing-row-outline-width: 1px;--tbw-invalid-bg: light-dark(#fef2f2, #450a0a);--tbw-invalid-border-color: light-dark(#ef4444, #f87171)}tbw-grid:not(.tbw-grid-mode) .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:calc(var(--tbw-row-height) + 2px);align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}tbw-grid .data-grid-row>.cell[data-invalid=true]{background:var(--tbw-invalid-bg);outline:1px solid var(--tbw-invalid-border-color);outline-offset:-1px}}";get defaultConfig(){return{mode:"row",editOn:"click"}}get#e(){return"grid"===this.config.mode}#t=-1;#i;#n;#o=-1;#r=new Map;#s=new Set;#d=new Set;#l=new Map;#c=!1;#a=-1;#u=new Map;#h=!1;#f=!1;#g=!1;attach(e){super.attach(e);const t=this.disconnectSignal,n=e;n._activeEditRows=-1,n._rowEditSnapshots=new Map,Object.defineProperty(e,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(e,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),e.resetChangedRows=e=>this.resetChangedRows(e),e.beginBulkEdit=(e,t)=>{t&&this.beginCellEdit(e,t)},document.addEventListener("keydown",e=>{if(!this.#e&&"Escape"===e.key&&-1!==this.#t){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}this.#w(this.#t,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",e=>{if(this.#e)return;if(-1===this.#t)return;const t=n.findRenderedRowElement?.(this.#t);if(!t)return;if(!(e.composedPath&&e.composedPath()||[]).includes(t)){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}queueMicrotask(()=>{-1!==this.#t&&this.#w(this.#t,!1)})}},{signal:t}),this.gridElement.addEventListener("cell-change",e=>{const t=e.detail;if("user"===t.source)return;const i=`${t.rowIndex}:${t.field}`,n=this.#l.get(i);n&&n(t.newValue)},{signal:t}),this.#e&&(n._isGridEditMode=!0,this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",e=>{const t=e.target;if(t.matches(i.FOCUSABLE_EDITOR_SELECTOR)){if(this.#f)return t.blur(),void this.gridElement.focus();this.#h=!0}},{signal:t}),this.gridElement.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&this.gridElement.contains(t)&&t.matches(i.FOCUSABLE_EDITOR_SELECTOR)||(this.#h=!1)},{signal:t}),this.gridElement.addEventListener("keydown",e=>{if("Escape"===e.key&&this.#h){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}const t=document.activeElement;t&&this.gridElement.contains(t)&&(t.blur(),this.gridElement.focus()),this.#h=!1,this.#f=!0,e.preventDefault(),e.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",e=>{e.target.matches(i.FOCUSABLE_EDITOR_SELECTOR)&&(this.#f=!1)},{signal:t}))}detach(){this.gridElement._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#t=-1,this.#i=void 0,this.#n=void 0,this.#o=-1,this.#r.clear(),this.#s.clear(),this.#d.clear(),this.#l.clear(),this.#h=!1,this.#f=!1,this.#g=!1,super.detach()}handleQuery(e){if("isEditing"===e.type)return this.#e||-1!==this.#t}onCellClick(e){if(this.#e)return!1;const t=this.grid,i=this.config.editOn??t.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;if("click"!==i&&"dblclick"!==i)return!1;const n="dblclick"===e.originalEvent.type;if("click"===i&&n)return!1;if("dblclick"===i&&!n)return!1;const{rowIndex:o}=e,r=t._columns?.some(e=>e.editable);return!!r&&(e.originalEvent.stopPropagation(),this.beginBulkEdit(o),!0)}onKeyDown(e){const i=this.grid;if("Escape"===e.key){if(this.#e&&this.#h){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}const t=document.activeElement;return t&&this.gridElement.contains(t)&&t.blur(),this.#h=!1,this.requestAfterRender(),!0}if(-1!==this.#t&&!this.#e){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}return this.#w(this.#t,!0),!0}}if(this.#e&&!this.#h&&("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key))return!1;if(this.#e&&this.#h&&("ArrowUp"===e.key||"ArrowDown"===e.key))return!0;if(("ArrowUp"===e.key||"ArrowDown"===e.key)&&-1!==this.#t&&!this.#e){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}const n=i._rows.length-1,o=this.#t;return this.#w(o,!1),"ArrowDown"===e.key?i._focusRow=Math.min(n,i._focusRow+1):i._focusRow=Math.max(0,i._focusRow-1),e.preventDefault(),t.ensureCellVisible(i),this.requestAfterRender(),!0}if("Tab"===e.key&&(-1!==this.#t||this.#e)){if(e.preventDefault(),this.#g)return this.#w(this.#t,!1),!0;const t=!e.shiftKey;return this.#E(t),!0}if(" "===e.key||"Spacebar"===e.key){if(-1!==this.#t)return!1;const t=i._focusRow,n=i._focusCol;if(t>=0&&n>=0){const o=i._visibleColumns[n],s=i._rows[t];if(o?.editable&&"boolean"===o.type&&s){const i=o.field;if(r(i)){const n=!s[i];return this.#p(t,o,n,s),e.preventDefault(),this.requestRender(),!0}}}return!1}if(!("Enter"!==e.key||e.shiftKey||e.ctrlKey||e.altKey||e.metaKey)){if(this.#e&&!this.#h)return this.#v(),!0;if(-1!==this.#t){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}return!1}const t=this.config.editOn??i.effectiveConfig?.editOn;if(!1===t||"manual"===t)return!1;const n=i._focusRow,o=i._focusCol;if(n>=0){const t=i._columns?.some(e=>e.editable);if(t){const t=i._visibleColumns[o],r=i._rows[n],s=t?.field??"",d=s&&r?r[s]:void 0,l=this.gridElement.querySelector(`[data-row="${n}"][data-col="${o}"]`),c=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:n,colIndex:o,field:s,value:d,row:r,cellEl:l,trigger:"keyboard",originalEvent:e}});this.gridElement.dispatchEvent(c);const a=new CustomEvent("activate-cell",{cancelable:!0,bubbles:!0,detail:{row:n,col:o}});return this.gridElement.dispatchEvent(a),c.defaultPrevented||a.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(n),!0)}}return!1}if("F2"===e.key){if(-1!==this.#t||this.#e)return!1;if(!1===(this.config.editOn??i.effectiveConfig?.editOn))return!1;const t=i._focusRow,n=i._focusCol;if(t>=0&&n>=0){const o=i._visibleColumns[n];if(o?.editable&&o.field)return e.preventDefault(),this.beginCellEdit(t,o.field),!0}return!1}return!1}processColumns(e){const t=this.grid,i=t.effectiveConfig?.typeDefaults,n=t.__frameworkAdapter;return i||n?.getTypeDefault?e.map(e=>{if(!e.type)return e;let t;if(i?.[e.type]?.editorParams&&(t=i[e.type].editorParams),!t&&n?.getTypeDefault){const i=n.getTypeDefault(e.type);i?.editorParams&&(t=i.editorParams)}return t?{...e,editorParams:{...t,...e.editorParams}}:e}):e}afterRender(){const e=this.grid;if(this.#c&&(this.#c=!1,this.#m(e)),-1!==this.#a){const t=this.#a;this.#a=-1,e.animateRow?.(t,"change")}if(!this.#e&&0!==this.#d.size)for(const t of this.#d){const[i,n]=t.split(":"),o=parseInt(i,10),r=parseInt(n,10),s=e.findRenderedRowElement?.(o);if(!s)continue;const d=s.querySelector(`.cell[data-col="${r}"]`);if(!d||d.classList.contains("editing"))continue;const l=e._rows[o],c=e._visibleColumns[r];l&&c&&this.#b(l,o,c,r,d,!0)}}afterCellRender(e){if(!this.#e)return;const{row:t,rowIndex:i,column:n,colIndex:o,cellElement:r}=e;n.editable&&(r.classList.contains("editing")||this.#b(t,i,n,o,r,!0))}onScrollRender(){this.afterRender()}get changedRows(){const e=[];for(const t of this.#s){const i=this.grid.getRow(t);i&&e.push(i)}return e}get changedRowIds(){return Array.from(this.#s)}get activeEditRow(){return this.#t}get activeEditCol(){return this.#o}isRowEditing(e){return this.#t===e}isCellEditing(e,t){return this.#d.has(`${e}:${t}`)}isRowChanged(e){const t=this.grid,i=t._rows[e];if(!i)return!1;try{const e=t.getRowId?.(i);return!!e&&this.#s.has(e)}catch{return!1}}isRowChangedById(e){return this.#s.has(e)}setInvalid(e,t,i=""){let n=this.#u.get(e);n||(n=new Map,this.#u.set(e,n)),n.set(t,i),this.#R(e,t,!0)}clearInvalid(e,t){const i=this.#u.get(e);i&&(i.delete(t),0===i.size&&this.#u.delete(e)),this.#R(e,t,!1)}clearRowInvalid(e){const t=this.#u.get(e);if(t){const i=Array.from(t.keys());this.#u.delete(e),i.forEach(t=>this.#R(e,t,!1))}}clearAllInvalid(){const e=Array.from(this.#u.entries());this.#u.clear(),e.forEach(([e,t])=>{t.forEach((t,i)=>this.#R(e,i,!1))})}isCellInvalid(e,t){return this.#u.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#u.get(e)?.get(t)}hasInvalidCells(e){const t=this.#u.get(e);return!!t&&t.size>0}getInvalidFields(e){return new Map(this.#u.get(e)??[])}#R(e,t,i){const n=this.grid,o=n._visibleColumns?.findIndex(e=>e.field===t);if(-1===o||void 0===o)return;const r=n._rows,s=r?.findIndex(t=>{try{return n.getRowId?.(t)===e}catch{return!1}});if(-1===s||void 0===s)return;const d=n.findRenderedRowElement?.(s),l=d?.querySelector(`.cell[data-col="${o}"]`);if(l)if(i){l.setAttribute("data-invalid","true");const i=this.#u.get(e)?.get(t);i&&l.setAttribute("title",i)}else l.removeAttribute("data-invalid"),l.removeAttribute("title")}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#s.clear(),this.#y(),e||this.emit("changed-rows-reset",{rows:t,ids:i});const n=this.grid;n._rowPool?.forEach(e=>e.classList.remove("changed"))}beginCellEdit(e,t){const i=this.grid,n=i._visibleColumns.findIndex(e=>e.field===t);if(-1===n)return;const o=i._visibleColumns[n];if(!o?.editable)return;const r=i.findRenderedRowElement?.(e),s=r?.querySelector(`.cell[data-col="${n}"]`);s&&(this.#g=!0,this.#C(e,n,s))}beginBulkEdit(e){const t=this.grid;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return;const n=t._columns?.some(e=>e.editable);if(!n)return;const o=t.findRenderedRowElement?.(e);if(!o)return;this.#g=!1;const r=t._rows[e];this.#I(e,r),Array.from(o.children).forEach((i,n)=>{const o=t._visibleColumns[n];if(o?.editable){const t=i;t.classList.contains("editing")||this.#b(r,e,o,n,t,!0)}}),setTimeout(()=>{let e=o.querySelector(`.cell[data-col="${t._focusCol}"]`);if(e?.classList.contains("editing")||(e=o.querySelector(".cell.editing")),e?.classList.contains("editing")){const t=e.querySelector(i.FOCUSABLE_EDITOR_SELECTOR);try{t?.focus({preventScroll:!0})}catch{}}},0)}commitActiveRowEdit(){-1!==this.#t&&this.#w(this.#t,!1)}cancelActiveRowEdit(){-1!==this.#t&&this.#w(this.#t,!0)}#C(e,t,i){const n=this.grid,o=n._rows[e],r=n._visibleColumns[t];o&&r?.editable&&(i.classList.contains("editing")||(this.#t!==e&&this.#I(e,o),this.#o=t,this.#b(o,e,r,t,i,!1)))}#v(){const e=this.grid,t=e._focusRow,n=e._focusCol;if(t<0||n<0)return;const o=e.findRenderedRowElement?.(t),r=o?.querySelector(`.cell[data-col="${n}"]`);if(r?.classList.contains("editing")){const e=r.querySelector(i.FOCUSABLE_EDITOR_SELECTOR);e&&(this.#f=!1,e.focus(),this.#h=!0,e instanceof HTMLInputElement&&("text"===e.type||"number"===e.type)&&e.select())}}#E(e){const n=this.grid,o=n._rows,r=this.#e?n._focusRow:this.#t,s=n._visibleColumns.map((e,t)=>e.editable?t:-1).filter(e=>e>=0);if(0===s.length)return;const d=s.indexOf(n._focusCol)+(e?1:-1);if(d>=0&&d<s.length){n._focusCol=s[d];const e=n.findRenderedRowElement?.(r),o=e?.querySelector(`.cell[data-col="${s[d]}"]`);if(o?.classList.contains("editing")){const e=o.querySelector(i.FOCUSABLE_EDITOR_SELECTOR);e?.focus({preventScroll:!0})}return void t.ensureCellVisible(n,{forceHorizontalScroll:!0})}const l=r+(e?1:-1);l>=0&&l<o.length&&(this.#e?(n._focusRow=l,n._focusCol=e?s[0]:s[s.length-1],t.ensureCellVisible(n,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const e=n.findRenderedRowElement?.(l),t=e?.querySelector(`.cell[data-col="${n._focusCol}"]`);if(t?.classList.contains("editing")){const e=t.querySelector(i.FOCUSABLE_EDITOR_SELECTOR);e?.focus({preventScroll:!0})}},0)):(this.#w(r,!1),n._focusRow=l,n._focusCol=e?s[0]:s[s.length-1],this.beginBulkEdit(l),t.ensureCellVisible(n,{forceHorizontalScroll:!0})))}#y(){const e=this.grid;e._activeEditRows=this.#t,e._rowEditSnapshots=this.#r}#I(e,t){if(this.#t!==e){this.#r.set(e,{...t}),this.#t=e,this.#n=t;const i=this.grid;try{this.#i=i.getRowId?.(t)??void 0}catch{this.#i=void 0}this.#y(),this.#e||this.emit("edit-open",{rowIndex:e,rowId:this.#i??"",row:t})}}#w(e,t){if(this.#t!==e)return;const i=this.grid,n=this.#r.get(e),o=i.findRenderedRowElement?.(e);let r=this.#i;const d=r?i._getRowEntry(r):void 0,l=d?.row??this.#n??i._rows[e];if(!r&&l)try{r=i.getRowId?.(l)}catch{}if(!t&&o&&l){o.querySelectorAll(".cell.editing").forEach(t=>{const n=Number(t.getAttribute("data-col"));if(isNaN(n))return;const o=i._visibleColumns[n];if(!o)return;if(t.hasAttribute("data-editor-managed"))return;const r=t.querySelector("input,textarea,select");if(r){const t=o.field,i=l[t],n=s(r,o,i);i!==n&&this.#p(e,o,n,l)}})}if(t||this.#e||!l||this.emit("before-edit-close",{rowIndex:e,rowId:r??"",row:l}),t&&n&&l)Object.keys(n).forEach(e=>{l[e]=n[e]}),r&&(this.#s.delete(r),this.clearRowInvalid(r));else if(!t&&l){const t=this.#_(n,l),i=r?this.#s.has(r):t,o=this.emitCancelable("row-commit",{rowIndex:e,rowId:r??"",row:l,oldValue:n,newValue:l,changed:i,changedRows:this.changedRows,changedRowIds:this.changedRowIds});o&&n?(Object.keys(n).forEach(e=>{l[e]=n[e]}),r&&(this.#s.delete(r),this.clearRowInvalid(r))):!o&&t&&this.isAnimationEnabled&&(this.#a=e)}this.#r.delete(e),this.#t=-1,this.#i=void 0,this.#n=void 0,this.#o=-1,this.#g=!1,this.#y();for(const s of this.#d)s.startsWith(`${e}:`)&&this.#d.delete(s);for(const s of this.#l.keys())s.startsWith(`${e}:`)&&this.#l.delete(s);this.#c=!0,o?(o.querySelectorAll(".cell.editing").forEach(e=>{e.classList.remove("editing"),function(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing")}(e.parentElement)}),i.refreshVirtualWindow(!0)):(this.#m(i),this.#c=!1),!this.#e&&l&&this.emit("edit-close",{rowIndex:e,rowId:r??"",row:l,reverted:t})}#p(e,t,i,n){const o=t.field;if(!r(o))return;const s=n[o];if(s===i)return;const l=this.grid;let c;try{c=this.grid.getRowId(n)}catch{}const a=!c||!this.#s.has(c),u=c?e=>this.grid.updateRow(c,e,"cascade"):d;let h=!1;const f=c?e=>{h=!0,this.setInvalid(c,o,e??"")}:()=>{};if(this.emitCancelable("cell-commit",{row:n,rowId:c??"",field:o,oldValue:s,value:i,rowIndex:e,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:a,updateRow:u,setInvalid:f}))return;c&&!h&&this.isCellInvalid(c,o)&&this.clearInvalid(c,o),n[o]=i,c&&this.#s.add(c),this.#y(),this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:o,oldValue:s,newValue:i});const g=l.findRenderedRowElement?.(e);g&&g.classList.add("changed")}#b(e,t,n,l,c,a){if(!n.editable)return;if(c.classList.contains("editing"))return;let u;try{u=this.grid.getRowId(e)}catch{}const h=u?e=>this.grid.updateRow(u,e,"cascade"):d,f=r(n.field)?e[n.field]:void 0;c.classList.add("editing"),this.#d.add(`${t}:${l}`);const g=c.parentElement;g&&function(e){const t=(e.__editingCellCount??0)+1;e.__editingCellCount=t,e.setAttribute("data-has-editing","")}(g);let w=!1;const E=i=>{if(w||!this.#e&&-1===this.#t)return;const o=this.grid,r=u?o._getRowEntry(u):void 0,s=r?.row??e,d=r?.index??t;this.#p(d,n,i,s)},p=()=>{if(w=!0,r(n.field)){const t=this.grid,i=u?t._getRowEntry(u):void 0;(i?.row??e)[n.field]=f}},v=document.createElement("div");v.className="tbw-editor-host",c.innerHTML="",c.appendChild(v),v.addEventListener("keydown",e=>{if("Enter"===e.key){if(this.#e){e.stopPropagation(),e.preventDefault();const t=v.querySelector("input,textarea,select");return void(t&&E(s(t,n,f)))}if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}e.stopPropagation(),e.preventDefault(),w=!0,this.#w(t,!1)}if("Escape"===e.key){if(this.#e)return e.stopPropagation(),void e.preventDefault();if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}e.stopPropagation(),e.preventDefault(),p(),this.#w(t,!0)}});const m=n,b=m.__editorTemplate,R=function(e,t){if(t.editor)return t.editor;if(t.__editorTemplate)return"template";if(!t.type)return;const i=e.effectiveConfig?.typeDefaults;if(i?.[t.type]?.editor)return i[t.type].editor;const n=e.__frameworkAdapter;if(n?.getTypeDefault){const e=n.getTypeDefault(t.type);if(e?.editor)return e.editor}}(this.grid,m)??o(n),y=f,C=`${t}:${n.field}`,I=[];this.#l.set(C,e=>{for(const t of I)t(e)});const _=e=>{I.push(e)};if("template"===R&&b)this.#k(v,m,e,f,E,p,a,t),_(e=>{const t=v.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if("string"==typeof R){const e=document.createElement(R);e.value=y,e.addEventListener("change",()=>E(e.value)),_(t=>{e.value=t}),v.appendChild(e),a||queueMicrotask(()=>{const e=v.querySelector(i.FOCUSABLE_EDITOR_SELECTOR);e?.focus({preventScroll:!0})})}else if("function"==typeof R){const t=R({row:e,rowId:u??"",value:y,field:n.field,column:n,commit:E,cancel:p,updateRow:h,onValueChange:_});if("string"==typeof t)v.innerHTML=t,function(e,t,i,n){const o=e.querySelector("input,textarea,select");o&&(o.addEventListener("blur",()=>{i(s(o,t,n))}),o instanceof HTMLInputElement&&"checkbox"===o.type?o.addEventListener("change",()=>i(o.checked)):o instanceof HTMLSelectElement&&o.addEventListener("change",()=>i(s(o,t,n))))}(v,n,E,f),_(e=>{const t=v.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if(t instanceof Node){v.appendChild(t);t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?_(e=>{t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??"")}):c.setAttribute("data-editor-managed","")}a||queueMicrotask(()=>{const e=v.querySelector(i.FOCUSABLE_EDITOR_SELECTOR);e?.focus({preventScroll:!0})})}else if(R&&"object"==typeof R){const t=document.createElement("div");t.setAttribute("data-external-editor",""),t.setAttribute("data-field",n.field),v.appendChild(t),c.setAttribute("data-editor-managed","");const i={row:e,rowId:u??"",value:y,field:n.field,column:n,commit:E,cancel:p,updateRow:h,onValueChange:_};if(R.mount)try{R.mount({placeholder:t,context:i,spec:R})}catch(k){console.warn(`[tbw-grid] External editor mount error for column '${n.field}':`,k)}else this.grid.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:t,spec:R,context:i}}))}}#k(e,t,i,n,o,d,l,c){const a=t.__editorTemplate;if(!a)return;const u=a.cloneNode(!0),h=t.__compiledEditor;h?u.innerHTML=h({row:i,value:n,field:t.field,column:t,commit:o,cancel:d}):u.querySelectorAll("*").forEach(e=>{1===e.childNodes.length&&e.firstChild?.nodeType===Node.TEXT_NODE&&(e.textContent=e.textContent?.replace(/{{\s*value\s*}}/g,null==n?"":String(n)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(e,t)=>{if(!r(t))return"";const n=i[t];return null==n?"":String(n)})||"")});const f=u.querySelector("input,textarea,select");if(f){f instanceof HTMLInputElement&&"checkbox"===f.type?f.checked=!!n:f.value=String(n??"");let e=!1;f.addEventListener("blur",()=>{e||o(s(f,t,n))}),f.addEventListener("keydown",i=>{const r=i;if("Enter"===r.key){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(r))return}r.stopPropagation(),r.preventDefault(),e=!0,o(s(f,t,n)),this.#w(c,!1)}if("Escape"===r.key){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(r))return}r.stopPropagation(),r.preventDefault(),d(),this.#w(c,!0)}}),f instanceof HTMLInputElement&&"checkbox"===f.type&&f.addEventListener("change",()=>o(f.checked)),l||setTimeout(()=>f.focus({preventScroll:!0}),0)}e.appendChild(u)}#_(e,t){if(!e)return!1;const i=e,n=t,o=new Set([...Object.keys(i),...Object.keys(n)]);for(const r of o)if(i[r]!==n[r])return!0;return!1}#m(e){queueMicrotask(()=>{try{const t=e._focusRow,i=e._focusCol,n=e.findRenderedRowElement?.(t);if(n){Array.from(e._bodyEl.querySelectorAll(".cell-focus")).forEach(e=>e.classList.remove("cell-focus"));const o=n.querySelector(`.cell[data-row="${t}"][data-col="${i}"]`);o&&(o.classList.add("cell-focus"),o.setAttribute("aria-selected","true"),o.hasAttribute("tabindex")||o.setAttribute("tabindex","-1"),o.focus({preventScroll:!0}))}}catch{}})}}e.EditingPlugin=l,e.defaultEditorFor=o,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/keyboard"),require("../../core/internal/rows"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/keyboard","../../core/internal/rows","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_editing={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,i,n){"use strict";function o(e){switch(e.type){case"number":return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");n.type="number",n.value=null!=t.value?String(t.value):"",void 0!==i?.min&&(n.min=String(i.min)),void 0!==i?.max&&(n.max=String(i.max)),void 0!==i?.step&&(n.step=String(i.step)),i?.placeholder&&(n.placeholder=i.placeholder);const o=()=>t.commit(""===n.value?null:Number(n.value));return n.addEventListener("blur",o),n.addEventListener("keydown",e=>{"Enter"===e.key&&o(),"Escape"===e.key&&t.cancel()}),n}}(e);case"boolean":return e=>{const t=document.createElement("input");return t.type="checkbox",t.checked=!!e.value,t.addEventListener("change",()=>e.commit(t.checked)),t};case"date":return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");return n.type="date",t.value instanceof Date?n.valueAsDate=t.value:"string"==typeof t.value&&t.value&&(n.value=t.value.split("T")[0]),i?.min&&(n.min=i.min),i?.max&&(n.max=i.max),i?.placeholder&&(n.placeholder=i.placeholder),n.addEventListener("change",()=>{"string"==typeof t.value?t.commit(n.value):t.commit(n.valueAsDate)}),n.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),n}}(e);case"select":return function(e){return t=>{const i=e.editorParams,n=document.createElement("select");if(e.multi&&(n.multiple=!0),i?.includeEmpty){const e=document.createElement("option");e.value="",e.textContent=i.emptyLabel??"",n.appendChild(e)}const o=function(e){const t=e.options;return t?"function"==typeof t?t():t:[]}(e);o.forEach(i=>{const o=document.createElement("option");o.value=String(i.value),o.textContent=i.label,e.multi&&Array.isArray(t.value)&&t.value.includes(i.value)?o.selected=!0:e.multi||t.value!==i.value||(o.selected=!0),n.appendChild(o)});const r=()=>{if(e.multi){const e=Array.from(n.selectedOptions).map(e=>e.value);t.commit(e)}else t.commit(n.value)};return n.addEventListener("change",r),n.addEventListener("blur",r),n.addEventListener("keydown",e=>{"Escape"===e.key&&t.cancel()}),n}}(e);default:return function(e){return t=>{const i=e.editorParams,n=document.createElement("input");n.type="text",n.value=null!=t.value?String(t.value):"",void 0!==i?.maxLength&&(n.maxLength=i.maxLength),i?.pattern&&(n.pattern=i.pattern),i?.placeholder&&(n.placeholder=i.placeholder);const o=()=>{const e=n.value;(null!==t.value&&void 0!==t.value||""!==e)&&("string"==typeof t.value&&e===t.value.replace(/[\n\r]/g,"")||("number"==typeof t.value&&""!==e?t.commit(Number(e)):t.commit(e)))};return n.addEventListener("blur",o),n.addEventListener("keydown",e=>{"Enter"===e.key&&o(),"Escape"===e.key&&t.cancel()}),n}}(e)}}function r(e){return"string"==typeof e&&("__proto__"!==e&&"constructor"!==e&&"prototype"!==e)}function s(e,t,i){return e instanceof HTMLInputElement?"checkbox"===e.type?e.checked:"number"===e.type?""===e.value?null:Number(e.value):"date"===e.type?"string"==typeof i?e.value:e.valueAsDate:"number"==typeof i?""===e.value?null:Number(e.value):null==i&&""===e.value||"string"==typeof i&&e.value===i.replace(/[\n\r]/g,"")?i:e.value:"number"===t?.type&&""!==e.value||"number"==typeof i&&""!==e.value?Number(e.value):null==i&&""===e.value?i:e.value}function d(e){}class l extends n.BaseGridPlugin{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>!0===e},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'}],events:[{type:"cell-edit-committed",description:"Emitted when a cell edit is committed (for plugin-to-plugin coordination)"}],queries:[{type:"isEditing",description:"Returns whether any cell is currently being edited"}]};name="editing";styles="@layer tbw-plugins{tbw-grid{--tbw-editing-bg: var(--tbw-color-selection);--tbw-editing-row-bg: var(--tbw-editing-bg);--tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));--tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);--tbw-font-size-editor: inherit;--tbw-editing-row-outline-color: var(--tbw-color-accent);--tbw-editing-row-outline-width: 1px;--tbw-invalid-bg: light-dark(#fef2f2, #450a0a);--tbw-invalid-border-color: light-dark(#ef4444, #f87171)}tbw-grid:not(.tbw-grid-mode) .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:calc(var(--tbw-row-height) + 2px);align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}tbw-grid .data-grid-row>.cell[data-invalid=true]{background:var(--tbw-invalid-bg);outline:1px solid var(--tbw-invalid-border-color);outline-offset:-1px}}";get defaultConfig(){return{mode:"row",editOn:"click"}}get#e(){return"grid"===this.config.mode}#t=-1;#i;#n;#o=-1;#r=new Map;#s=new Set;#d=new Set;#l=new Map;#c=!1;#a=-1;#u=new Map;#h=!1;#f=!1;#g=!1;attach(e){super.attach(e);const t=this.disconnectSignal,n=e;n._activeEditRows=-1,n._rowEditSnapshots=new Map,Object.defineProperty(e,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(e,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),e.resetChangedRows=e=>this.resetChangedRows(e),e.beginBulkEdit=(e,t)=>{t&&this.beginCellEdit(e,t)},document.addEventListener("keydown",e=>{if(!this.#e&&"Escape"===e.key&&-1!==this.#t){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}this.#w(this.#t,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",e=>{if(this.#e)return;if(-1===this.#t)return;const t=n.findRenderedRowElement?.(this.#t);if(!t)return;if((e.composedPath&&e.composedPath()||[]).includes(t))return;const i=e.target;if(!i||!this.grid.containsFocus?.(i)){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}queueMicrotask(()=>{-1!==this.#t&&this.#w(this.#t,!1)})}},{signal:t}),this.config.focusTrap&&this.gridElement.addEventListener("focusout",e=>{if(this.#e)return;if(-1===this.#t)return;const t=e.relatedTarget;t&&this.grid.containsFocus?.(t)||t&&this.gridElement.contains(t)||queueMicrotask(()=>{-1!==this.#t&&this.#E()})},{signal:t}),this.gridElement.addEventListener("cell-change",e=>{const t=e.detail;if("user"===t.source)return;const i=`${t.rowIndex}:${t.field}`,n=this.#l.get(i);n&&n(t.newValue)},{signal:t}),this.#e&&(n._isGridEditMode=!0,this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",e=>{const t=e.target;if(t.matches(i.FOCUSABLE_EDITOR_SELECTOR)){if(this.#f)return t.blur(),void this.gridElement.focus();this.#h=!0}},{signal:t}),this.gridElement.addEventListener("focusout",e=>{const t=e.relatedTarget;t&&(this.gridElement.contains(t)||this.grid.containsFocus?.(t))&&t.matches(i.FOCUSABLE_EDITOR_SELECTOR)||(this.#h=!1)},{signal:t}),this.gridElement.addEventListener("keydown",e=>{if("Escape"===e.key&&this.#h){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}const t=document.activeElement;t&&this.gridElement.contains(t)&&(t.blur(),this.gridElement.focus()),this.#h=!1,this.#f=!0,e.preventDefault(),e.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",e=>{e.target.matches(i.FOCUSABLE_EDITOR_SELECTOR)&&(this.#f=!1)},{signal:t}))}detach(){this.gridElement._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#t=-1,this.#i=void 0,this.#n=void 0,this.#o=-1,this.#r.clear(),this.#s.clear(),this.#d.clear(),this.#l.clear(),this.#h=!1,this.#f=!1,this.#g=!1,super.detach()}handleQuery(e){if("isEditing"===e.type)return this.#e||-1!==this.#t}onCellClick(e){if(this.#e)return!1;const t=this.grid,i=this.config.editOn??t.effectiveConfig?.editOn;if(!1===i||"manual"===i)return!1;if("click"!==i&&"dblclick"!==i)return!1;const n="dblclick"===e.originalEvent.type;if("click"===i&&n)return!1;if("dblclick"===i&&!n)return!1;const{rowIndex:o}=e,r=t._columns?.some(e=>e.editable);return!!r&&(e.originalEvent.stopPropagation(),this.beginBulkEdit(o),!0)}onKeyDown(e){const i=this.grid;if("Escape"===e.key){if(this.#e&&this.#h){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}const t=document.activeElement;return t&&this.gridElement.contains(t)&&t.blur(),this.#h=!1,this.requestAfterRender(),!0}if(-1!==this.#t&&!this.#e){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}return this.#w(this.#t,!0),!0}}if(this.#e&&!this.#h&&("ArrowUp"===e.key||"ArrowDown"===e.key||"ArrowLeft"===e.key||"ArrowRight"===e.key))return!1;if(this.#e&&this.#h&&("ArrowUp"===e.key||"ArrowDown"===e.key))return!0;if(("ArrowUp"===e.key||"ArrowDown"===e.key)&&-1!==this.#t&&!this.#e){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}const n=i._rows.length-1,o=this.#t;return this.#w(o,!1),"ArrowDown"===e.key?i._focusRow=Math.min(n,i._focusRow+1):i._focusRow=Math.max(0,i._focusRow-1),e.preventDefault(),t.ensureCellVisible(i),this.requestAfterRender(),!0}if("Tab"===e.key&&(-1!==this.#t||this.#e)){if(e.preventDefault(),this.#g)return this.#w(this.#t,!1),!0;const t=!e.shiftKey;return this.#p(t),!0}if(" "===e.key||"Spacebar"===e.key){if(-1!==this.#t)return!1;const t=i._focusRow,n=i._focusCol;if(t>=0&&n>=0){const o=i._visibleColumns[n],s=i._rows[t];if(o?.editable&&"boolean"===o.type&&s){const i=o.field;if(r(i)){const n=!s[i];return this.#v(t,o,n,s),e.preventDefault(),this.requestRender(),!0}}}return!1}if(!("Enter"!==e.key||e.shiftKey||e.ctrlKey||e.altKey||e.metaKey)){if(this.#e&&!this.#h)return this.#E(),!0;if(-1!==this.#t){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return!0}return!1}const t=this.config.editOn??i.effectiveConfig?.editOn;if(!1===t||"manual"===t)return!1;const n=i._focusRow,o=i._focusCol;if(n>=0){const t=i._columns?.some(e=>e.editable);if(t){const t=i._visibleColumns[o],r=i._rows[n],s=t?.field??"",d=s&&r?r[s]:void 0,l=this.gridElement.querySelector(`[data-row="${n}"][data-col="${o}"]`),c=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:n,colIndex:o,field:s,value:d,row:r,cellEl:l,trigger:"keyboard",originalEvent:e}});this.gridElement.dispatchEvent(c);const a=new CustomEvent("activate-cell",{cancelable:!0,bubbles:!0,detail:{row:n,col:o}});return this.gridElement.dispatchEvent(a),c.defaultPrevented||a.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(n),!0)}}return!1}if("F2"===e.key){if(-1!==this.#t||this.#e)return!1;if(!1===(this.config.editOn??i.effectiveConfig?.editOn))return!1;const t=i._focusRow,n=i._focusCol;if(t>=0&&n>=0){const o=i._visibleColumns[n];if(o?.editable&&o.field)return e.preventDefault(),this.beginCellEdit(t,o.field),!0}return!1}return!1}processColumns(e){const t=this.grid,i=t.effectiveConfig?.typeDefaults,n=t.__frameworkAdapter;return i||n?.getTypeDefault?e.map(e=>{if(!e.type)return e;let t;if(i?.[e.type]?.editorParams&&(t=i[e.type].editorParams),!t&&n?.getTypeDefault){const i=n.getTypeDefault(e.type);i?.editorParams&&(t=i.editorParams)}return t?{...e,editorParams:{...t,...e.editorParams}}:e}):e}afterRender(){const e=this.grid;if(this.#c&&(this.#c=!1,this.#m(e)),-1!==this.#a){const t=this.#a;this.#a=-1,e.animateRow?.(t,"change")}if(!this.#e&&0!==this.#d.size)for(const t of this.#d){const[i,n]=t.split(":"),o=parseInt(i,10),r=parseInt(n,10),s=e.findRenderedRowElement?.(o);if(!s)continue;const d=s.querySelector(`.cell[data-col="${r}"]`);if(!d||d.classList.contains("editing"))continue;const l=e._rows[o],c=e._visibleColumns[r];l&&c&&this.#R(l,o,c,r,d,!0)}}afterCellRender(e){if(!this.#e)return;const{row:t,rowIndex:i,column:n,colIndex:o,cellElement:r}=e;n.editable&&(r.classList.contains("editing")||this.#R(t,i,n,o,r,!0))}onScrollRender(){this.afterRender()}get changedRows(){const e=[];for(const t of this.#s){const i=this.grid.getRow(t);i&&e.push(i)}return e}get changedRowIds(){return Array.from(this.#s)}get activeEditRow(){return this.#t}get activeEditCol(){return this.#o}isRowEditing(e){return this.#t===e}isCellEditing(e,t){return this.#d.has(`${e}:${t}`)}isRowChanged(e){const t=this.grid,i=t._rows[e];if(!i)return!1;try{const e=t.getRowId?.(i);return!!e&&this.#s.has(e)}catch{return!1}}isRowChangedById(e){return this.#s.has(e)}setInvalid(e,t,i=""){let n=this.#u.get(e);n||(n=new Map,this.#u.set(e,n)),n.set(t,i),this.#b(e,t,!0)}clearInvalid(e,t){const i=this.#u.get(e);i&&(i.delete(t),0===i.size&&this.#u.delete(e)),this.#b(e,t,!1)}clearRowInvalid(e){const t=this.#u.get(e);if(t){const i=Array.from(t.keys());this.#u.delete(e),i.forEach(t=>this.#b(e,t,!1))}}clearAllInvalid(){const e=Array.from(this.#u.entries());this.#u.clear(),e.forEach(([e,t])=>{t.forEach((t,i)=>this.#b(e,i,!1))})}isCellInvalid(e,t){return this.#u.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#u.get(e)?.get(t)}hasInvalidCells(e){const t=this.#u.get(e);return!!t&&t.size>0}getInvalidFields(e){return new Map(this.#u.get(e)??[])}#b(e,t,i){const n=this.grid,o=n._visibleColumns?.findIndex(e=>e.field===t);if(-1===o||void 0===o)return;const r=n._rows,s=r?.findIndex(t=>{try{return n.getRowId?.(t)===e}catch{return!1}});if(-1===s||void 0===s)return;const d=n.findRenderedRowElement?.(s),l=d?.querySelector(`.cell[data-col="${o}"]`);if(l)if(i){l.setAttribute("data-invalid","true");const i=this.#u.get(e)?.get(t);i&&l.setAttribute("title",i)}else l.removeAttribute("data-invalid"),l.removeAttribute("title")}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#s.clear(),this.#y(),e||this.emit("changed-rows-reset",{rows:t,ids:i});const n=this.grid;n._rowPool?.forEach(e=>e.classList.remove("changed"))}beginCellEdit(e,t){const i=this.grid,n=i._visibleColumns.findIndex(e=>e.field===t);if(-1===n)return;const o=i._visibleColumns[n];if(!o?.editable)return;const r=i.findRenderedRowElement?.(e),s=r?.querySelector(`.cell[data-col="${n}"]`);s&&(this.#g=!0,this.#C(e,n,s))}beginBulkEdit(e){const t=this.grid;if(!1===(this.config.editOn??t.effectiveConfig?.editOn))return;const n=t._columns?.some(e=>e.editable);if(!n)return;const o=t.findRenderedRowElement?.(e);if(!o)return;this.#g=!1;const r=t._rows[e];this.#I(e,r),Array.from(o.children).forEach((i,n)=>{const o=t._visibleColumns[n];if(o?.editable){const t=i;t.classList.contains("editing")||this.#R(r,e,o,n,t,!0)}}),setTimeout(()=>{let e=o.querySelector(`.cell[data-col="${t._focusCol}"]`);if(e?.classList.contains("editing")||(e=o.querySelector(".cell.editing")),e?.classList.contains("editing")){const t=e.querySelector(i.FOCUSABLE_EDITOR_SELECTOR);try{t?.focus({preventScroll:!0})}catch{}}},0)}commitActiveRowEdit(){-1!==this.#t&&this.#w(this.#t,!1)}cancelActiveRowEdit(){-1!==this.#t&&this.#w(this.#t,!0)}#C(e,t,i){const n=this.grid,o=n._rows[e],r=n._visibleColumns[t];o&&r?.editable&&(i.classList.contains("editing")||(this.#t!==e&&this.#I(e,o),this.#o=t,this.#R(o,e,r,t,i,!1)))}#E(){const e=this.grid,t=e._focusRow,n=e._focusCol;if(t<0||n<0)return;const o=e.findRenderedRowElement?.(t),r=o?.querySelector(`.cell[data-col="${n}"]`);if(r?.classList.contains("editing")){const e=r.querySelector(i.FOCUSABLE_EDITOR_SELECTOR);e&&(this.#f=!1,e.focus(),this.#h=!0,e instanceof HTMLInputElement&&("text"===e.type||"number"===e.type)&&e.select())}}#p(e){const n=this.grid,o=n._rows,r=this.#e?n._focusRow:this.#t,s=n._visibleColumns.map((e,t)=>e.editable?t:-1).filter(e=>e>=0);if(0===s.length)return;const d=s.indexOf(n._focusCol)+(e?1:-1);if(d>=0&&d<s.length){n._focusCol=s[d];const e=n.findRenderedRowElement?.(r),o=e?.querySelector(`.cell[data-col="${s[d]}"]`);if(o?.classList.contains("editing")){const e=o.querySelector(i.FOCUSABLE_EDITOR_SELECTOR);e?.focus({preventScroll:!0})}return void t.ensureCellVisible(n,{forceHorizontalScroll:!0})}const l=r+(e?1:-1);l>=0&&l<o.length&&(this.#e?(n._focusRow=l,n._focusCol=e?s[0]:s[s.length-1],t.ensureCellVisible(n,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const e=n.findRenderedRowElement?.(l),t=e?.querySelector(`.cell[data-col="${n._focusCol}"]`);if(t?.classList.contains("editing")){const e=t.querySelector(i.FOCUSABLE_EDITOR_SELECTOR);e?.focus({preventScroll:!0})}},0)):(this.#w(r,!1),n._focusRow=l,n._focusCol=e?s[0]:s[s.length-1],this.beginBulkEdit(l),t.ensureCellVisible(n,{forceHorizontalScroll:!0})))}#y(){const e=this.grid;e._activeEditRows=this.#t,e._rowEditSnapshots=this.#r}#I(e,t){if(this.#t!==e){this.#r.set(e,{...t}),this.#t=e,this.#n=t;const i=this.grid;try{this.#i=i.getRowId?.(t)??void 0}catch{this.#i=void 0}this.#y(),this.#e||this.emit("edit-open",{rowIndex:e,rowId:this.#i??"",row:t})}}#w(e,t){if(this.#t!==e)return;const i=this.grid,n=this.#r.get(e),o=i.findRenderedRowElement?.(e);let r=this.#i;const d=r?i._getRowEntry(r):void 0,l=d?.row??this.#n??i._rows[e];if(!r&&l)try{r=i.getRowId?.(l)}catch{}if(!t&&o&&l){o.querySelectorAll(".cell.editing").forEach(t=>{const n=Number(t.getAttribute("data-col"));if(isNaN(n))return;const o=i._visibleColumns[n];if(!o)return;if(t.hasAttribute("data-editor-managed"))return;const r=t.querySelector("input,textarea,select");if(r){const t=o.field,i=l[t],n=s(r,o,i);i!==n&&this.#v(e,o,n,l)}})}if(t||this.#e||!l||this.emit("before-edit-close",{rowIndex:e,rowId:r??"",row:l}),t&&n&&l)Object.keys(n).forEach(e=>{l[e]=n[e]}),r&&(this.#s.delete(r),this.clearRowInvalid(r));else if(!t&&l){const t=this.#_(n,l),i=r?this.#s.has(r):t,o=this.emitCancelable("row-commit",{rowIndex:e,rowId:r??"",row:l,oldValue:n,newValue:l,changed:i,changedRows:this.changedRows,changedRowIds:this.changedRowIds});o&&n?(Object.keys(n).forEach(e=>{l[e]=n[e]}),r&&(this.#s.delete(r),this.clearRowInvalid(r))):!o&&t&&this.isAnimationEnabled&&(this.#a=e)}this.#r.delete(e),this.#t=-1,this.#i=void 0,this.#n=void 0,this.#o=-1,this.#g=!1,this.#y();for(const s of this.#d)s.startsWith(`${e}:`)&&this.#d.delete(s);for(const s of this.#l.keys())s.startsWith(`${e}:`)&&this.#l.delete(s);this.#c=!0,o?(o.querySelectorAll(".cell.editing").forEach(e=>{e.classList.remove("editing"),function(e){e.__editingCellCount=0,e.removeAttribute("data-has-editing")}(e.parentElement)}),i.refreshVirtualWindow(!0)):(this.#m(i),this.#c=!1),!this.#e&&l&&this.emit("edit-close",{rowIndex:e,rowId:r??"",row:l,reverted:t})}#v(e,t,i,n){const o=t.field;if(!r(o))return;const s=n[o];if(s===i)return;const l=this.grid;let c;try{c=this.grid.getRowId(n)}catch{}const a=!c||!this.#s.has(c),u=c?e=>this.grid.updateRow(c,e,"cascade"):d;let h=!1;const f=c?e=>{h=!0,this.setInvalid(c,o,e??"")}:()=>{};if(this.emitCancelable("cell-commit",{row:n,rowId:c??"",field:o,oldValue:s,value:i,rowIndex:e,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:a,updateRow:u,setInvalid:f}))return;c&&!h&&this.isCellInvalid(c,o)&&this.clearInvalid(c,o),n[o]=i,c&&this.#s.add(c),this.#y(),this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:o,oldValue:s,newValue:i});const g=l.findRenderedRowElement?.(e);g&&g.classList.add("changed")}#R(e,t,n,l,c,a){if(!n.editable)return;if(c.classList.contains("editing"))return;let u;try{u=this.grid.getRowId(e)}catch{}const h=u?e=>this.grid.updateRow(u,e,"cascade"):d,f=r(n.field)?e[n.field]:void 0;c.classList.add("editing"),this.#d.add(`${t}:${l}`);const g=c.parentElement;g&&function(e){const t=(e.__editingCellCount??0)+1;e.__editingCellCount=t,e.setAttribute("data-has-editing","")}(g);let w=!1;const E=i=>{if(w||!this.#e&&-1===this.#t)return;const o=this.grid,r=u?o._getRowEntry(u):void 0,s=r?.row??e,d=r?.index??t;this.#v(d,n,i,s)},p=()=>{if(w=!0,r(n.field)){const t=this.grid,i=u?t._getRowEntry(u):void 0;(i?.row??e)[n.field]=f}},v=document.createElement("div");v.className="tbw-editor-host",c.innerHTML="",c.appendChild(v),v.addEventListener("keydown",e=>{if("Enter"===e.key){if(this.#e){e.stopPropagation(),e.preventDefault();const t=v.querySelector("input,textarea,select");return void(t&&E(s(t,n,f)))}if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}e.stopPropagation(),e.preventDefault(),w=!0,this.#w(t,!1)}if("Escape"===e.key){if(this.#e)return e.stopPropagation(),void e.preventDefault();if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(e))return}e.stopPropagation(),e.preventDefault(),p(),this.#w(t,!0)}});const m=n,R=m.__editorTemplate,b=function(e,t){if(t.editor)return t.editor;if(t.__editorTemplate)return"template";if(!t.type)return;const i=e.effectiveConfig?.typeDefaults;if(i?.[t.type]?.editor)return i[t.type].editor;const n=e.__frameworkAdapter;if(n?.getTypeDefault){const e=n.getTypeDefault(t.type);if(e?.editor)return e.editor}}(this.grid,m)??o(n),y=f,C=`${t}:${n.field}`,I=[];this.#l.set(C,e=>{for(const t of I)t(e)});const _=e=>{I.push(e)};if("template"===b&&R)this.#k(v,m,e,f,E,p,a,t),_(e=>{const t=v.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if("string"==typeof b){const e=document.createElement(b);e.value=y,e.addEventListener("change",()=>E(e.value)),_(t=>{e.value=t}),v.appendChild(e),a||queueMicrotask(()=>{const e=v.querySelector(i.FOCUSABLE_EDITOR_SELECTOR);e?.focus({preventScroll:!0})})}else if("function"==typeof b){const t=b({row:e,rowId:u??"",value:y,field:n.field,column:n,commit:E,cancel:p,updateRow:h,onValueChange:_});if("string"==typeof t)v.innerHTML=t,function(e,t,i,n){const o=e.querySelector("input,textarea,select");o&&(o.addEventListener("blur",()=>{i(s(o,t,n))}),o instanceof HTMLInputElement&&"checkbox"===o.type?o.addEventListener("change",()=>i(o.checked)):o instanceof HTMLSelectElement&&o.addEventListener("change",()=>i(s(o,t,n))))}(v,n,E,f),_(e=>{const t=v.querySelector("input,textarea,select");t&&(t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??""))});else if(t instanceof Node){v.appendChild(t);t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?_(e=>{t instanceof HTMLInputElement&&"checkbox"===t.type?t.checked=!!e:t.value=String(e??"")}):c.setAttribute("data-editor-managed","")}a||queueMicrotask(()=>{const e=v.querySelector(i.FOCUSABLE_EDITOR_SELECTOR);e?.focus({preventScroll:!0})})}else if(b&&"object"==typeof b){const t=document.createElement("div");t.setAttribute("data-external-editor",""),t.setAttribute("data-field",n.field),v.appendChild(t),c.setAttribute("data-editor-managed","");const i={row:e,rowId:u??"",value:y,field:n.field,column:n,commit:E,cancel:p,updateRow:h,onValueChange:_};if(b.mount)try{b.mount({placeholder:t,context:i,spec:b})}catch(k){console.warn(`[tbw-grid] External editor mount error for column '${n.field}':`,k)}else this.grid.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:t,spec:b,context:i}}))}}#k(e,t,i,n,o,d,l,c){const a=t.__editorTemplate;if(!a)return;const u=a.cloneNode(!0),h=t.__compiledEditor;h?u.innerHTML=h({row:i,value:n,field:t.field,column:t,commit:o,cancel:d}):u.querySelectorAll("*").forEach(e=>{1===e.childNodes.length&&e.firstChild?.nodeType===Node.TEXT_NODE&&(e.textContent=e.textContent?.replace(/{{\s*value\s*}}/g,null==n?"":String(n)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(e,t)=>{if(!r(t))return"";const n=i[t];return null==n?"":String(n)})||"")});const f=u.querySelector("input,textarea,select");if(f){f instanceof HTMLInputElement&&"checkbox"===f.type?f.checked=!!n:f.value=String(n??"");let e=!1;f.addEventListener("blur",()=>{e||o(s(f,t,n))}),f.addEventListener("keydown",i=>{const r=i;if("Enter"===r.key){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(r))return}r.stopPropagation(),r.preventDefault(),e=!0,o(s(f,t,n)),this.#w(c,!1)}if("Escape"===r.key){if(this.config.onBeforeEditClose){if(!1===this.config.onBeforeEditClose(r))return}r.stopPropagation(),r.preventDefault(),d(),this.#w(c,!0)}}),f instanceof HTMLInputElement&&"checkbox"===f.type&&f.addEventListener("change",()=>o(f.checked)),l||setTimeout(()=>f.focus({preventScroll:!0}),0)}e.appendChild(u)}#_(e,t){if(!e)return!1;const i=e,n=t,o=new Set([...Object.keys(i),...Object.keys(n)]);for(const r of o)if(i[r]!==n[r])return!0;return!1}#m(e){queueMicrotask(()=>{try{const t=e._focusRow,i=e._focusCol,n=e.findRenderedRowElement?.(t);if(n){Array.from(e._bodyEl.querySelectorAll(".cell-focus")).forEach(e=>e.classList.remove("cell-focus"));const o=n.querySelector(`.cell[data-row="${t}"][data-col="${i}"]`);o&&(o.classList.add("cell-focus"),o.setAttribute("aria-selected","true"),o.hasAttribute("tabindex")||o.setAttribute("tabindex","-1"),o.focus({preventScroll:!0}))}}catch{}})}}e.EditingPlugin=l,e.defaultEditorFor=o,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=editing.umd.js.map
|