@toolbox-web/grid 3.8.2 → 3.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/all.js +1 -1
  2. package/all.js.map +1 -1
  3. package/index.js +1 -1
  4. package/index.js.map +1 -1
  5. package/lib/core/defaults.d.ts +1 -1
  6. package/lib/core/internal/aria.d.ts +1 -1
  7. package/lib/core/internal/config-manager.d.ts +0 -4
  8. package/lib/core/types.d.ts +6 -0
  9. package/lib/features/registry.js +1 -1
  10. package/lib/plugins/clipboard/clipboard-plugin.d.ts +2 -3
  11. package/lib/plugins/clipboard/index.js +1 -1
  12. package/lib/plugins/clipboard/index.js.map +1 -1
  13. package/lib/plugins/column-virtualization/index.js +1 -1
  14. package/lib/plugins/column-virtualization/index.js.map +1 -1
  15. package/lib/plugins/context-menu/index.js +1 -1
  16. package/lib/plugins/context-menu/index.js.map +1 -1
  17. package/lib/plugins/editing/index.js +1 -1
  18. package/lib/plugins/editing/index.js.map +1 -1
  19. package/lib/plugins/export/index.js +1 -1
  20. package/lib/plugins/export/index.js.map +1 -1
  21. package/lib/plugins/filtering/index.js +1 -1
  22. package/lib/plugins/filtering/index.js.map +1 -1
  23. package/lib/plugins/grouping-columns/index.js +1 -1
  24. package/lib/plugins/grouping-columns/index.js.map +1 -1
  25. package/lib/plugins/grouping-rows/index.js +1 -1
  26. package/lib/plugins/grouping-rows/index.js.map +1 -1
  27. package/lib/plugins/master-detail/index.js +1 -1
  28. package/lib/plugins/master-detail/index.js.map +1 -1
  29. package/lib/plugins/multi-sort/index.js +1 -1
  30. package/lib/plugins/multi-sort/index.js.map +1 -1
  31. package/lib/plugins/pinned-columns/index.js +1 -1
  32. package/lib/plugins/pinned-columns/index.js.map +1 -1
  33. package/lib/plugins/pinned-rows/index.js +1 -1
  34. package/lib/plugins/pinned-rows/index.js.map +1 -1
  35. package/lib/plugins/pivot/index.js +1 -1
  36. package/lib/plugins/pivot/index.js.map +1 -1
  37. package/lib/plugins/print/index.js +1 -1
  38. package/lib/plugins/print/index.js.map +1 -1
  39. package/lib/plugins/reorder-columns/index.js +1 -1
  40. package/lib/plugins/reorder-columns/index.js.map +1 -1
  41. package/lib/plugins/responsive/index.js +1 -1
  42. package/lib/plugins/responsive/index.js.map +1 -1
  43. package/lib/plugins/row-drag-drop/index.js +1 -1
  44. package/lib/plugins/row-drag-drop/index.js.map +1 -1
  45. package/lib/plugins/row-drag-drop/row-drag-drop-plugin.d.ts +1 -0
  46. package/lib/plugins/row-drag-drop/types.d.ts +3 -2
  47. package/lib/plugins/selection/index.js +1 -1
  48. package/lib/plugins/selection/index.js.map +1 -1
  49. package/lib/plugins/selection/selection-plugin.d.ts +2 -2
  50. package/lib/plugins/server-side/index.js +1 -1
  51. package/lib/plugins/server-side/index.js.map +1 -1
  52. package/lib/plugins/shell/index.js +1 -1
  53. package/lib/plugins/shell/index.js.map +1 -1
  54. package/lib/plugins/sticky-rows/index.js +1 -1
  55. package/lib/plugins/sticky-rows/index.js.map +1 -1
  56. package/lib/plugins/tooltip/index.js +1 -1
  57. package/lib/plugins/tooltip/index.js.map +1 -1
  58. package/lib/plugins/tree/index.js +1 -1
  59. package/lib/plugins/tree/index.js.map +1 -1
  60. package/lib/plugins/undo-redo/index.js +1 -1
  61. package/lib/plugins/undo-redo/index.js.map +1 -1
  62. package/lib/plugins/visibility/index.js +1 -1
  63. package/lib/plugins/visibility/index.js.map +1 -1
  64. package/package.json +1 -1
  65. package/umd/grid.all.umd.js +1 -1
  66. package/umd/grid.all.umd.js.map +1 -1
  67. package/umd/grid.umd.js +1 -1
  68. package/umd/grid.umd.js.map +1 -1
  69. package/umd/plugins/clipboard.umd.js +1 -1
  70. package/umd/plugins/clipboard.umd.js.map +1 -1
  71. package/umd/plugins/editing.umd.js +1 -1
  72. package/umd/plugins/editing.umd.js.map +1 -1
  73. package/umd/plugins/grouping-rows.umd.js +1 -1
  74. package/umd/plugins/grouping-rows.umd.js.map +1 -1
  75. package/umd/plugins/row-drag-drop.umd.js +1 -1
  76. package/umd/plugins/row-drag-drop.umd.js.map +1 -1
  77. package/umd/plugins/selection.umd.js +1 -1
  78. package/umd/plugins/selection.umd.js.map +1 -1
  79. package/umd/plugins/tooltip.umd.js +1 -1
  80. package/umd/plugins/tooltip.umd.js.map +1 -1
  81. package/umd/plugins/tree.umd.js +1 -1
  82. package/umd/plugins/tree.umd.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../../../libs/grid/src/lib/core/internal/value-accessor.ts","../../../../../../libs/grid/src/lib/core/defaults.ts","../../../../../../libs/grid/src/lib/core/internal/diagnostics.ts","../../../../../../libs/grid/src/lib/core/internal/sanitize.ts","../../../../../../libs/grid/src/lib/core/plugin/base-plugin.ts","../../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../../libs/grid/src/lib/plugins/clipboard/clipboard-payload.ts","../../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts","../../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../../libs/grid/src/lib/plugins/clipboard/clipboard-plugin.ts"],"sourcesContent":["/**\n * Value Accessor Module\n *\n * Single source of truth for resolving a column's value from a row.\n *\n * Resolution precedence:\n * 1. `column.valueAccessor({ row, column, rowIndex })` — when defined\n * 2. `row[column.field]` — direct field read (default)\n *\n * Per-column escape hatches (`sortComparator`, `filterValue`) still take\n * precedence over the accessor — the accessor is the *default* value source,\n * never an override. See {@link BaseColumnConfig.valueAccessor}.\n *\n * Performance: results are memoized per (row identity, column field) using a\n * `WeakMap`. Row identity changes (immutable updates) invalidate naturally;\n * in-place mutations must call {@link invalidateAccessorCache} on the row.\n */\n\nimport type { ColumnConfig } from '../types';\n\n// Box-wrapped values let the cache-hit path do a SINGLE `Map.get` instead of\n// `has()` + `get()`. A truthy box means cache hit (even when the cached value\n// itself is `undefined` / `null` / `0` / `''`).\ninterface CacheBox {\n v: unknown;\n}\nconst accessorCache = new WeakMap<object, Map<string, CacheBox>>();\n\n// #region Nested dotted-path field access (issue #438)\n\n// Prototype-pollution guard applied to every path segment on read AND write.\n// Uses explicit `===` comparisons (not a Set lookup) so static analyzers\n// recognize the barrier guarding the assignments in `setByPath`/`writeCellField`.\nfunction isUnsafeKey(key: string): boolean {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\n// Parsed dotted-path cache: field string → segments. Only **dotted** fields are\n// cached; a plain key is recognised by a single `indexOf` scan, which is cheaper\n// than hashing the string for a Map probe and — critically — keeps the cache\n// from growing without bound when a plugin mints synthetic field names at\n// runtime (PivotPlugin derives one column per distinct pivot value).\nconst fieldPathCache = new Map<string, readonly string[]>();\n\n/**\n * Parse a column `field` into path segments, or `null` when it is a plain\n * top-level key (contains no `.`). Dotted results are memoized.\n *\n * @param field - The column field key (may be a dotted path like `a.b.c`).\n * @returns Frozen segment array for dotted paths, else `null`.\n * @since 3.3.0\n */\nexport function parseFieldPath(field: string): readonly string[] | null {\n if (field.indexOf('.') === -1) return null;\n let segments = fieldPathCache.get(field);\n if (segments === undefined) {\n segments = Object.freeze(field.split('.'));\n fieldPathCache.set(field, segments);\n }\n return segments;\n}\n\n/**\n * Read a nested value from `row` by pre-parsed path segments. Returns\n * `undefined` on any nullish/non-object hop. Prototype-pollution safe.\n *\n * @since 3.3.0\n */\nexport function getByPath(row: unknown, path: readonly string[]): unknown {\n let cur = row as Record<string, unknown> | null | undefined;\n for (let i = 0; i < path.length; i++) {\n if (cur == null || typeof cur !== 'object') return undefined;\n const seg = path[i];\n if (isUnsafeKey(seg)) return undefined;\n cur = cur[seg] as Record<string, unknown>;\n }\n return cur;\n}\n\n/**\n * Write `value` into `row` at the location described by pre-parsed path\n * segments. Walks **existing** objects only — it does NOT fabricate missing\n * intermediates — and returns `true` only when the write happened.\n * Prototype-pollution safe (every segment is guarded).\n *\n * @since 3.3.0\n */\nexport function setByPath(row: unknown, path: readonly string[], value: unknown): boolean {\n if (row == null || typeof row !== 'object') return false;\n let cur = row as Record<string, unknown>;\n for (let i = 0; i < path.length - 1; i++) {\n const seg = path[i];\n if (isUnsafeKey(seg)) return false;\n const next = cur[seg];\n if (next == null || typeof next !== 'object') return false;\n cur = next as Record<string, unknown>;\n }\n const last = path[path.length - 1];\n if (isUnsafeKey(last)) return false;\n cur[last] = value;\n return true;\n}\n\n/**\n * Read the raw stored value for `field` from `row`, honoring nested dotted\n * paths — the non-accessor counterpart to {@link resolveCellValue}.\n *\n * Resolution rules (back-compat critical, see `grid-core.md` DECIDED #438):\n * 1. Plain field (no `.`) → direct `row[field]` (identical to legacy path),\n * except prototype-polluting keys (`__proto__`/`constructor`/`prototype`)\n * which return `undefined` — symmetric with {@link writeCellField}.\n * 2. Dotted field whose literal key is an **own property** of `row` → that\n * flat value wins (preserves synthetic-key rows that really store `'a.b'`).\n * 3. Otherwise → nested traversal via {@link getByPath}.\n *\n * @since 3.3.0\n */\nexport function readCellField(row: unknown, field: string): unknown {\n if (row == null) return undefined;\n const path = parseFieldPath(field);\n const r = row as Record<string, unknown>;\n if (path === null) return isUnsafeKey(field) ? undefined : r[field];\n if (Object.prototype.hasOwnProperty.call(r, field)) return r[field];\n return getByPath(r, path);\n}\n\n/**\n * A precompiled reader that extracts one column's raw value from a row.\n *\n * @since 3.4.0\n */\nexport type FieldReader = (row: unknown) => unknown;\n\n/**\n * Build a {@link FieldReader} for `field`, resolving the plain / unsafe /\n * dotted decision **once** instead of on every cell read.\n *\n * Hoist the reader out of any per-row loop (sort comparators, compiled filter\n * predicates, aggregators, export writers). Semantics are identical to\n * {@link readCellField}; only the dispatch is paid up front.\n *\n * @param field - The column field key (may be a dotted path like `a.b.c`).\n * @returns A single-argument reader closure.\n *\n * @example\n * ```typescript\n * const read = createFieldReader(column.field);\n * rows.sort((a, b) => compare(read(a), read(b)));\n * ```\n * @since 3.4.0\n */\nexport function createFieldReader(field: string): FieldReader {\n const path = parseFieldPath(field);\n if (path === null) {\n if (isUnsafeKey(field)) return () => undefined;\n return (row) => (row == null ? undefined : (row as Record<string, unknown>)[field]);\n }\n return (row) => {\n if (row == null) return undefined;\n const r = row as Record<string, unknown>;\n // A literal own key containing a dot wins over traversal (see readCellField).\n if (Object.prototype.hasOwnProperty.call(r, field)) return r[field];\n return getByPath(r, path);\n };\n}\n\n/**\n * Whether `field` is a plain, safe top-level key — i.e. `row[field]` is exactly\n * equivalent to {@link readCellField} and callers may inline the property read.\n *\n * Used by benchmarked hot loops (compiled filter predicates) that keep a\n * hand-inlined fast path and only fall back to a {@link FieldReader} for the\n * dotted/unsafe minority.\n *\n * @since 3.4.0\n */\nexport function isPlainField(field: string): boolean {\n return field.indexOf('.') === -1 && !isUnsafeKey(field);\n}\n\n/**\n * Write `value` into `row` for `field`, honoring nested dotted paths and the\n * same back-compat precedence as {@link readCellField}. Returns `true` when a\n * write occurred. Prototype-pollution safe.\n *\n * @since 3.3.0\n */\nexport function writeCellField(row: unknown, field: string, value: unknown): boolean {\n if (row == null || typeof row !== 'object') return false;\n const path = parseFieldPath(field);\n const r = row as Record<string, unknown>;\n if (path === null) {\n if (isUnsafeKey(field)) return false;\n r[field] = value;\n return true;\n }\n // A literal own key containing a dot wins over traversal (symmetric with\n // readCellField). Such a key always contains `.`, so it can never be an\n // unsafe prototype key.\n if (Object.prototype.hasOwnProperty.call(r, field)) {\n r[field] = value;\n return true;\n }\n return setByPath(r, path, value);\n}\n\n// #endregion\n\n/**\n * Resolve the cell value for a column, honoring `valueAccessor` if defined,\n * otherwise reading `row[column.field]` (with nested dotted-path support).\n *\n * @param row - The row object\n * @param column - The column definition\n * @param rowIndex - The visible row index (passed to accessor; defaults to -1)\n * @returns The resolved cell value\n *\n * @example\n * ```typescript\n * const value = resolveCellValue(row, column);\n * ```\n * @since 2.2.0\n */\nexport function resolveCellValue<TRow>(row: TRow, column: ColumnConfig<TRow>, rowIndex = -1): unknown {\n if (!column.valueAccessor) {\n return readCellField(row, column.field);\n }\n // Non-object rows (primitives, null) bypass the cache.\n if (typeof row !== 'object' || row === null) {\n return column.valueAccessor({ row, column, rowIndex });\n }\n // After the guard above, `row` is provably a non-null object. Single\n // assertion (no `as unknown as`) bridges the generic `TRow` to the WeakMap\n // key type; see `.github/instructions/typescript-conventions.instructions.md`.\n const rowKey = row as object;\n const key = column.field;\n let cellMap = accessorCache.get(rowKey);\n if (cellMap) {\n const box = cellMap.get(key);\n if (box !== undefined) return box.v;\n } else {\n cellMap = new Map();\n accessorCache.set(rowKey, cellMap);\n }\n const value = column.valueAccessor({ row, column, rowIndex });\n cellMap.set(key, { v: value });\n return value;\n}\n\n/**\n * Invalidate cached accessor values for a row (after in-place mutation),\n * a single (row, field) pair, or — when called with no argument — clear\n * the entire cache. Immutable updates auto-invalidate via row identity.\n *\n * Edit/transaction paths that mutate row objects in-place must call this.\n * @since 2.2.0\n */\nexport function invalidateAccessorCache(row?: object, field?: string): void {\n if (!row) {\n // WeakMap can't be cleared in O(1); the GC handles unreferenced rows.\n // For an explicit full reset, callers should mutate row identities instead.\n return;\n }\n if (!field) {\n accessorCache.delete(row);\n return;\n }\n accessorCache.get(row)?.delete(field);\n}\n\n/**\n * Build a `(value, row) => unknown` extractor compatible with\n * `filterValue`-style APIs from a column's `valueAccessor`. Returns `undefined`\n * when the column has no accessor.\n *\n * Used by FilteringPlugin to bridge the two API shapes without duplicating\n * cache lookups.\n */\nexport function accessorAsFilterValue<TRow>(\n column: ColumnConfig<TRow>,\n): ((value: unknown, row: TRow) => unknown) | undefined {\n if (!column.valueAccessor) return undefined;\n return (_value, row) => resolveCellValue(row, column);\n}\n","/**\n * Runtime default values for grid configuration.\n *\n * Kept out of `core/types.ts` so that file stays type-only apart from the two\n * enum-like consts whose `type` aliases are derived from them via `typeof`.\n * Import types from `./types`; import the values that back them from here.\n */\n\nimport type { A11yMessages, AnimationConfig, GridIcons } from './types';\n\n/**\n * Default English announcement messages.\n * Used when no custom messages are provided via {@link A11yConfig.messages}.\n * @since 2.0.0\n */\nexport const DEFAULT_A11Y_MESSAGES: A11yMessages = {\n sortApplied: (column, direction) => `Sorted by ${column}, ${direction}`,\n sortCleared: () => 'Sort cleared',\n filterApplied: (column) => `Filter applied on ${column}`,\n filterCleared: (column) => `Filter cleared from ${column}`,\n allFiltersCleared: () => 'All filters cleared',\n groupExpanded: (name, count) => `Group ${name} expanded, ${count} rows`,\n groupCollapsed: (name) => `Group ${name} collapsed`,\n selectionChanged: (count) => `${count} rows selected`,\n selectAllRows: () => 'Select all rows',\n selectRow: (rowIndex) => `Select row ${rowIndex + 1}`,\n columnSelected: (label) => `Column ${label} selected`,\n columnSelectionChanged: (count) => `${count} columns selected`,\n columnSelectionCleared: () => 'Column selection cleared',\n selectionAxisChanged: (toAxis) =>\n toAxis === 'column'\n ? 'Row selection cleared, column selection active'\n : 'Column selection cleared, row selection active',\n editingStarted: (rowIndex) => `Editing row ${rowIndex + 1}`,\n editingCommitted: (rowIndex) => `Row ${rowIndex + 1} saved`,\n dataLoaded: (count) => `${count} rows loaded`,\n};\n\n/**\n * Default animation configuration\n * @since 0.2.7\n */\nexport const DEFAULT_ANIMATION_CONFIG: Required<Omit<AnimationConfig, 'sort'>> = {\n mode: 'reduced-motion',\n duration: 200,\n easing: 'ease-out',\n};\n\n/**\n * Default icons used when not overridden. Most entries are short text/emoji;\n * `filter` and `filterActive` are empty strings because the actual rendering\n * is driven by the `--tbw-icon-filter[-active]-mask` CSS custom properties\n * (see `core/styles/variables.css`). Userland that wants an HTML/SVG fallback\n * via `gridConfig.icons.filter = '<svg…>'` is unaffected — that path overrides this default.\n * @since 0.1.1\n */\nexport const DEFAULT_GRID_ICONS: Required<GridIcons> = {\n expand: '▶',\n collapse: '▼',\n sortAsc: '▲',\n sortDesc: '▼',\n sortNone: '⇅',\n submenuArrow: '▶',\n dragHandle: '⋮⋮',\n toolPanel: '☰',\n filter: '',\n filterActive: '',\n print: '🖨️',\n};\n","/**\n * Centralized diagnostic messages for @toolbox-web/grid.\n *\n * Every user-facing warning, error, or info message in the grid has a unique\n * diagnostic code (e.g. `TBW001`). Each code maps to a section on the online\n * troubleshooting page, giving developers a direct link to resolution steps.\n *\n * ## Usage\n *\n * ```ts\n * import { MISSING_BREAKPOINT, warnDiagnostic, throwDiagnostic } from './diagnostics';\n *\n * // Warn with a code\n * warnDiagnostic(MISSING_BREAKPOINT, 'Set a breakpoint...', gridId);\n *\n * // Throw with a code\n * throwDiagnostic(MISSING_ROW_ID, 'Configure getRowId...', gridId);\n * ```\n *\n * Plugins should prefer `this.warn(MISSING_BREAKPOINT, message)` via BaseGridPlugin\n * instead of importing this module directly.\n *\n * @internal\n */\n\n// #region Grid Prefix\n\n/**\n * Build the `[tbw-grid]` or `[tbw-grid#my-id]` log prefix.\n * Pass `pluginName` for a scoped prefix like `[tbw-grid:SelectionPlugin]`.\n */\nexport function gridPrefix(gridId?: string, pluginName?: string): string {\n const id = gridId ? `#${gridId}` : '';\n const plugin = pluginName ? `:${pluginName}` : '';\n return `[tbw-grid${id}${plugin}]`;\n}\n\n// #endregion\n\n// #region Diagnostic Codes\n\n/**\n * Diagnostic codes used across the grid library.\n *\n * Each code is an individual export so that unused codes are tree-shaken\n * from bundles that don't reference them (esbuild can't tree-shake\n * properties from a single object).\n *\n * Naming: TBW + 3-digit number.\n * Ranges:\n * 001–019 Configuration validation (missing plugins, bad config)\n * 020–029 Plugin lifecycle (dependencies, incompatibilities, alias collapse)\n * 030–039 Feature registry\n * 040–049 Row operations (row ID, row mutations)\n * 050–059 Column operations (width, template)\n * 060–069 Rendering (callbacks, formatters, external views)\n * 070–079 Shell (tool panels, header/toolbar content)\n * 080–089 Editing & editors\n * 090–099 Print\n * 100–109 Clipboard\n * 110–119 Plugin-specific (responsive, undo-redo, grouping-columns)\n * 120–129 Style injection\n * 130–139 Attribute parsing\n * 140–149 DataSource / ServerSide\n */\n\n// --- Config validation (001–019) ---\n/** Column uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN = 'TBW001' as const;\n/** Grid config uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN_CONFIG = 'TBW002' as const;\n/** Plugin config rule violation (error severity). */\nexport const CONFIG_RULE_ERROR = 'TBW003' as const;\n/** Plugin config rule violation (warning severity). */\nexport const CONFIG_RULE_WARN = 'TBW004' as const;\n\n// --- Plugin lifecycle (020–029) ---\n/** Required plugin dependency is missing. */\nexport const MISSING_DEPENDENCY = 'TBW020' as const;\n/** Optional plugin dependency is missing. */\nexport const OPTIONAL_DEPENDENCY = 'TBW021' as const;\n/** Two loaded plugins are incompatible. */\nexport const INCOMPATIBLE_PLUGINS = 'TBW022' as const;\n/** Two plugin instances resolve to the same canonical name (alias collapse). */\nexport const PLUGIN_ALIAS_COLLAPSE = 'TBW023' as const;\n/** Error thrown inside a plugin event handler. */\nexport const PLUGIN_EVENT_ERROR = 'TBW024' as const;\n/** Conflicting config values found while merging alias-collapsed plugin instances. */\nexport const PLUGIN_ALIAS_CONFIG_CONFLICT = 'TBW025' as const;\n\n// --- Feature registry (030–039) ---\n/** Feature was re-registered (overwritten). */\nexport const FEATURE_REREGISTERED = 'TBW030' as const;\n/** Feature configured but not imported. */\nexport const FEATURE_NOT_IMPORTED = 'TBW031' as const;\n/** Feature depends on another feature that is not enabled. */\nexport const FEATURE_MISSING_DEP = 'TBW032' as const;\n\n// --- Row operations (040–049) ---\n/** Cannot determine row ID (no getRowId and no id property). */\nexport const MISSING_ROW_ID = 'TBW040' as const;\n/** Row with given ID not found. */\nexport const ROW_NOT_FOUND = 'TBW041' as const;\n\n// --- Column operations (050–059) ---\n/** Column has an invalid CSS width value. */\nexport const INVALID_COLUMN_WIDTH = 'TBW050' as const;\n\n// --- Rendering callbacks (060–069) ---\n/** rowClass callback threw an error. */\nexport const ROW_CLASS_ERROR = 'TBW060' as const;\n/** cellClass callback threw an error. */\nexport const CELL_CLASS_ERROR = 'TBW061' as const;\n/** Column format function threw an error. */\nexport const FORMAT_ERROR = 'TBW062' as const;\n/** External view mount() threw an error. */\nexport const VIEW_MOUNT_ERROR = 'TBW063' as const;\n/** External view event dispatch error. */\nexport const VIEW_DISPATCH_ERROR = 'TBW064' as const;\n\n// --- Shell (070–079) ---\n/** Tool panel missing required id. */\nexport const TOOL_PANEL_MISSING_ATTR = 'TBW070' as const;\n/** No tool panels registered. */\nexport const NO_TOOL_PANELS = 'TBW071' as const;\n/** Tool panel section not found. */\nexport const TOOL_PANEL_NOT_FOUND = 'TBW072' as const;\n/** Tool panel already registered. */\nexport const TOOL_PANEL_DUPLICATE = 'TBW073' as const;\n/** Header content already registered. */\nexport const HEADER_CONTENT_DUPLICATE = 'TBW074' as const;\n/** Toolbar content already registered. */\nexport const TOOLBAR_CONTENT_DUPLICATE = 'TBW075' as const;\n\n// --- Editing & editors (080–089) ---\n/** External editor mount() threw an error. */\nexport const EDITOR_MOUNT_ERROR = 'TBW080' as const;\n\n// --- Print (090–099) ---\n/** Print already in progress. */\nexport const PRINT_IN_PROGRESS = 'TBW090' as const;\n/** Grid not available for printing. */\nexport const PRINT_NO_GRID = 'TBW091' as const;\n/** Print operation failed. */\nexport const PRINT_FAILED = 'TBW092' as const;\n/** Multiple elements share the same grid ID (print isolation issue). */\nexport const PRINT_DUPLICATE_ID = 'TBW093' as const;\n\n// --- Clipboard (100–109) ---\n/** Clipboard API write failed. */\nexport const CLIPBOARD_FAILED = 'TBW100' as const;\n\n// --- Plugin-specific (110–119) ---\n/** ResponsivePlugin: no breakpoint configured. */\nexport const MISSING_BREAKPOINT = 'TBW110' as const;\n/** UndoRedoPlugin: transaction already in progress. */\nexport const TRANSACTION_IN_PROGRESS = 'TBW111' as const;\n/** UndoRedoPlugin: no transaction in progress. */\nexport const NO_TRANSACTION = 'TBW112' as const;\n/** GroupingColumnsPlugin: missing id or header on column group definition. */\nexport const COLUMN_GROUP_NO_ID = 'TBW113' as const;\n/** GroupingColumnsPlugin: conflicting columnGroups sources. */\nexport const COLUMN_GROUPS_CONFLICT = 'TBW114' as const;\n\n// --- Style injection (120–129) ---\n/** Failed to extract grid.css from document stylesheets. */\nexport const STYLE_EXTRACT_FAILED = 'TBW120' as const;\n/** Could not find grid.css in document.styleSheets. */\nexport const STYLE_NOT_FOUND = 'TBW121' as const;\n\n// --- Attribute parsing (130–139) ---\n/** Invalid JSON in an HTML attribute. */\nexport const INVALID_ATTRIBUTE_JSON = 'TBW130' as const;\n\n// --- DataSource / ServerSide (140–149) ---\n/** ServerSidePlugin: getRows() rejected. */\nexport const DATASOURCE_FETCH_ERROR = 'TBW140' as const;\n/** ServerSidePlugin: getChildRows() rejected. */\nexport const DATASOURCE_CHILD_FETCH_ERROR = 'TBW141' as const;\n/** ServerSidePlugin: getChildRows() not implemented but a plugin queried for children. */\nexport const DATASOURCE_NO_CHILD_HANDLER = 'TBW142' as const;\n/** ServerSidePlugin: concurrent request limit reached, request deferred. */\nexport const DATASOURCE_THROTTLED = 'TBW143' as const;\n\nexport type DiagnosticCode =\n | typeof MISSING_PLUGIN\n | typeof MISSING_PLUGIN_CONFIG\n | typeof CONFIG_RULE_ERROR\n | typeof CONFIG_RULE_WARN\n | typeof MISSING_DEPENDENCY\n | typeof OPTIONAL_DEPENDENCY\n | typeof INCOMPATIBLE_PLUGINS\n | typeof PLUGIN_ALIAS_COLLAPSE\n | typeof PLUGIN_EVENT_ERROR\n | typeof PLUGIN_ALIAS_CONFIG_CONFLICT\n | typeof FEATURE_REREGISTERED\n | typeof FEATURE_NOT_IMPORTED\n | typeof FEATURE_MISSING_DEP\n | typeof MISSING_ROW_ID\n | typeof ROW_NOT_FOUND\n | typeof INVALID_COLUMN_WIDTH\n | typeof ROW_CLASS_ERROR\n | typeof CELL_CLASS_ERROR\n | typeof FORMAT_ERROR\n | typeof VIEW_MOUNT_ERROR\n | typeof VIEW_DISPATCH_ERROR\n | typeof TOOL_PANEL_MISSING_ATTR\n | typeof NO_TOOL_PANELS\n | typeof TOOL_PANEL_NOT_FOUND\n | typeof TOOL_PANEL_DUPLICATE\n | typeof HEADER_CONTENT_DUPLICATE\n | typeof TOOLBAR_CONTENT_DUPLICATE\n | typeof EDITOR_MOUNT_ERROR\n | typeof PRINT_IN_PROGRESS\n | typeof PRINT_NO_GRID\n | typeof PRINT_FAILED\n | typeof PRINT_DUPLICATE_ID\n | typeof CLIPBOARD_FAILED\n | typeof MISSING_BREAKPOINT\n | typeof TRANSACTION_IN_PROGRESS\n | typeof NO_TRANSACTION\n | typeof COLUMN_GROUP_NO_ID\n | typeof COLUMN_GROUPS_CONFLICT\n | typeof STYLE_EXTRACT_FAILED\n | typeof STYLE_NOT_FOUND\n | typeof INVALID_ATTRIBUTE_JSON\n | typeof DATASOURCE_FETCH_ERROR\n | typeof DATASOURCE_CHILD_FETCH_ERROR\n | typeof DATASOURCE_NO_CHILD_HANDLER\n | typeof DATASOURCE_THROTTLED;\n\n// #endregion\n\n// #region Docs URL\n\nconst DOCS_BASE = 'https://toolboxjs.com/grid/errors';\n\n/** Build a direct link to the troubleshooting section for a code. */\nfunction docsUrl(code: DiagnosticCode): string {\n return `${DOCS_BASE}#${code.toLowerCase()}`;\n}\n\n// #endregion\n\n// #region Formatting\n\n/**\n * Format a diagnostic message with prefix, code, and docs link.\n *\n * Output format:\n * ```\n * [tbw-grid#my-id] TBW001: Your message here.\n *\n * → More info: https://toolboxjs.com/grid/errors#tbw001\n * ```\n */\nexport function formatDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): string {\n const prefix = gridPrefix(gridId, pluginName);\n return `${prefix} ${code}: ${message}\\n\\n → More info: ${docsUrl(code)}`;\n}\n\n// #endregion\n\n// #region Public API\n\n/**\n * Throw an error with a diagnostic code and docs link.\n * Use for configuration errors and API misuse that should halt execution.\n */\nexport function throwDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): never {\n throw new Error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a warning with a diagnostic code and docs link.\n * Use for recoverable issues the developer should fix.\n */\nexport function warnDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.warn(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a debug message with a diagnostic code and docs link.\n * Use for optional/soft dependency notifications — visible only when\n * the browser DevTools \"Verbose\" log level is enabled.\n */\nexport function debugDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.debug(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log an error with a diagnostic code and docs link.\n * Use for non-throwing errors (e.g., failed async operations).\n */\nexport function errorDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n// #endregion\n","// Centralized template expression evaluation & sanitization utilities.\n// Responsible for safely interpolating {{ }} expressions while blocking\n// access to dangerous globals / reflective capabilities.\nimport type { CompiledViewFunction, EvalContext } from '../types';\n\n// #region Constants\nconst EXPR_RE = /{{\\s*([^}]+)\\s*}}/g;\nconst EMPTY_SENTINEL = '__DG_EMPTY__';\nconst SAFE_EXPR = /^[\\w$. '?+\\-*/%:()!<>=,&|]+$/;\n\n// Forbidden identifiers built at runtime to avoid static analysis scanners\n// from flagging string literals (e.g. socket.dev \"network access\" / \"uses eval\").\n// Stored as reversed, pipe-delimited tokens — reversed back when constructing the regex.\nconst _F =\n '__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles'\n .split('|')\n .map((s) => s.split('').reverse().join(''));\nconst FORBIDDEN = new RegExp(`__(proto|defineGetter|defineSetter)|${_F.slice(3).join('|')}|this\\\\b`);\n// #endregion\n\n// #region HTML Sanitization\n\n/**\n * Escape a plain text string for safe insertion into HTML.\n * Converts special HTML characters to their entity equivalents.\n *\n * @param text - Plain text string to escape\n * @returns HTML-safe string\n */\nexport function escapeHtml(text: string): string {\n if (!text || typeof text !== 'string') return '';\n return text\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n/**\n * Tags that are considered dangerous and will be completely removed.\n * These can execute scripts, load external resources, or manipulate the page.\n */\nconst DANGEROUS_TAGS = new Set(\n 'script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing|math'.split(\n '|',\n ),\n);\n\n/**\n * Attributes that are considered dangerous - event handlers and data loading.\n */\nconst DANGEROUS_ATTR_PATTERN = /^on\\w+$/i;\n\n/**\n * Attributes that can contain URLs which might be javascript: or data: URIs.\n */\nconst URL_ATTRS = new Set('href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset'.split('|'));\n\n/**\n * Protocol patterns that are dangerous in URLs.\n */\nconst DANGEROUS_URL_PROTOCOL = /^\\s*(javascript|vbscript|data|blob):/i;\n\n/**\n * Sanitize an HTML string by removing dangerous tags and attributes.\n *\n * Prefer {@link setSanitizedHTML} wherever the result is destined for an\n * element: this function has to re-serialize the sanitized tree back to a\n * string, and the caller's `innerHTML =` then re-parses it. That\n * parse→serialize→parse round trip is the classic mutation-XSS vector, and it\n * costs a second parse. Use this overload only when a string is genuinely\n * required (e.g. the value is stored, compared, or handed to another API).\n *\n * @param html - Raw HTML string to sanitize\n * @returns Sanitized HTML string safe for innerHTML\n */\nexport function sanitizeHTML(html: string): string {\n if (!html || typeof html !== 'string') return '';\n\n // Fast path: if no HTML tags at all, return as-is (already safe)\n if (html.indexOf('<') === -1) return html;\n\n const template = document.createElement('template');\n template.innerHTML = html;\n\n sanitizeNode(template.content);\n\n return template.innerHTML;\n}\n\n/**\n * Parse and sanitize an HTML string into a detached {@link DocumentFragment}.\n *\n * This is the primitive {@link setSanitizedHTML} builds on, exposed for callers\n * that need to inspect or relocate the nodes before insertion.\n *\n * @param html - Raw HTML string to sanitize\n * @returns Fragment containing the sanitized nodes (empty for falsy input)\n */\nexport function sanitizeToFragment(html: string): DocumentFragment {\n const template = document.createElement('template');\n if (html && typeof html === 'string') {\n template.innerHTML = html;\n sanitizeNode(template.content);\n }\n return template.content;\n}\n\n/**\n * Replace an element's children with the sanitized parse of `html`.\n *\n * **This is the canonical sink for user-supplied markup** — cell/header/group\n * renderer string returns, `gridConfig.icons.*`, light-DOM tool panel fallback\n * content, and any new extension point that turns a user string into markup.\n * `textContent` is wrong here (it renders SVG icon strings as literal text) and\n * raw `innerHTML` is wrong (it is an XSS sink).\n *\n * Nodes are moved from the parse fragment rather than re-serialized, so the\n * sanitized tree is exactly what lands in the document.\n *\n * @param el - Element whose children are replaced\n * @param html - Raw HTML string to sanitize and insert\n */\nexport function setSanitizedHTML(el: Element, html: string): void {\n if (!html || typeof html !== 'string') {\n el.replaceChildren();\n return;\n }\n // Nothing for the parser to do: no markup and no entities to decode.\n if (html.indexOf('<') === -1 && html.indexOf('&') === -1) {\n el.textContent = html;\n return;\n }\n el.replaceChildren(sanitizeToFragment(html));\n}\n\n/**\n * Recursively sanitize a DOM node tree.\n */\nfunction sanitizeNode(root: DocumentFragment | Element): void {\n const toRemove: Element[] = [];\n\n // Use querySelectorAll to find all elements, then filter\n const elements = root.querySelectorAll('*');\n\n for (const el of elements) {\n const tagName = el.tagName.toLowerCase();\n\n // Check if tag is dangerous\n if (DANGEROUS_TAGS.has(tagName)) {\n toRemove.push(el);\n continue;\n }\n\n // SVG elements need special handling - they can contain script-like behavior\n if (tagName === 'svg' || el.namespaceURI === 'http://www.w3.org/2000/svg') {\n // Remove entire SVG if it has any suspicious attributes\n const hasDangerousContent = Array.from(el.attributes).some(\n (attr) => DANGEROUS_ATTR_PATTERN.test(attr.name) || attr.name === 'href' || attr.name === 'xlink:href',\n );\n if (hasDangerousContent) {\n toRemove.push(el);\n continue;\n }\n }\n\n // Check and remove dangerous attributes\n const attrsToRemove: string[] = [];\n for (const attr of el.attributes) {\n const attrName = attr.name.toLowerCase();\n\n // Event handlers (onclick, onerror, onload, etc.)\n if (DANGEROUS_ATTR_PATTERN.test(attrName)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // `is=` upgrades a plain tag into a registered customized built-in, so it\n // can smuggle behaviour past the tag-name check above.\n if (attrName === 'is') {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // URL attributes with dangerous protocols\n if (URL_ATTRS.has(attrName) && DANGEROUS_URL_PROTOCOL.test(attr.value)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // style attribute can contain expressions (IE) or url() with javascript:\n if (attrName === 'style' && /expression\\s*\\(|javascript:|behavior\\s*:/i.test(attr.value)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n }\n\n attrsToRemove.forEach((name) => el.removeAttribute(name));\n }\n\n // Remove dangerous elements (do this after iteration to avoid modifying during traversal)\n toRemove.forEach((el) => el.remove());\n}\n\n// #endregion\n\n// #region Template Evaluation\n\n// #region Safe Expression Evaluator\n// A minimal recursive-descent evaluator for the token set allowed by SAFE_EXPR.\n// Replaces `new Function()` to avoid dynamic code execution warnings from\n// static analysis tools (socket.dev, npm audit) while maintaining identical\n// functionality for expressions that pass the allowlist guards.\n//\n// Supported grammar (matching SAFE_EXPR = /^[\\w$. '?+\\-*/%:()!<>=,&|]+$/):\n// ternary → logicalOr ('?' ternary ':' ternary)?\n// logicalOr → logicalAnd ('||' logicalAnd)*\n// logicalAnd → equality ('&&' equality)*\n// equality → comparison (('==' | '!=' | '===' | '!==') comparison)*\n// comparison → additive (('<' | '>' | '<=' | '>=') additive)*\n// additive → multiplicative (('+' | '-') multiplicative)*\n// multiplicative → unary (('*' | '/' | '%') unary)*\n// unary → '!' unary | primary\n// primary → NUMBER | STRING | IDENT ('.' IDENT)? | '(' ternary ')'\n\ntype Token =\n { type: 'num'; v: number } | { type: 'str'; v: string } | { type: 'id'; v: string } | { type: 'op'; v: string };\n\nfunction tokenize(expr: string): Token[] | null {\n const tokens: Token[] = [];\n let i = 0;\n while (i < expr.length) {\n const ch = expr[i];\n if (ch === ' ') {\n i++;\n continue;\n }\n\n // Numbers\n if ((ch >= '0' && ch <= '9') || (ch === '.' && i + 1 < expr.length && expr[i + 1] >= '0' && expr[i + 1] <= '9')) {\n const start = i;\n while (i < expr.length && ((expr[i] >= '0' && expr[i] <= '9') || expr[i] === '.')) i++;\n tokens.push({ type: 'num', v: Number(expr.slice(start, i)) });\n continue;\n }\n\n // String literals (single-quoted only, per SAFE_EXPR)\n if (ch === \"'\") {\n let s = '';\n i++; // skip opening quote\n while (i < expr.length && expr[i] !== \"'\") s += expr[i++];\n if (i >= expr.length) return null; // unterminated\n i++; // skip closing quote\n tokens.push({ type: 'str', v: s });\n continue;\n }\n\n // Identifiers (value, row, row.field)\n if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '_' || ch === '$') {\n const start = i;\n while (i < expr.length && /[\\w$.]/.test(expr[i])) i++;\n tokens.push({ type: 'id', v: expr.slice(start, i) });\n continue;\n }\n\n // Multi-char operators\n if (i + 2 < expr.length) {\n const tri = expr.slice(i, i + 3);\n if (tri === '===' || tri === '!==') {\n tokens.push({ type: 'op', v: tri });\n i += 3;\n continue;\n }\n }\n if (i + 1 < expr.length) {\n const bi = expr.slice(i, i + 2);\n if (bi === '==' || bi === '!=' || bi === '<=' || bi === '>=' || bi === '&&' || bi === '||') {\n tokens.push({ type: 'op', v: bi });\n i += 2;\n continue;\n }\n }\n\n // Single-char operators\n if ('+-*/%<>!?:(),'.includes(ch)) {\n tokens.push({ type: 'op', v: ch });\n i++;\n continue;\n }\n\n return null; // unexpected character\n }\n return tokens;\n}\n\nfunction safeEval(expr: string, ctx: EvalContext): unknown {\n const toks = tokenize(expr);\n if (!toks) return undefined;\n const tokens: Token[] = toks;\n let pos = 0;\n\n function peek(): Token | undefined {\n return tokens[pos];\n }\n function advance(): Token {\n return tokens[pos++];\n }\n function match(type: string, val?: string): boolean {\n const t = peek();\n if (!t) return false;\n if (t.type !== type) return false;\n if (val !== undefined && t.v !== val) return false;\n return true;\n }\n\n function resolveId(name: string): unknown {\n if (name === 'value') return ctx.value;\n if (name.startsWith('row.')) {\n const key = name.slice(4);\n return ctx.row ? ctx.row[key] : undefined;\n }\n if (name.startsWith('typeDefault.')) {\n const key = name.slice('typeDefault.'.length);\n return ctx.typeDefault ? ctx.typeDefault[key] : undefined;\n }\n // bare 'row' reference\n if (name === 'row') return ctx.row;\n if (name === 'typeDefault') return ctx.typeDefault;\n return undefined;\n }\n\n function parseTernary(): unknown {\n const result = parseLogicalOr();\n if (match('op', '?')) {\n advance(); // consume '?'\n const consequent = parseTernary();\n if (!match('op', ':')) return undefined;\n advance(); // consume ':'\n const alternate = parseTernary();\n return result ? consequent : alternate;\n }\n return result;\n }\n\n function parseLogicalOr(): unknown {\n let left = parseLogicalAnd();\n while (match('op', '||')) {\n advance();\n left = left || parseLogicalAnd();\n }\n return left;\n }\n\n function parseLogicalAnd(): unknown {\n let left = parseEquality();\n while (match('op', '&&')) {\n advance();\n left = left && parseEquality();\n }\n return left;\n }\n\n function parseEquality(): unknown {\n let left = parseComparison();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '===') {\n advance();\n left = left === parseComparison();\n } else if (t.v === '!==') {\n advance();\n left = left !== parseComparison();\n } else if (t.v === '==') {\n advance();\n left = left == parseComparison();\n } else if (t.v === '!=') {\n advance();\n left = left != parseComparison();\n } else break;\n }\n return left;\n }\n\n function parseComparison(): unknown {\n let left = parseAdditive();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '<') {\n advance();\n left = (left as number) < (parseAdditive() as number);\n } else if (t.v === '>') {\n advance();\n left = (left as number) > (parseAdditive() as number);\n } else if (t.v === '<=') {\n advance();\n left = (left as number) <= (parseAdditive() as number);\n } else if (t.v === '>=') {\n advance();\n left = (left as number) >= (parseAdditive() as number);\n } else break;\n }\n return left;\n }\n\n function parseAdditive(): unknown {\n let left = parseMultiplicative();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '+') {\n advance();\n left = (left as number) + (parseMultiplicative() as number);\n } else if (t.v === '-') {\n advance();\n left = (left as number) - (parseMultiplicative() as number);\n } else break;\n }\n return left;\n }\n\n function parseMultiplicative(): unknown {\n let left = parseUnary();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '*') {\n advance();\n left = (left as number) * (parseUnary() as number);\n } else if (t.v === '/') {\n advance();\n left = (left as number) / (parseUnary() as number);\n } else if (t.v === '%') {\n advance();\n left = (left as number) % (parseUnary() as number);\n } else break;\n }\n return left;\n }\n\n function parseUnary(): unknown {\n if (match('op', '!')) {\n advance();\n return !parseUnary();\n }\n return parsePrimary();\n }\n\n function parsePrimary(): unknown {\n const t = peek();\n if (!t) return undefined;\n if (t.type === 'num') {\n advance();\n return t.v;\n }\n if (t.type === 'str') {\n advance();\n return t.v;\n }\n if (t.type === 'id') {\n advance();\n return resolveId(t.v as string);\n }\n if (t.type === 'op' && t.v === '(') {\n advance(); // consume '('\n const result = parseTernary();\n if (match('op', ')')) advance(); // consume ')'\n return result;\n }\n // Unary minus for negative numbers\n if (t.type === 'op' && t.v === '-') {\n advance();\n return -(parsePrimary() as number);\n }\n return undefined;\n }\n\n const result = parseTernary();\n // Ensure all tokens were consumed\n if (pos < tokens.length) return undefined;\n return result;\n}\n// #endregion\n\nexport function evalTemplateString(raw: string, ctx: EvalContext): string {\n if (!raw || raw.indexOf('{{') === -1) return raw; // fast path (no expressions)\n const parts: { expr: string; result: string }[] = [];\n const evaluated = raw.replace(EXPR_RE, (_m, expr) => {\n const res = evalSingle(expr, ctx);\n parts.push({ expr: expr.trim(), result: res });\n // The template markup is author-controlled; the interpolated data is not.\n // Escaping here stops row data from injecting elements or breaking out of\n // an attribute (sanitizeHTML downstream only strips *dangerous* markup).\n return res === EMPTY_SENTINEL ? res : escapeHtml(res);\n });\n const finalStr = postProcess(evaluated);\n // If every part evaluated to EMPTY_SENTINEL we treat this as intentionally blank.\n // If any expression was blocked due to forbidden token (EMPTY_SENTINEL) we *still* only output ''\n // but do not escalate to BLOCKED_SENTINEL unless the original contained explicit forbidden tokens.\n const allEmpty = parts.length && parts.every((p) => p.result === '' || p.result === EMPTY_SENTINEL);\n const hadForbidden = REFLECTIVE_RE.test(raw);\n if (hadForbidden || allEmpty) return '';\n return finalStr;\n}\n\nfunction evalSingle(expr: string, ctx: EvalContext): string {\n expr = (expr || '').trim();\n if (!expr) return EMPTY_SENTINEL;\n if (REFLECTIVE_RE.test(expr)) return EMPTY_SENTINEL;\n if (expr === 'value') return ctx.value == null ? EMPTY_SENTINEL : String(ctx.value);\n if (expr.startsWith('row.') && !/[()?]/.test(expr) && !expr.includes(':')) {\n const key = expr.slice(4);\n const v = ctx.row ? ctx.row[key] : undefined;\n return v == null ? EMPTY_SENTINEL : String(v);\n }\n if (expr.startsWith('typeDefault.') && !/[()?]/.test(expr) && !expr.includes(':')) {\n const key = expr.slice('typeDefault.'.length);\n const v = ctx.typeDefault ? ctx.typeDefault[key] : undefined;\n return v == null ? EMPTY_SENTINEL : String(v);\n }\n if (expr.length > 80) return EMPTY_SENTINEL;\n if (!SAFE_EXPR.test(expr) || FORBIDDEN.test(expr)) return EMPTY_SENTINEL;\n const dotChain = expr.match(/\\./g);\n if (dotChain && dotChain.length > 1) return EMPTY_SENTINEL;\n try {\n const out = safeEval(expr, ctx);\n const str = out == null ? '' : String(out);\n if (REFLECTIVE_RE.test(str)) return EMPTY_SENTINEL;\n return str || EMPTY_SENTINEL;\n } catch {\n return EMPTY_SENTINEL;\n }\n}\n// #endregion\n\n// #region Cell Scrubbing\n/** Pattern matching reflective/introspective APIs that must be stripped from output. */\nconst REFLECTIVE_RE = /Reflect|Proxy|ownKeys/;\n\nfunction postProcess(s: string): string {\n if (!s) return s;\n return s.replace(new RegExp(EMPTY_SENTINEL, 'g'), '').replace(/Reflect\\.[^<>{}\\s]+|\\bProxy\\b|ownKeys\\([^)]*\\)/g, '');\n}\n\nexport function finalCellScrub(cell: HTMLElement): void {\n if (!REFLECTIVE_RE.test(cell.textContent || '')) return;\n // First pass: clear only text nodes containing forbidden tokens\n for (const n of cell.childNodes) {\n if (n.nodeType === Node.TEXT_NODE && REFLECTIVE_RE.test(n.textContent || '')) n.textContent = '';\n }\n // If forbidden tokens persist in element nodes, nuke everything\n if (REFLECTIVE_RE.test(cell.textContent || '')) {\n cell.textContent = '';\n }\n}\n// #endregion\n\n// #region Template Compilation\nexport function compileTemplate(raw: string) {\n if (REFLECTIVE_RE.test(raw)) {\n const fn = (() => '') as CompiledViewFunction;\n fn.__blocked = true;\n return fn;\n }\n const fn = ((ctx: EvalContext) => evalTemplateString(raw, ctx)) as CompiledViewFunction;\n fn.__blocked = false;\n return fn;\n}\n// #endregion\n","/**\n * Base Grid Plugin Class\n *\n * All plugins extend this abstract class.\n * Plugins are instantiated per-grid and manage their own state.\n */\n\n// Injected by Vite at build time from package.json (same as grid.ts)\ndeclare const __GRID_VERSION__: string;\n\nimport type { HeaderContentDefinition, ToolPanelDefinition } from '../../plugins/shell/types';\nimport { DEFAULT_GRID_ICONS } from '../defaults';\nimport {\n type DiagnosticCode,\n PLUGIN_ALIAS_CONFIG_CONFLICT,\n formatDiagnostic,\n gridPrefix,\n} from '../internal/diagnostics';\nimport { setSanitizedHTML } from '../internal/sanitize';\nimport type {\n ColumnConfig,\n ColumnState,\n GridConfig,\n GridIcons,\n GridPlugin,\n IconValue,\n PluginNameMap,\n Translate,\n} from '../types';\n\n// Re-export shared plugin types for convenience\nexport type {\n AfterCellRenderContext,\n AfterRowRenderContext,\n CellClickEvent,\n CellCoords,\n CellEditor,\n CellMouseEvent,\n CellRenderer,\n ContextMenuItem,\n ContextMenuParams,\n GridElementRef,\n HeaderClickEvent,\n HeaderRenderer,\n KeyboardModifiers,\n PluginCellRenderContext,\n PluginQuery,\n RowClickEvent,\n ScrollEvent,\n} from './types';\n\nimport type {\n AfterCellRenderContext,\n AfterRowRenderContext,\n CellClickEvent,\n CellEditor,\n CellMouseEvent,\n CellRenderer,\n GridElementRef,\n HeaderClickEvent,\n HeaderRenderer,\n PluginQuery,\n RowClickEvent,\n ScrollEvent,\n} from './types';\n\n/**\n * Grid element interface for plugins.\n * Extends GridElementRef with plugin-specific methods.\n * Note: effectiveConfig is already available from GridElementRef.\n */\nexport interface GridElement extends GridElementRef {\n getPlugin<T extends GridPlugin>(PluginClass: new (...args: any[]) => T): T | undefined;\n getPluginByName<K extends string>(\n name: K,\n ): (K extends keyof PluginNameMap ? PluginNameMap[K] : BaseGridPlugin) | undefined;\n /**\n * Get a plugin's state by plugin name.\n * This is a loose-coupling method for plugins to access other plugins' state\n * without importing the plugin class directly.\n * @internal Plugin API\n */\n getPluginState?(name: string): unknown;\n\n // Focus Management\n /** Register an external DOM element as a logical focus container. @internal Plugin API */\n registerExternalFocusContainer?(el: Element): void;\n /** Unregister a previously registered external focus container. @internal Plugin API */\n unregisterExternalFocusContainer?(el: Element): void;\n /** Check whether focus is logically inside this grid (own DOM + external containers). @internal Plugin API */\n containsFocus?(node?: Node | null): boolean;\n}\n\n/**\n * Header render context for plugin header renderers.\n */\nexport interface PluginHeaderRenderContext {\n /** Column configuration */\n column: ColumnConfig;\n /** Column index */\n colIndex: number;\n}\n\n// ============================================================================\n// Plugin Dependency Types\n// ============================================================================\n\n/**\n * Declares a dependency on another plugin.\n *\n * @category Plugin Development\n * @example\n * ```typescript\n * export class UndoRedoPlugin extends BaseGridPlugin {\n * static readonly dependencies: PluginDependency[] = [\n * { name: 'editing', required: true },\n * ];\n * }\n * ```\n * @since 0.4.1\n */\nexport interface PluginDependency {\n /**\n * The name of the required plugin (matches the plugin's `name` property).\n * Use string names for loose coupling - avoids static imports.\n */\n name: string;\n\n /**\n * Whether this dependency is required (hard) or optional (soft).\n * - `true`: Plugin cannot function without it. Throws error if missing.\n * - `false`: Plugin works with reduced functionality. Silent if missing\n * (set {@link severity} to `'warn'` or `'info'` to opt into a message).\n * @default true\n */\n required?: boolean;\n\n /**\n * Explicit severity when this dependency is missing. Overrides the default\n * derived from {@link required}.\n * - `'error'`: throw (halts grid setup). Default when `required` is not `false`.\n * - `'warn'`: log a console warning and continue (development only).\n * - `'info'`: log a verbose console.debug message and continue (development only).\n *\n * When omitted, a missing hard dependency throws and a missing soft\n * dependency is silent — preserving backward-compatible behavior.\n * @since 2.16.0\n */\n severity?: 'error' | 'warn' | 'info';\n\n /**\n * Optional predicate that gates whether this dependency applies, evaluated\n * against the depending plugin's own resolved configuration (defaults merged\n * with user config). Return `false` to skip the dependency entirely.\n *\n * Lets a plugin require/recommend another plugin only under certain config\n * — e.g. a plugin that needs a tool-panel host only when its tool panel is\n * enabled. When omitted, the dependency always applies.\n * @example when: (cfg: PivotConfig) => cfg.showToolPanel === true\n * @since 2.16.0\n */\n when?: (pluginConfig: unknown) => boolean;\n\n /**\n * Human-readable reason for this dependency.\n * Shown in error/info messages to help users understand why.\n * @example \"UndoRedoPlugin needs EditingPlugin to track cell edits\"\n */\n reason?: string;\n}\n\n/**\n * Declares an incompatibility between plugins.\n * When both plugins are loaded, a warning is logged to help users understand the conflict.\n *\n * @category Plugin Development\n */\nexport interface PluginIncompatibility {\n /**\n * The name of the incompatible plugin (matches the plugin's `name` property).\n */\n name: string;\n\n /**\n * Human-readable reason for the incompatibility.\n * Should explain why the plugins conflict and any workarounds.\n * @example \"Both transform the entire row model in different ways\"\n */\n reason: string;\n}\n\n// ============================================================================\n// Plugin Query & Event Definitions\n// ============================================================================\n\n/**\n * Defines a query that a plugin can handle.\n * Other plugins or the grid can send this query type to retrieve data.\n *\n * @category Plugin Development\n *\n * @example\n * ```typescript\n * // In manifest\n * queries: [\n * {\n * type: 'canMoveColumn',\n * description: 'Check if a column can be moved/reordered',\n * },\n * ]\n *\n * // In plugin class\n * handleQuery(query: PluginQuery): unknown {\n * if (query.type === 'canMoveColumn') {\n * return this.canMoveColumn(query.context);\n * }\n * }\n * ```\n * @since 1.8.0\n */\nexport interface QueryDefinition {\n /**\n * The query type identifier (e.g., 'canMoveColumn', 'getContextMenuItems').\n * Should be unique across all plugins.\n */\n type: string;\n\n /**\n * Human-readable description of what the query does.\n */\n description?: string;\n}\n\n/**\n * Defines an event that a plugin can emit.\n * Other plugins can subscribe to these events via the Event Bus.\n *\n * @category Plugin Development\n *\n * @example\n * ```typescript\n * // In manifest\n * events: [\n * {\n * type: 'filter-change',\n * description: 'Emitted when filter criteria change',\n * },\n * ]\n *\n * // In plugin class - emit\n * this.emitPluginEvent('filter-change', { field: 'name', value: 'Alice' });\n *\n * // In another plugin - subscribe\n * this.on('filter-change', (detail) => console.log('Filter changed:', detail));\n * ```\n * @since 1.8.0\n */\nexport interface EventDefinition {\n /**\n * The event type identifier (e.g., 'filter-change', 'selection-change').\n * Used when emitting and subscribing to events.\n */\n type: string;\n\n /**\n * Human-readable description of what the event represents.\n */\n description?: string;\n\n /**\n * Whether this event is cancelable via `event.preventDefault()`.\n * @default false\n */\n cancelable?: boolean;\n}\n\n// ============================================================================\n// Plugin Manifest Types\n// ============================================================================\n\n/**\n * Defines a property that a plugin \"owns\" - used for configuration validation.\n * When this property is used without the owning plugin loaded, an error is thrown.\n *\n * @category Plugin Development\n */\nexport interface PluginPropertyDefinition {\n /** The property name on column or grid config */\n property: string;\n /** Whether this is a column-level or config-level property */\n level: 'column' | 'config';\n /** Human-readable description for error messages (e.g., 'the \"editable\" column property') */\n description: string;\n /** Import path hint for error messages (e.g., \"import { EditingPlugin } from '@toolbox-web/grid/plugins/editing';\") */\n importHint?: string;\n /** Custom check for whether property is considered \"used\" (default: truthy value check) */\n isUsed?: (value: unknown) => boolean;\n}\n\n/**\n * A configuration validation rule for detecting invalid/conflicting settings.\n * Plugins declare rules in their manifest; the validator executes them during grid initialization.\n *\n * @category Plugin Development\n * @template TConfig - The plugin's configuration type\n */\nexport interface PluginConfigRule<TConfig = unknown> {\n /** Rule identifier for debugging (e.g., 'selection/range-dblclick') */\n id: string;\n /** Severity: 'error' throws, 'warn' logs warning */\n severity: 'error' | 'warn';\n /** Human-readable message shown when rule is violated */\n message: string;\n /** Predicate returning true if the rule is VIOLATED (i.e., config is invalid) */\n check: (pluginConfig: TConfig) => boolean;\n}\n\n/**\n * Hook names that can have execution priority configured.\n *\n * @category Plugin Development\n */\nexport type HookName =\n | 'processColumns'\n | 'processConfig'\n | 'processRows'\n | 'afterStructuralRender'\n | 'afterRender'\n | 'afterCellRender'\n | 'afterRowRender'\n | 'onCellClick'\n | 'onCellMouseDown'\n | 'onCellMouseMove'\n | 'onCellMouseUp'\n | 'onHeaderClick'\n | 'onKeyDown'\n | 'onRowClick'\n | 'onScroll'\n | 'onScrollRender';\n\n/**\n * Static metadata about a plugin's capabilities and requirements.\n * Declared as a static property on plugin classes.\n *\n * @category Plugin Development\n * @template TConfig - The plugin's configuration type\n *\n * @example\n * ```typescript\n * export class MyPlugin extends BaseGridPlugin<MyConfig> {\n * static override readonly manifest: PluginManifest<MyConfig> = {\n * ownedProperties: [\n * { property: 'myProp', level: 'column', description: 'the \"myProp\" column property' },\n * ],\n * configRules: [\n * { id: 'my-plugin/invalid-combo', severity: 'warn', message: '...', check: (c) => c.a && c.b },\n * ],\n * };\n * readonly name = 'myPlugin';\n * }\n * ```\n * @since 1.1.0\n */\nexport interface PluginManifest<TConfig = unknown> {\n /**\n * Properties this plugin owns - validated by validate-config.ts.\n * If a user uses one of these properties without loading the plugin, an error is thrown.\n */\n ownedProperties?: PluginPropertyDefinition[];\n\n /**\n * Hook execution priority (higher = later, default 0).\n * Use negative values to run earlier, positive to run later.\n */\n hookPriority?: Partial<Record<HookName, number>>;\n\n /**\n * Configuration validation rules - checked during grid initialization.\n * Rules with severity 'error' throw, 'warn' logs to console.\n */\n configRules?: PluginConfigRule<TConfig>[];\n\n /**\n * Plugins that are incompatible with this plugin.\n * When both plugins are loaded together, a warning is shown.\n *\n * @example\n * ```typescript\n * incompatibleWith: [\n * { name: 'tree', reason: 'Both transform the entire row model in different ways' },\n * ],\n * ```\n */\n incompatibleWith?: PluginIncompatibility[];\n\n /**\n * Queries this plugin can handle.\n * Declares what query types this plugin responds to via `handleQuery()`.\n * This replaces the centralized PLUGIN_QUERIES approach with manifest-declared queries.\n *\n * @example\n * ```typescript\n * queries: [\n * { type: 'canMoveColumn', description: 'Check if a column can be moved' },\n * ],\n * ```\n */\n queries?: QueryDefinition[];\n\n /**\n * Events this plugin can emit.\n * Declares what event types other plugins can subscribe to via `on()`.\n *\n * @example\n * ```typescript\n * events: [\n * { type: 'filter-change', description: 'Emitted when filter criteria change' },\n * ],\n * ```\n */\n events?: EventDefinition[];\n\n /**\n * Whether this plugin's `processRows` hook injects or removes rows\n * (group headers, tree nodes, pivot aggregates, placeholders, etc.).\n *\n * When true, the core sorting module delegates to the render scheduler\n * instead of sorting `_rows` in-place, because `_rows` may contain\n * plugin-generated marker objects that would be corrupted by a direct sort.\n *\n * Plugins that only **filter** or **reorder** existing rows (e.g. Filtering,\n * MultiSort) should leave this unset or set it to `false`.\n */\n modifiesRowStructure?: boolean;\n}\n\n/** Convert camelCase icon key to kebab-case data-icon attribute value. */\nexport function toIconAttr(key: string): string {\n return key.replace(/([A-Z])/g, '-$1').toLowerCase();\n}\n\n/**\n * Abstract base class for all grid plugins.\n *\n * @category Plugin Development\n * @template TConfig - Configuration type for the plugin\n * @since 0.1.1\n */\nexport abstract class BaseGridPlugin<TConfig = unknown> implements GridPlugin {\n /**\n * Plugin dependencies - declare other plugins this one requires.\n *\n * Dependencies are validated when the plugin is attached.\n * Required dependencies throw an error if missing. Optional dependencies are\n * silent by default; set a {@link PluginDependency.severity} of `'warn'` or\n * `'info'` to opt into a development-only log.\n *\n * @example\n * ```typescript\n * static readonly dependencies: PluginDependency[] = [\n * { name: 'editing', required: true, reason: 'Tracks cell edits for undo/redo' },\n * { name: 'selection', required: false, reason: 'Enables selection-based undo' },\n * ];\n * ```\n */\n static readonly dependencies?: PluginDependency[];\n\n /**\n * Plugin manifest - declares owned properties, config rules, and hook priorities.\n *\n * This is read by the configuration validator to:\n * - Validate that required plugins are loaded when their properties are used\n * - Execute configRules to detect invalid/conflicting settings\n * - Order hook execution based on priority\n *\n * @example\n * ```typescript\n * static override readonly manifest: PluginManifest<MyConfig> = {\n * ownedProperties: [\n * { property: 'myProp', level: 'column', description: 'the \"myProp\" column property' },\n * ],\n * configRules: [\n * { id: 'myPlugin/conflict', severity: 'warn', message: '...', check: (c) => c.a && c.b },\n * ],\n * };\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static readonly manifest?: PluginManifest<any>;\n\n /** Unique plugin identifier (derived from class name by default) */\n abstract readonly name: string;\n\n /**\n * Alternative names for backward compatibility.\n * `getPluginByName()` matches against both `name` and `aliases`.\n * @internal\n */\n readonly aliases?: readonly string[];\n\n /**\n * Plugin version - defaults to grid version for built-in plugins.\n * Third-party plugins can override with their own semver.\n */\n readonly version: string = typeof __GRID_VERSION__ !== 'undefined' ? __GRID_VERSION__ : 'dev';\n\n /** CSS styles to inject via `document.adoptedStyleSheets` */\n readonly styles?: string;\n\n /** Custom cell renderers keyed by type name */\n readonly cellRenderers?: Record<string, CellRenderer>;\n\n /** Custom header renderers keyed by type name */\n readonly headerRenderers?: Record<string, HeaderRenderer>;\n\n /** Custom cell editors keyed by type name */\n readonly cellEditors?: Record<string, CellEditor>;\n\n /** The grid instance this plugin is attached to */\n protected grid!: GridElement;\n\n /** Plugin configuration - merged with defaults in attach() */\n protected config!: TConfig;\n\n /** User-provided configuration from constructor */\n protected readonly userConfig: Partial<TConfig>;\n\n /**\n * Plugin-level AbortController for event listener cleanup.\n * Created fresh in attach(), aborted in detach().\n * This ensures event listeners are properly cleaned up when plugins are re-attached.\n */\n #abortController?: AbortController;\n\n /**\n * Default configuration - subclasses should override this getter.\n * Note: This must be a getter (not property initializer) for proper inheritance\n * since property initializers run after parent constructor.\n */\n protected get defaultConfig(): Partial<TConfig> {\n return {};\n }\n\n constructor(config: Partial<TConfig> = {}) {\n this.userConfig = config;\n }\n\n /**\n * Effective configuration (defaults merged with user config), resolved\n * eagerly so it is available **before** {@link attach} runs. Dependency\n * validation happens before `attach()` merges {@link config}, so config\n * -conditional dependency `when` predicates evaluate against this getter.\n *\n * While attached, returns the already-merged {@link config}; otherwise\n * recomputes `defaultConfig` + `userConfig` fresh. `config` is intentionally\n * **not** trusted when detached because {@link detach} does not clear it — a\n * re-validated plugin would otherwise see stale config from a prior\n * attachment. The {@link attach}-managed abort controller is the\n * attached/detached signal.\n * @internal Plugin infrastructure (used by `validatePluginDependencies`).\n */\n get resolvedConfig(): TConfig {\n return (this.#abortController ? this.config : { ...this.defaultConfig, ...this.userConfig }) as TConfig;\n }\n\n /**\n * Merge user-supplied configuration from other plugin instances into this\n * plugin's `userConfig`. Used by `PluginManager.attachAll()`'s alias-collapse\n * pre-pass: when a consumer instantiates the same plugin more than once (or\n * under an alias name), only one instance is attached, and the other\n * instances' configs are folded in via this method.\n *\n * Merge rules (shallow):\n *\n * - Same key, **same value** → silent.\n * - Same key, **different values** (incl. function vs function) → throws\n * a diagnostic naming the conflicting key. Conflicting callbacks\n * (`canDrag`, `canDrop`, etc.) cannot be reconciled automatically.\n * - **Disjoint keys** → merged cleanly.\n *\n * Subclasses may override to implement custom deep-merge logic, but should\n * call `super.mergeConfigsFrom(others)` to inherit the conflict-detection.\n *\n * @internal Plugin infrastructure (used by `PluginManager.attachAll`).\n * @throws Error with diagnostic code `TBW025` when configs conflict.\n */\n mergeConfigsFrom(others: readonly BaseGridPlugin<TConfig>[]): void {\n if (others.length === 0) return;\n const merged = { ...this.userConfig } as Record<string, unknown>;\n const sources: Record<string, BaseGridPlugin<TConfig>> = {};\n for (const key of Object.keys(merged)) sources[key] = this;\n for (const other of others) {\n const otherConfig = other.userConfig as Record<string, unknown>;\n for (const [key, value] of Object.entries(otherConfig)) {\n if (value === undefined) continue;\n if (!(key in merged)) {\n merged[key] = value;\n sources[key] = other;\n continue;\n }\n if (merged[key] === value) continue;\n // Conflict\n const ownerA = sources[key]?.constructor.name ?? this.constructor.name;\n const ownerB = other.constructor.name;\n const code = formatDiagnostic(\n PLUGIN_ALIAS_CONFIG_CONFLICT,\n `Cannot merge plugin configs for \"${this.name}\": conflicting value for \"${key}\" supplied by both ${ownerA} and ${ownerB}. Pass the option on a single instance, or remove the duplicate.`,\n undefined,\n this.name,\n );\n throw new Error(code);\n }\n }\n // Mutate userConfig in place so re-attach picks it up via attach().\n // `userConfig` is declared `readonly` to prevent reassigning the binding,\n // but the object's own properties are intentionally mutable for this\n // alias-collapse pre-pass. A single cast to a record is enough — no\n // `as unknown as` double-cast needed.\n Object.assign(this.userConfig as Record<string, unknown>, merged);\n }\n\n /**\n * Replace this plugin's `userConfig` with a freshly-resolved sibling\n * instance's config. Used by the grid's per-grid feature-instance gate\n * (`#initializePlugins`): when a feature is re-resolved across a config\n * change, the **existing** instance is reused — so its accumulated state\n * survives — but it must adopt the latest `gridConfig.features.<name>`\n * value. Unlike {@link mergeConfigsFrom}, this is last-write-wins with no\n * conflict detection: the re-resolved instance is authoritative.\n *\n * `attach()` recomputes {@link config} from `userConfig`, so updating\n * `userConfig` here is enough for the reused instance to pick up the new\n * config on its next attach during the same `#initializePlugins` pass.\n *\n * @internal Plugin infrastructure (used by the grid feature gate).\n */\n refreshUserConfigFrom(other: BaseGridPlugin<TConfig>): void {\n const target = this.userConfig as Record<string, unknown>;\n // Snapshot the source BEFORE clearing `target`. A feature factory may\n // store the consumer's config object by reference (e.g. `new\n // ContextMenuPlugin(config)`), and a consumer that passes the *same* config\n // object across re-resolutions (common when `gridConfig` is a recomputed\n // Angular `computed()`) makes `this.userConfig === other.userConfig`.\n // Without this snapshot, the `delete` loop below would empty that shared\n // object first, then `Object.assign` would copy back nothing — silently\n // wiping the config and falling back to plugin defaults. (#contextMenu)\n const source = { ...(other.userConfig as Record<string, unknown>) };\n for (const key of Object.keys(target)) delete target[key];\n Object.assign(target, source);\n }\n\n /**\n * Called when the plugin is attached to a grid.\n * Override to set up event listeners, initialize state, etc.\n *\n * @example\n * ```ts\n * attach(grid: GridElement): void {\n * super.attach(grid);\n * // Set up document-level listeners with auto-cleanup\n * document.addEventListener('keydown', this.handleEscape, {\n * signal: this.disconnectSignal\n * });\n * }\n * ```\n */\n attach(grid: GridElement): void {\n // Abort any previous abort controller (in case of re-attach without detach)\n this.#abortController?.abort();\n // Create fresh abort controller for this attachment\n this.#abortController = new AbortController();\n\n this.grid = grid;\n // Merge config here (after subclass construction is complete)\n this.config = { ...this.defaultConfig, ...this.userConfig } as TConfig;\n }\n\n /**\n * Called when the plugin is detached from a grid.\n * Override to clean up event listeners, timers, etc.\n *\n * @example\n * ```ts\n * detach(): void {\n * // Clean up any state not handled by disconnectSignal\n * this.selectedRows.clear();\n * this.cache = null;\n * }\n * ```\n */\n detach(): void {\n // Abort the plugin's abort controller to clean up all event listeners\n // registered with { signal: this.disconnectSignal }\n this.#abortController?.abort();\n this.#abortController = undefined;\n // Override in subclass for additional cleanup\n }\n\n /**\n * Called when another plugin is attached to the same grid.\n * Use for inter-plugin coordination, e.g., to integrate with new plugins.\n *\n * @param name - The name of the plugin that was attached\n * @param plugin - The plugin instance (for direct access if needed)\n *\n * @example\n * ```ts\n * onPluginAttached(name: string, plugin: BaseGridPlugin): void {\n * if (name === 'selection') {\n * // Integrate with selection plugin\n * this.selectionPlugin = plugin as SelectionPlugin;\n * }\n * }\n * ```\n */\n onPluginAttached?(name: string, plugin: BaseGridPlugin): void;\n\n /**\n * Called when another plugin is detached from the same grid.\n * Use to clean up inter-plugin references.\n *\n * @param name - The name of the plugin that was detached\n *\n * @example\n * ```ts\n * onPluginDetached(name: string): void {\n * if (name === 'selection') {\n * this.selectionPlugin = undefined;\n * }\n * }\n * ```\n */\n onPluginDetached?(name: string): void;\n\n /**\n * Get another plugin instance from the same grid.\n * Use for inter-plugin communication.\n *\n * **Prefer {@link BaseGridPlugin.grid grid.getPluginByName()}** when you don't need the class import.\n *\n * @example\n * ```ts\n * // Preferred: by name\n * const selection = this.grid?.getPluginByName('selection');\n *\n * // Alternative: by class\n * const selection = this.getPlugin(SelectionPlugin);\n * if (selection) {\n * const selectedRows = selection.getSelectedRows();\n * }\n * ```\n */\n protected getPlugin<T extends BaseGridPlugin>(PluginClass: new (...args: any[]) => T): T | undefined {\n return this.grid?.getPlugin(PluginClass);\n }\n\n /**\n * Emit a custom event from the grid.\n */\n protected emit<T>(eventName: string, detail: T): void {\n this.grid?.dispatchEvent?.(new CustomEvent(eventName, { detail, bubbles: true }));\n }\n\n /**\n * Emit a cancelable custom event from the grid.\n * @returns `true` if the event was cancelled (preventDefault called), `false` otherwise\n */\n protected emitCancelable<T>(eventName: string, detail: T): boolean {\n const event = new CustomEvent(eventName, { detail, bubbles: true, cancelable: true });\n this.grid?.dispatchEvent?.(event);\n return event.defaultPrevented;\n }\n\n // =========================================================================\n // Event Bus - Plugin-to-Plugin Communication\n // =========================================================================\n\n /**\n * Subscribe to an event from another plugin.\n * The subscription is automatically cleaned up when this plugin is detached.\n *\n * @category Plugin Development\n * @param eventType - The event type to listen for (e.g., 'filter-change')\n * @param callback - The callback to invoke when the event is emitted\n *\n * @example\n * ```typescript\n * // In attach() or other initialization\n * this.on('filter-change', (detail) => {\n * console.log('Filter changed:', detail);\n * });\n * ```\n */\n protected on<T = unknown>(eventType: string, callback: (detail: T) => void): void {\n this.grid?._pluginManager?.subscribe(this, eventType, callback as (detail: unknown) => void);\n }\n\n /**\n * Unsubscribe from a plugin event.\n *\n * @category Plugin Development\n * @param eventType - The event type to stop listening for\n *\n * @example\n * ```typescript\n * this.off('filter-change');\n * ```\n */\n protected off(eventType: string): void {\n this.grid?._pluginManager?.unsubscribe(this, eventType);\n }\n\n /**\n * Emit an event to other plugins via the Event Bus.\n * This is for inter-plugin communication only; it does NOT dispatch DOM events.\n * Use `emit()` to dispatch DOM events that external consumers can listen to.\n *\n * @category Plugin Development\n * @param eventType - The event type to emit (should be declared in manifest.events)\n * @param detail - The event payload\n *\n * @example\n * ```typescript\n * // Emit to other plugins (not DOM)\n * this.emitPluginEvent('filter-change', { field: 'name', value: 'Alice' });\n *\n * // For DOM events that consumers can addEventListener to:\n * this.emit('filter-change', { field: 'name', value: 'Alice' });\n * ```\n */\n protected emitPluginEvent<T>(eventType: string, detail: T): void {\n this.grid?._pluginManager?.emitPluginEvent(eventType, detail);\n }\n\n /**\n * Emit an event to **both** the plugin Event Bus (for inter-plugin communication)\n * **and** the DOM (for external consumers via `addEventListener`).\n *\n * Use this when a state change is relevant to both other plugins and external\n * consumers. For example, `sort-change` needs to invalidate Selection (plugin bus)\n * and notify the host application (DOM event).\n *\n * @category Plugin Development\n * @param eventType - The event type to broadcast\n * @param detail - The event payload\n *\n * @example\n * ```typescript\n * // Notify both plugins and consumers of a sort change\n * this.broadcast('sort-change', { sortModel: [...this.sortModel] });\n * ```\n */\n protected broadcast<T>(eventType: string, detail: T): void {\n this.emitPluginEvent(eventType, detail);\n this.emit(eventType, detail);\n }\n\n /**\n * Run a yes/no plugin query and reduce the responses to a single boolean.\n *\n * `grid.query()` always returns an **array** of responses (empty when no\n * plugin handles the query), and `[]` is truthy in JavaScript — so testing\n * the raw result directly (`if (grid.query(...))`) is always `true` and\n * silently takes the \"some plugin said yes\" branch even when nothing\n * answered. Always route boolean queries through this helper.\n *\n * @category Plugin Development\n * @param type - The query type to dispatch\n * @param context - Optional query context passed to the handlers\n * @returns `true` only when at least one plugin answered truthily\n *\n * @example\n * ```typescript\n * if (this.queryBoolean('datasource:is-active')) {\n * // A ServerSide data source really is installed\n * }\n * ```\n * @since 3.4.0\n */\n protected queryBoolean(type: string, context: unknown = null): boolean {\n const responses = this.grid?.query?.(type, context);\n // Tolerate hosts/tests that hand back a bare value instead of the array.\n return Array.isArray(responses) ? responses.some(Boolean) : !!responses;\n }\n\n /**\n * Request a re-render of the grid.\n * Uses ROWS phase - does NOT trigger processColumns hooks.\n */\n protected requestRender(): void {\n this.grid?.requestRender?.();\n }\n\n /**\n * Request a columns re-render of the grid.\n * Uses COLUMNS phase - triggers processColumns hooks.\n * Use this when your plugin needs to reprocess column configuration.\n */\n protected requestColumnsRender(): void {\n (this.grid as { requestColumnsRender?: () => void })?.requestColumnsRender?.();\n }\n\n /**\n * Request a re-render and restore focus styling afterward.\n * Use this when a plugin action (like expand/collapse) triggers a render\n * but needs to maintain keyboard navigation focus.\n */\n protected requestRenderWithFocus(): void {\n this.grid?.requestRenderWithFocus?.();\n }\n\n /**\n * Request a lightweight style update without rebuilding DOM.\n * Use this instead of requestRender() when only CSS classes need updating.\n */\n protected requestAfterRender(): void {\n this.grid?.requestAfterRender?.();\n }\n\n /**\n * Re-render visible rows without rebuilding the row model or recalculating geometry.\n * Use this when row data has been updated in-place (e.g., server-side block loads)\n * and only the visible viewport needs to re-render.\n */\n protected requestVirtualRefresh(): void {\n this.grid?.requestVirtualRefresh?.();\n }\n\n /**\n * Get the current rows from the grid.\n */\n protected get rows(): any[] {\n return this.grid?.rows ?? [];\n }\n\n /**\n * Get the original unfiltered/unprocessed rows from the grid.\n * Use this when you need all source data regardless of active filters.\n */\n protected get sourceRows(): any[] {\n return this.grid?.sourceRows ?? [];\n }\n\n /**\n * Get the current columns from the grid.\n */\n protected get columns(): ColumnConfig[] {\n return this.grid?.columns ?? [];\n }\n\n /**\n * Get only visible columns from the grid (excludes hidden).\n * Use this for rendering that needs to match the grid template.\n */\n protected get visibleColumns(): ColumnConfig[] {\n return this.grid?._visibleColumns ?? [];\n }\n\n /**\n * Get the grid as an HTMLElement for direct DOM operations.\n * Use sparingly - prefer the typed GridElementRef API when possible.\n *\n * @example\n * ```ts\n * const width = this.gridElement.clientWidth;\n * this.gridElement.classList.add('my-plugin-active');\n * ```\n */\n protected get gridElement(): HTMLElement {\n return this.grid?._hostElement;\n }\n\n /**\n * Get the disconnect signal for event listener cleanup.\n * This signal is aborted when the grid disconnects from the DOM.\n * Use this when adding event listeners that should be cleaned up automatically.\n *\n * Best for:\n * - Document/window-level listeners added in attach()\n * - Listeners on the grid element itself\n * - Any listener that should persist across renders\n *\n * Not needed for:\n * - Listeners on elements created in afterRender() (removed with element)\n *\n * @example\n * element.addEventListener('click', handler, { signal: this.disconnectSignal });\n * document.addEventListener('keydown', handler, { signal: this.disconnectSignal });\n */\n protected get disconnectSignal(): AbortSignal {\n // Return the plugin's own abort signal for proper cleanup on detach/re-attach\n // Falls back to grid's signal if plugin's controller not yet created\n return this.#abortController?.signal ?? this.grid?.disconnectSignal;\n }\n\n /**\n * Get the grid-level icons configuration.\n * Returns merged icons (user config + defaults).\n */\n protected get gridIcons(): Required<GridIcons> {\n const userIcons = this.grid?.gridConfig?.icons ?? {};\n return { ...DEFAULT_GRID_ICONS, ...userIcons };\n }\n\n /**\n * Resolve a user-visible string from {@link GridConfig.locale}, falling back to\n * the English default supplied at the call site.\n *\n * The fallback is passed inline rather than read from a shipped default map so\n * that a plugin's strings live in the plugin's own chunk.\n *\n * @param key - Namespaced message id, e.g. `'filter.apply'`.\n * @param fallback - English text used when the key is not overridden.\n * @since 3.5.0\n *\n * @example\n * ```ts\n * applyBtn.textContent = this.t('filter.apply', 'Apply');\n * ```\n */\n protected t(key: string, fallback: string): string {\n return this.grid?.effectiveConfig?.locale?.[key] ?? fallback;\n }\n\n /**\n * A bound `t()` suitable for handing to standalone renderer\n * helpers and public renderer callbacks.\n * @since 3.5.0\n */\n protected get translate(): Translate {\n return (key, fallback) => this.t(key, fallback);\n }\n\n // #region Animation Helpers\n\n /**\n * Check if animations are enabled at the grid level.\n * Respects gridConfig.animation.mode and the CSS variable set by the grid.\n *\n * Plugins should use this to skip animations when:\n * - Animation mode is 'off' or `false`\n * - User prefers reduced motion and mode is 'reduced-motion' (default)\n *\n * @example\n * ```ts\n * private get animationStyle(): 'slide' | 'fade' | false {\n * if (!this.isAnimationEnabled) return false;\n * return this.config.animation ?? 'slide';\n * }\n * ```\n */\n protected get isAnimationEnabled(): boolean {\n const mode = this.grid?.effectiveConfig?.animation?.mode ?? 'reduced-motion';\n\n // Explicit off = disabled\n if (mode === false || mode === 'off') return false;\n\n // Explicit on = always enabled\n if (mode === true || mode === 'on') return true;\n\n // reduced-motion: check CSS variable (set by grid based on media query)\n const host = this.gridElement;\n if (host) {\n const enabled = getComputedStyle(host).getPropertyValue('--tbw-animation-enabled').trim();\n return enabled !== '0';\n }\n\n return true; // Default to enabled\n }\n\n /**\n * Get the animation duration in milliseconds from CSS variable.\n * Falls back to 200ms if not set.\n *\n * Plugins can use this for their animation timing to stay consistent\n * with the grid-level animation.duration setting.\n *\n * @example\n * ```ts\n * element.animate(keyframes, { duration: this.animationDuration });\n * ```\n */\n protected get animationDuration(): number {\n const host = this.gridElement;\n if (host) {\n const durationStr = getComputedStyle(host).getPropertyValue('--tbw-animation-duration').trim();\n const parsed = parseInt(durationStr, 10);\n if (!isNaN(parsed)) return parsed;\n }\n return 200; // Default\n }\n\n // #endregion\n\n /**\n * Set an icon on an element using the CSS-first hybrid approach.\n *\n * Sets `data-icon` for CSS pseudo-element rendering and `data-expanded` for\n * expand/collapse toggle elements. Only injects DOM content when a JS override\n * is present (via `gridConfig.icons` or `pluginOverride`), which naturally\n * suppresses the CSS `::before` via the `:empty` selector.\n *\n * @param element - The element to set the icon on\n * @param iconKey - The icon key in GridIcons (e.g., 'expand', 'collapse')\n * @param pluginOverride - Optional plugin-level override (string or HTMLElement)\n */\n protected setIcon(element: HTMLElement, iconKey: keyof GridIcons, pluginOverride?: IconValue): void {\n // Set data-icon attribute for CSS targeting (always)\n element.dataset.icon = toIconAttr(iconKey);\n\n // Set data-expanded for toggle elements (tree, group, master-detail)\n if (iconKey === 'collapse') {\n element.dataset.expanded = '';\n } else if (iconKey === 'expand') {\n delete element.dataset.expanded;\n }\n\n // Resolve JS-only icon (returns undefined when CSS default should be used)\n const jsIcon = this.#resolveJsIcon(iconKey, pluginOverride);\n\n if (jsIcon !== undefined) {\n // JS override: inject content (suppresses CSS ::before via :empty)\n if (typeof jsIcon === 'string') {\n setSanitizedHTML(element, jsIcon);\n } else if (jsIcon instanceof HTMLElement) {\n element.replaceChildren(jsIcon.cloneNode(true));\n }\n } else {\n // CSS path: ensure element is empty so ::before renders\n element.innerHTML = '';\n }\n }\n\n /**\n * Resolve JS-only icon override. Returns undefined if CSS default should render.\n * Only returns a value when the user explicitly set gridConfig.icons[key] or\n * the plugin passed an override.\n */\n #resolveJsIcon(iconKey: keyof GridIcons, pluginOverride?: IconValue): IconValue | undefined {\n if (pluginOverride !== undefined) return pluginOverride;\n return this.grid?.gridConfig?.icons?.[iconKey];\n }\n\n /**\n * Create or replace a sort indicator on a header cell.\n *\n * Handles the full lifecycle: removes any existing indicator, creates a new\n * `<span part=\"sort-indicator\" class=\"sort-indicator\">` with the appropriate\n * icon, sets `aria-sort` / `data-sort` attributes, and inserts it before the\n * filter button or resize handle.\n *\n * Plugins decide **which** cells and **when** — this method handles **how**.\n *\n * @param cell - The header cell element\n * @param direction - `'asc'` | `'desc'` for sorted, `null` for unsorted idle state\n * @returns The created indicator element (useful for appending badges, etc.)\n */\n protected updateSortIndicator(cell: Element, direction: 'asc' | 'desc' | null): HTMLElement {\n // Remove any existing indicator (core uses part, plugins use class)\n cell.querySelector('[part~=\"sort-indicator\"], .sort-indicator')?.remove();\n\n const indicator = document.createElement('span');\n indicator.setAttribute('part', 'sort-indicator');\n indicator.className = 'sort-indicator';\n\n if (direction) {\n cell.setAttribute('aria-sort', direction === 'asc' ? 'ascending' : 'descending');\n cell.setAttribute('data-sort', direction);\n this.setIcon(indicator, direction === 'asc' ? 'sortAsc' : 'sortDesc');\n } else {\n cell.setAttribute('aria-sort', 'none');\n cell.removeAttribute('data-sort');\n this.setIcon(indicator, 'sortNone');\n }\n\n // Insert before filter button or resize handle to maintain DOM order\n const insertBefore = cell.querySelector('.tbw-filter-btn') ?? cell.querySelector('.resize-handle');\n if (insertBefore) {\n cell.insertBefore(indicator, insertBefore);\n } else {\n cell.appendChild(indicator);\n }\n\n return indicator;\n }\n\n /**\n * Log a warning with an optional diagnostic code.\n *\n * When a diagnostic code is provided, the message is formatted with the code\n * and a link to the troubleshooting docs.\n *\n * @example\n * ```ts\n * this.warn('Something went wrong'); // plain\n * this.warn(MISSING_BREAKPOINT, 'Set a breakpoint'); // with code + docs link\n * ```\n */\n protected warn(message: string): void;\n protected warn(code: DiagnosticCode, message: string): void;\n protected warn(codeOrMessage: DiagnosticCode | string, message?: string): void {\n if (message !== undefined) {\n // Called with (code, message)\n console.warn(formatDiagnostic(codeOrMessage as DiagnosticCode, message, this.gridElement.id, this.name));\n } else {\n // Called with (message) — plain warning, no diagnostic code\n console.warn(`${gridPrefix(this.gridElement.id, this.name)} ${codeOrMessage}`);\n }\n }\n\n /**\n * Throw an error with a diagnostic code and docs link.\n * Use for configuration errors and API misuse that should halt execution.\n */\n protected throwDiagnostic(code: DiagnosticCode, message: string): never {\n throw new Error(formatDiagnostic(code, message, this.gridElement.id, this.name));\n }\n\n // #region Lifecycle Hooks\n\n /**\n * Transform rows before rendering.\n * Called during each render cycle before rows are rendered to the DOM.\n * Use this to filter, sort, or add computed properties to rows.\n *\n * @param rows - The current rows array (readonly to encourage returning a new array)\n * @returns The modified rows array to render\n *\n * @example\n * ```ts\n * processRows(rows: readonly any[]): any[] {\n * // Filter out hidden rows\n * return rows.filter(row => !row._hidden);\n * }\n * ```\n *\n * @example\n * ```ts\n * processRows(rows: readonly any[]): any[] {\n * // Add computed properties\n * return rows.map(row => ({\n * ...row,\n * _fullName: `${row.firstName} ${row.lastName}`\n * }));\n * }\n * ```\n */\n processRows?(rows: readonly any[]): any[];\n\n /**\n * Contribute to the grid's effective configuration during each config merge.\n * Called by {@link ConfigManager.merge} after the base config is assembled,\n * before it becomes `effectiveConfig`. Mutate `config` in place to inject\n * plugin-derived settings (e.g. the shell plugin folds its light-DOM /\n * API-registered state into `config.shell`).\n *\n * This is the config-pipeline counterpart to {@link processColumns} /\n * {@link processRows}: it keeps the core config merge free of any plugin\n * knowledge — each plugin owns the shape it contributes.\n *\n * @param config - The mutable base config being assembled into effectiveConfig.\n *\n * @example\n * ```ts\n * processConfig(config: GridConfig): void {\n * config.shell = { ...config.shell, header: { title: this.#title } };\n * }\n * ```\n */\n processConfig?(config: GridConfig): void;\n\n /**\n * Transform columns before rendering.\n * Called during each render cycle before column headers and cells are rendered.\n * Use this to add, remove, or modify column definitions.\n *\n * @param columns - The current columns array (readonly to encourage returning a new array)\n * @returns The modified columns array to render\n *\n * @example\n * ```ts\n * processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n * // Add a selection checkbox column\n * return [\n * { field: '_select', header: '', width: 40 },\n * ...columns\n * ];\n * }\n * ```\n */\n processColumns?(columns: readonly ColumnConfig[]): ColumnConfig[];\n\n /**\n * Called before each render cycle begins.\n * Use this to prepare state or cache values needed during rendering.\n *\n * **Note:** This hook is currently a placeholder for future implementation.\n * It is defined in the interface but not yet invoked by the grid's render pipeline.\n * If you need this functionality, please open an issue or contribute an implementation.\n *\n * @example\n * ```ts\n * beforeRender(): void {\n * this.visibleRowCount = this.calculateVisibleRows();\n * }\n * ```\n */\n beforeRender?(): void;\n\n /**\n * Called after each render cycle completes.\n * Use this for DOM manipulation, adding event listeners to rendered elements,\n * or applying visual effects like selection highlights.\n *\n * @example\n * ```ts\n * afterRender(): void {\n * // Apply selection styling to rendered rows\n * const rows = this.gridElement?.querySelectorAll('.data-grid-row');\n * rows?.forEach((row, i) => {\n * row.classList.toggle('selected', this.selectedRows.has(i));\n * });\n * }\n * ```\n */\n afterRender?(): void;\n\n /**\n * Called synchronously immediately after the grid (re)builds its root DOM\n * structure, before the browser has a chance to paint.\n *\n * Unlike {@link afterRender} (which runs in the scheduler's STYLE phase and\n * may be deferred), this hook fires inside the same task as the structural\n * DOM build. It is the correct place for plugins that need to wrap, relocate,\n * or augment the freshly built grid DOM without a flash of unstyled/unwrapped\n * content — e.g. a shell that moves the grid content into a chrome wrapper.\n *\n * The grid emits this hook every time it performs a full structural rebuild\n * (initial connect and structural changes), but NOT on the scroll/data hot\n * path. Implementations MUST be idempotent: a full rebuild discards any DOM a\n * previous invocation produced, so re-create it, and no-op when the desired\n * structure is already present.\n *\n * @example\n * ```ts\n * afterStructuralRender(): void {\n * const root = this.grid?._renderRoot;\n * if (!root || root.querySelector('.my-wrapper > .tbw-grid-content')) return;\n * // build wrapper, move .tbw-grid-content inside it\n * }\n * ```\n */\n afterStructuralRender?(): void;\n\n /**\n * Called synchronously by the grid immediately before it tears down and\n * rebuilds its root DOM structure (a structural re-render). Plugins that\n * relocated existing light-DOM nodes into their own chrome (e.g. a shell that\n * moves toolbar buttons into the header bar) use this to move those nodes back\n * to their original container so they survive the rebuild. Generic\n * counterpart to {@link afterStructuralRender}. MUST be idempotent.\n */\n beforeStructuralRender?(): void;\n\n /**\n * Called by the grid after a config merge to ask whether the change requires a\n * full structural re-render (rather than a cheaper in-place update). A plugin\n * returns `true` when its rendered DOM signature no longer matches the new\n * effective config — e.g. a shell header appearing/disappearing or a tool\n * panel's count/position/mode changing. The grid performs a structural\n * re-render if ANY plugin returns `true`. MUST be side-effect free.\n */\n needsStructuralRerender?(): boolean;\n\n /**\n * Called by the grid to let a plugin (re-)parse its own light-DOM\n * contributions into plugin state ahead of a config merge. Generic seam that\n * keeps core free of plugin-specific light-DOM tag knowledge (the plugin reads\n * `this.grid._hostElement`). MUST be idempotent.\n */\n parseLightDom?(): void;\n\n /**\n * Called by the grid (from `refreshColumns` and the light-DOM observer) to\n * let a plugin re-parse its light-DOM contributions AND refresh any\n * already-rendered chrome in place when something changed — e.g. a shell\n * title or tool buttons that a framework projected asynchronously after the\n * initial render. Distinct from {@link parseLightDom}, which only updates\n * plugin state. Generic seam — core holds no plugin-specific knowledge. MUST\n * be idempotent and a no-op when the plugin's chrome is not yet rendered.\n */\n syncLightDom?(): void;\n\n /**\n * Called after each cell is rendered.\n * This hook is more efficient than `afterRender()` for cell-level modifications\n * because you receive the cell context directly - no DOM queries needed.\n *\n * Use cases:\n * - Adding selection/highlight classes to specific cells\n * - Injecting badges or decorations\n * - Applying conditional styling based on cell value\n *\n * Performance note: Called for every visible cell during render. Keep implementation fast.\n * This hook is also called during scroll when cells are recycled.\n *\n * @param context - The cell render context with row, column, value, and elements\n *\n * @example\n * ```ts\n * afterCellRender(context: AfterCellRenderContext): void {\n * // Add selection class without DOM queries\n * if (this.isSelected(context.rowIndex, context.colIndex)) {\n * context.cellElement.classList.add('selected');\n * }\n *\n * // Add validation error styling\n * if (this.hasError(context.row, context.column.field)) {\n * context.cellElement.classList.add('has-error');\n * }\n * }\n * ```\n */\n afterCellRender?(context: AfterCellRenderContext): void;\n\n /**\n * Called after a row is fully rendered (all cells complete).\n * Use this for row-level decorations, styling, or ARIA attributes.\n *\n * Common use cases:\n * - Adding selection classes to entire rows (row-focus, selected)\n * - Setting row-level ARIA attributes\n * - Applying row validation highlighting\n * - Tree indentation styling\n *\n * Performance note: Called for every visible row during render. Keep implementation fast.\n * This hook is also called during scroll when rows are recycled.\n *\n * @param context - The row render context with row data and element\n *\n * @example\n * ```ts\n * afterRowRender(context: AfterRowRenderContext): void {\n * // Add row selection class without DOM queries\n * if (this.isRowSelected(context.rowIndex)) {\n * context.rowElement.classList.add('selected', 'row-focus');\n * }\n *\n * // Add validation error styling\n * if (this.rowHasErrors(context.row)) {\n * context.rowElement.classList.add('has-errors');\n * }\n * }\n * ```\n */\n afterRowRender?(context: AfterRowRenderContext): void;\n\n /**\n * Called after scroll-triggered row rendering completes.\n * This is a lightweight hook for applying visual state to recycled DOM elements.\n * Use this instead of afterRender when you need to reapply styling during scroll.\n *\n * Performance note: This is called frequently during scroll. Keep implementation fast.\n *\n * @example\n * ```ts\n * onScrollRender(): void {\n * // Reapply selection state to visible cells\n * this.applySelectionToVisibleCells();\n * }\n * ```\n */\n onScrollRender?(): void;\n\n /**\n * Get the height of a specific row.\n * Used for synthetic rows (group headers, detail panels, etc.) that have fixed heights.\n * Return undefined if this plugin does not manage the height for this row.\n *\n * This hook is called during position cache rebuilds for variable row height virtualization.\n * Plugins that create synthetic rows should implement this to provide accurate heights.\n *\n * @param row - The row data\n * @param index - The row index in the processed rows array\n * @returns The row height in pixels, or undefined if not managed by this plugin\n */\n getRowHeight?(row: unknown, index: number): number | undefined;\n\n /**\n * Adjust the virtualization start index to render additional rows before the visible range.\n * Use this when expanded content (like detail rows) needs its parent row to remain rendered\n * even when the parent row itself has scrolled above the viewport.\n *\n * @param start - The calculated start row index\n * @param scrollTop - The current scroll position\n * @param rowHeight - The height of a single row\n * @returns The adjusted start index (lower than or equal to original start)\n *\n * @example\n * ```ts\n * adjustVirtualStart(start: number, scrollTop: number, rowHeight: number): number {\n * // If row 5 is expanded and scrolled partially, keep it rendered\n * for (const expandedRowIndex of this.expandedRowIndices) {\n * const expandedRowTop = expandedRowIndex * rowHeight;\n * const expandedRowBottom = expandedRowTop + rowHeight + this.detailHeight;\n * if (expandedRowBottom > scrollTop && expandedRowIndex < start) {\n * return expandedRowIndex;\n * }\n * }\n * return start;\n * }\n * ```\n */\n adjustVirtualStart?(start: number, scrollTop: number, rowHeight: number): number;\n\n /**\n * Render a custom row, bypassing the default row rendering.\n * Use this for special row types like group headers, detail rows, or footers.\n *\n * @param row - The row data object\n * @param rowEl - The row DOM element to render into\n * @param rowIndex - The index of the row in the data array\n * @returns `true` if the plugin handled rendering (prevents default), `false`/`void` for default rendering\n *\n * @example\n * ```ts\n * renderRow(row: any, rowEl: HTMLElement, rowIndex: number): boolean | void {\n * if (row._isGroupHeader) {\n * rowEl.innerHTML = `<div class=\"group-header\">${row._groupLabel}</div>`;\n * return true; // Handled - skip default rendering\n * }\n * // Return void to let default rendering proceed\n * }\n * ```\n */\n renderRow?(row: any, rowEl: HTMLElement, rowIndex: number): boolean | void;\n\n // #endregion\n\n // #region Inter-Plugin Communication\n\n /**\n * Handle queries from other plugins or the grid.\n *\n * Queries are declared in `manifest.queries` and dispatched via `grid.query()`.\n * This enables type-safe, discoverable inter-plugin communication.\n *\n * @category Plugin Development\n * @param query - The query object with type and context\n * @returns Query-specific response, or undefined if not handling this query\n *\n * @example\n * ```ts\n * // In manifest\n * static override readonly manifest: PluginManifest = {\n * queries: [\n * { type: 'canMoveColumn', description: 'Check if a column can be moved' },\n * ],\n * };\n *\n * // In plugin class\n * handleQuery(query: PluginQuery): unknown {\n * if (query.type === 'canMoveColumn') {\n * const column = query.context as ColumnConfig;\n * return !column.sticky; // Can't move sticky columns\n * }\n * }\n * ```\n */\n handleQuery?(query: PluginQuery): unknown;\n\n // #endregion\n\n // #region Interaction Hooks\n\n /**\n * Handle keyboard events on the grid.\n * Called when a key is pressed while the grid or a cell has focus.\n *\n * @param event - The native KeyboardEvent\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onKeyDown(event: KeyboardEvent): boolean | void {\n * // Handle Ctrl+A for select all\n * if (event.ctrlKey && event.key === 'a') {\n * this.selectAllRows();\n * return true; // Prevent default browser select-all\n * }\n * }\n * ```\n */\n onKeyDown?(event: KeyboardEvent): boolean | void;\n\n /**\n * Handle cell click events.\n * Called when a data cell is clicked (not headers).\n *\n * @param event - Cell click event with row/column context\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onCellClick(event: CellClickEvent): boolean | void {\n * if (event.field === '_select') {\n * this.toggleRowSelection(event.rowIndex);\n * return true; // Handled\n * }\n * }\n * ```\n */\n onCellClick?(event: CellClickEvent): boolean | void;\n\n /**\n * Handle row click events.\n * Called when any part of a data row is clicked.\n * Note: This is called in addition to onCellClick, not instead of.\n *\n * @param event - Row click event with row context\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onRowClick(event: RowClickEvent): boolean | void {\n * if (this.config.mode === 'row') {\n * this.selectRow(event.rowIndex, event.originalEvent);\n * return true;\n * }\n * }\n * ```\n */\n onRowClick?(event: RowClickEvent): boolean | void;\n\n /**\n * Handle header click events.\n * Called when a column header is clicked. Commonly used for sorting.\n *\n * @param event - Header click event with column context\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onHeaderClick(event: HeaderClickEvent): boolean | void {\n * if (event.column.sortable !== false) {\n * this.toggleSort(event.field);\n * return true;\n * }\n * }\n * ```\n */\n onHeaderClick?(event: HeaderClickEvent): boolean | void;\n\n /**\n * Handle scroll events on the grid viewport.\n * Called during scrolling. Note: This may be called frequently; debounce if needed.\n *\n * @param event - Scroll event with scroll position and viewport dimensions\n *\n * @example\n * ```ts\n * onScroll(event: ScrollEvent): void {\n * // Update sticky column positions\n * this.updateStickyPositions(event.scrollLeft);\n * }\n * ```\n */\n onScroll?(event: ScrollEvent): void;\n\n /**\n * Handle cell mousedown events.\n * Used for initiating drag operations like range selection or column resize.\n *\n * @param event - Mouse event with cell context\n * @returns `true` to indicate drag started (prevents text selection), `false`/`void` otherwise\n *\n * @example\n * ```ts\n * onCellMouseDown(event: CellMouseEvent): boolean | void {\n * if (event.rowIndex !== undefined && this.config.mode === 'range') {\n * this.startDragSelection(event.rowIndex, event.colIndex);\n * return true; // Prevent text selection\n * }\n * }\n * ```\n */\n onCellMouseDown?(event: CellMouseEvent): boolean | void;\n\n /**\n * Handle cell mousemove events during drag operations.\n * Only called when a drag is in progress (after mousedown returned true).\n *\n * @param event - Mouse event with current cell context\n * @returns `true` to continue handling the drag, `false`/`void` otherwise\n *\n * @example\n * ```ts\n * onCellMouseMove(event: CellMouseEvent): boolean | void {\n * if (this.isDragging && event.rowIndex !== undefined) {\n * this.extendSelection(event.rowIndex, event.colIndex);\n * return true;\n * }\n * }\n * ```\n */\n onCellMouseMove?(event: CellMouseEvent): boolean | void;\n\n /**\n * Handle cell mouseup events to end drag operations.\n *\n * @param event - Mouse event with final cell context\n * @returns `true` if drag was finalized, `false`/`void` otherwise\n *\n * @example\n * ```ts\n * onCellMouseUp(event: CellMouseEvent): boolean | void {\n * if (this.isDragging) {\n * this.finalizeDragSelection();\n * this.isDragging = false;\n * return true;\n * }\n * }\n * ```\n */\n onCellMouseUp?(event: CellMouseEvent): boolean | void;\n\n // Note: Context menu items are provided via handleQuery('getContextMenuItems').\n // This keeps the core decoupled from the context-menu plugin specifics.\n\n // #endregion\n\n // #region Column State Hooks\n\n /**\n * Contribute plugin-specific state for a column.\n * Called by the grid when collecting column state for serialization.\n * Plugins can add their own properties to the column state.\n *\n * @param field - The field name of the column\n * @returns Partial column state with plugin-specific properties, or undefined if no state to contribute\n *\n * @example\n * ```ts\n * getColumnState(field: string): Partial<ColumnState> | undefined {\n * const filterModel = this.filterModels.get(field);\n * if (filterModel) {\n * // Uses module augmentation to add filter property to ColumnState\n * return { filter: filterModel } as Partial<ColumnState>;\n * }\n * return undefined;\n * }\n * ```\n */\n getColumnState?(field: string): Partial<ColumnState> | undefined;\n\n /**\n * Apply plugin-specific state to a column.\n * Called by the grid when restoring column state from serialized data.\n * Plugins should restore their internal state based on the provided state.\n *\n * @param field - The field name of the column\n * @param state - The column state to apply (may contain plugin-specific properties)\n *\n * @example\n * ```ts\n * applyColumnState(field: string, state: ColumnState): void {\n * // Check for filter property added via module augmentation\n * const filter = (state as any).filter;\n * if (filter) {\n * this.filterModels.set(field, filter);\n * this.applyFilter();\n * }\n * }\n * ```\n */\n applyColumnState?(field: string, state: ColumnState): void;\n\n // #endregion\n\n // #region Scroll Boundary Hooks\n\n /**\n * Report horizontal scroll boundary offsets for this plugin.\n * Plugins that obscure part of the scroll area (e.g., pinned/sticky columns)\n * should return how much space they occupy on each side.\n * The keyboard navigation uses this to ensure focused cells are fully visible.\n *\n * @param rowEl - The row element (optional, for calculating widths from rendered cells)\n * @param focusedCell - The currently focused cell element (optional, to determine if scrolling should be skipped)\n * @returns Object with left/right pixel offsets and optional skipScroll flag, or undefined if plugin has no offsets\n *\n * @example\n * ```ts\n * getHorizontalScrollOffsets(rowEl?: HTMLElement, focusedCell?: HTMLElement): { left: number; right: number; skipScroll?: boolean } | undefined {\n * // Calculate total width of left-pinned columns\n * const leftCells = rowEl?.querySelectorAll('.sticky-left') ?? [];\n * let left = 0;\n * leftCells.forEach(el => { left += (el as HTMLElement).offsetWidth; });\n * // Skip scroll if focused cell is pinned (always visible)\n * const skipScroll = focusedCell?.classList.contains('sticky-left');\n * return { left, right: 0, skipScroll };\n * }\n * ```\n */\n getHorizontalScrollOffsets?(\n rowEl?: HTMLElement,\n focusedCell?: HTMLElement,\n ): { left: number; right: number; skipScroll?: boolean } | undefined;\n\n /**\n * Report vertical scroll boundary offsets for this plugin.\n * Plugins that overlay the top or bottom of the rows viewport (e.g. sticky\n * row clones) should return how much space they obscure on each edge, so\n * keyboard navigation can scroll a focused row clear of the overlay rather\n * than leaving it hidden underneath — WCAG 2.2 SC 2.4.11 Focus Not Obscured.\n *\n * Only report space that is painted *over* the scrollable rows. Content that\n * takes part in normal flow (pinned-row bars, the column header) already\n * shrinks the viewport and must NOT be reported here, or rows would scroll\n * twice as far as needed.\n *\n * @param focusedRowIndex - Index of the row being scrolled into view, so a plugin can report `skipScroll` when it already renders that row in a permanently visible overlay\n * @returns Object with top/bottom pixel offsets and optional skipScroll flag, or undefined if plugin obscures nothing\n *\n * @example\n * ```ts\n * getVerticalScrollOffsets(focusedRowIndex?: number): { top: number; bottom: number; skipScroll?: boolean } | undefined {\n * if (!this.overlayEl) return undefined;\n * // The row is already pinned in the overlay — it is visible where it is.\n * if (focusedRowIndex != null && this.stuckIndices.includes(focusedRowIndex)) {\n * return { top: 0, bottom: 0, skipScroll: true };\n * }\n * return { top: this.overlayEl.offsetHeight, bottom: 0 };\n * }\n * ```\n *\n * @since 3.6.0\n */\n getVerticalScrollOffsets?(\n focusedRowIndex?: number,\n ): { top: number; bottom: number; skipScroll?: boolean } | undefined;\n\n // #endregion\n\n // #region Shell Integration Hooks\n\n /**\n * Register a tool panel for this plugin.\n * Return undefined if plugin has no tool panel.\n * The shell will create a toolbar toggle button and render the panel content\n * when the user opens the panel.\n *\n * @returns Tool panel definition, or undefined if plugin has no panel\n *\n * @example\n * ```ts\n * getToolPanel(): ToolPanelDefinition | undefined {\n * return {\n * id: 'columns',\n * title: 'Columns',\n * icon: '☰',\n * tooltip: 'Show/hide columns',\n * order: 10,\n * render: (container) => {\n * this.renderColumnList(container);\n * return () => this.cleanup();\n * },\n * };\n * }\n * ```\n */\n getToolPanel?(): ToolPanelDefinition | undefined;\n\n /**\n * Register content for the shell header center section.\n * Return undefined if plugin has no header content.\n * Examples: search input, selection summary, status indicators.\n *\n * @returns Header content definition, or undefined if plugin has no header content\n *\n * @example\n * ```ts\n * getHeaderContent(): HeaderContentDefinition | undefined {\n * return {\n * id: 'quick-filter',\n * order: 10,\n * render: (container) => {\n * const input = document.createElement('input');\n * input.type = 'text';\n * input.placeholder = 'Search...';\n * input.addEventListener('input', this.handleInput);\n * container.appendChild(input);\n * return () => input.removeEventListener('input', this.handleInput);\n * },\n * };\n * }\n * ```\n */\n getHeaderContent?(): HeaderContentDefinition | undefined;\n\n // #endregion\n}\n","/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n\n/**\n * Leading characters that make Excel / LibreOffice / Google Sheets treat a cell\n * as a formula rather than text.\n */\nconst FORMULA_TRIGGER_RE = /^[=+\\-@\\t\\r]/;\n\n/**\n * Options for {@link formatDelimitedValue}.\n *\n * @since 3.5.0\n */\nexport interface DelimitedFormatOptions {\n /** Field separator (`,` for CSV, `\\t` for clipboard). */\n delimiter: string;\n /** Row separator. */\n newline: string;\n /**\n * `'auto'` (default) quotes only strings containing a separator or quote,\n * `'always'` quotes every string, `'never'` disables quoting entirely.\n */\n quoting?: 'auto' | 'always' | 'never';\n /**\n * Prefix formula-triggering strings with `'` so spreadsheets treat them as\n * text. Defaults to `true`.\n */\n escapeFormulas?: boolean;\n}\n\n/**\n * Format a cell value for a delimiter-separated text format (CSV export or\n * clipboard copy).\n *\n * Only string values are formula-escaped: numbers such as `-5` stringify to a\n * leading `-` but are unambiguously numeric to a spreadsheet, and escaping them\n * would turn every negative number into text.\n *\n * Dispatch order is `typeof`-first because string + number cover the vast\n * majority of cell values; the cheap typeof check skips an `instanceof Date`\n * probe (which V8 cannot fold into a fast path) for every plain string cell.\n *\n * @param value - The cell value to format\n * @param opts - Delimiter, newline, quoting and formula-escaping behaviour\n * @returns The value as a delimiter-safe string\n * @since 3.5.0\n */\nexport function formatDelimitedValue(value: unknown, opts: DelimitedFormatOptions): string {\n // Hot path: strings (most cells).\n if (typeof value === 'string') {\n const text = opts.escapeFormulas !== false && FORMULA_TRIGGER_RE.test(value) ? `'${value}` : value;\n const quoting = opts.quoting ?? 'auto';\n if (\n quoting === 'always' ||\n (quoting === 'auto' &&\n (text.includes(opts.delimiter) ||\n text.includes(opts.newline) ||\n text.includes('\"') ||\n text.includes('\\n') ||\n text.includes('\\r')))\n ) {\n return `\"${text.replace(/\"/g, '\"\"')}\"`;\n }\n return text;\n }\n if (typeof value === 'number') return String(value);\n if (typeof value === 'boolean') return value ? 'true' : 'false';\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n // Symbols, bigints, etc.\n return String(value);\n}\n","/**\n * Structured clipboard payload codec.\n *\n * Copy writes both `text/plain` (WYSIWYG for external targets) and `text/html`.\n * The HTML is a real `<table>` of the display text whose root element also\n * carries a base64-encoded structured payload in a `data-tbw-clip` attribute.\n * A same-app paste — even **cross-grid or cross-window** — can then recover the\n * raw cell values losslessly, while external targets just see the table/text.\n *\n * Kept in its own module so `copy.ts` and `paste.ts` share the format without\n * importing each other.\n */\nimport { escapeHtml } from '../../core/internal/sanitize';\n\n/**\n * Structured clipboard payload carried in `text/html`. `rows` are the RAW cell\n * values (data rows only), `fields` the source column fields in the same order.\n * @internal\n */\nexport interface ClipboardPayload {\n /** Payload schema version. */\n v: 1;\n /** Source column fields, in column order. */\n fields: string[];\n /** Raw cell values, one inner array per data row (no header). */\n rows: unknown[][];\n}\n\n/** Attribute (on the payload table) that marks our structured HTML clipboard. */\nexport const CLIPBOARD_PAYLOAD_ATTR = 'data-tbw-clip';\n\n/** Unicode-safe base64 encode of a JSON payload for an HTML attribute. */\nfunction encodePayload(payload: ClipboardPayload): string {\n return btoa(encodeURIComponent(JSON.stringify(payload)));\n}\n\n/**\n * Build the `text/html` clipboard representation: a real `<table>` of the\n * DISPLAY text (so external targets like Excel get a proper table) whose root\n * element carries the base64-encoded structured {@link ClipboardPayload} in a\n * `data-tbw-clip` attribute for lossless same-app paste.\n */\nexport function buildClipboardHtml(\n header: string[] | null,\n displayRows: string[][],\n payload: ClipboardPayload,\n): string {\n const thead = header ? `<thead><tr>${header.map((h) => `<th>${escapeHtml(h)}</th>`).join('')}</tr></thead>` : '';\n const tbody = `<tbody>${displayRows\n .map((r) => `<tr>${r.map((c) => `<td>${escapeHtml(c)}</td>`).join('')}</tr>`)\n .join('')}</tbody>`;\n return `<table ${CLIPBOARD_PAYLOAD_ATTR}=\"${encodePayload(payload)}\">${thead}${tbody}</table>`;\n}\n\n/**\n * Extract the structured {@link ClipboardPayload} embedded in a `text/html`\n * clipboard representation written by {@link buildClipboardHtml}. Enables a\n * lossless **cross-grid / cross-window** paste of object-valued cells (the\n * in-memory buffer only covers the same grid instance).\n *\n * Returns `null` when the HTML has no `data-tbw-clip` marker (e.g. an external\n * paste from Excel) or the payload can't be decoded. Parsing is defensive —\n * malformed input never throws.\n *\n * @param html - Raw `text/html` from `clipboardData.getData('text/html')`\n */\nexport function parseClipboardHtmlPayload(html: string | undefined | null): ClipboardPayload | null {\n if (!html || html.indexOf(CLIPBOARD_PAYLOAD_ATTR) === -1) return null;\n try {\n // Extract only our own base64 payload attribute with a targeted match rather\n // than parsing the whole (untrusted) clipboard HTML through a DOM sink\n // (DOMParser) — the latter feeds attacker-controlled markup to the parser and\n // trips CodeQL js/xss. The attribute value is base64 (btoa output), whose\n // alphabet excludes quotes and tag characters, so a simple attribute match is\n // both safe and sufficient.\n const match = html.match(new RegExp(`${CLIPBOARD_PAYLOAD_ATTR}=\"([A-Za-z0-9+/=]*)\"`));\n const encoded = match?.[1];\n if (!encoded) return null;\n const payload = JSON.parse(decodeURIComponent(atob(encoded))) as ClipboardPayload;\n if (payload && Array.isArray(payload.rows) && Array.isArray(payload.fields)) {\n return payload;\n }\n return null;\n } catch {\n return null;\n }\n}\n","/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport { CLIPBOARD_FAILED, warnDiagnostic } from '../../core/internal/diagnostics';\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatDelimitedValue, type DelimitedFormatOptions } from '../shared/data-collection';\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 return formatDelimitedValue(value, toFormatOptions(config));\n}\n\n/** Map the plugin config onto the shared delimited-format options. */\nfunction toFormatOptions(config: ClipboardConfig): DelimitedFormatOptions {\n return {\n delimiter: config.delimiter ?? '\\t',\n newline: config.newline ?? '\\n',\n quoting: config.quoteStrings ? 'always' : 'auto',\n escapeFormulas: config.escapeFormulas,\n };\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 // Built once — this runs per cell across the whole selection.\n const format = toFormatOptions(config);\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 const value = resolveCellValue(row, col);\n return config.processCell\n ? config.processCell(value, col.field, row)\n : formatDelimitedValue(value, format);\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 * When `html` is supplied, writes BOTH `text/plain` and `text/html` via\n * `ClipboardItem` so a same-app paste (even cross-grid or cross-window) can\n * recover a structured payload embedded in the HTML, while external targets\n * (Excel, editors) still get the plain text. Silently falls back to text-only\n * when `ClipboardItem` / `clipboard.write` is unavailable or rejects.\n *\n * @param text - The text to copy (`text/plain`)\n * @param html - Optional rich `text/html` representation (may embed a payload)\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string, html?: string): Promise<boolean> {\n if (html && typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {\n try {\n await navigator.clipboard.write([\n new ClipboardItem({\n 'text/plain': new Blob([text], { type: 'text/plain' }),\n 'text/html': new Blob([html], { type: 'text/html' }),\n }),\n ]);\n return true;\n } catch {\n // Fall through to text-only write below.\n }\n }\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch (err) {\n warnDiagnostic(CLIPBOARD_FAILED, `Clipboard API failed: ${err}`);\n // Fallback for older browsers or when Clipboard API is not available\n const textarea = document.createElement('textarea');\n textarea.value = text;\n textarea.style.position = 'fixed';\n textarea.style.opacity = '0';\n textarea.style.pointerEvents = 'none';\n document.body.appendChild(textarea);\n textarea.select();\n const success = document.execCommand('copy');\n document.body.removeChild(textarea);\n return success;\n }\n}\n","/**\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 * Implementation: char-by-char state machine for delimiter/newline/quote\n * detection, but cell values are extracted via `slice(start, end)` rather\n * than `+= char` accumulation. The vast majority of cells have no quotes,\n * so the hot path is a single substring slice per cell. Cells that did\n * contain quotes fall back to {@link unquoteCell} for the strip + escape\n * pass.\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 // Normalize Windows / old-Mac line endings.\n const normalized = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n const len = normalized.length;\n\n const rows: string[][] = [];\n let currentRow: string[] = [];\n let cellStart = 0;\n let inQuotes = false;\n let cellHasQuotes = false;\n\n const finalizeCell = (endIdx: number): string => {\n const raw = normalized.slice(cellStart, endIdx);\n return cellHasQuotes ? unquoteCell(raw) : raw;\n };\n\n const pushRow = () => {\n // Filter purely-empty rows (single empty cell or all-whitespace cells),\n // matching the original char-by-char implementation's contract.\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n currentRow = [];\n };\n\n for (let i = 0; i < len; i++) {\n const char = normalized[i];\n\n if (char === '\"') {\n cellHasQuotes = true;\n if (!inQuotes) {\n inQuotes = true;\n } else if (normalized[i + 1] === '\"') {\n // Escaped quote (\"\") — skip the second quote, stay inside the quoted run.\n i++;\n } else {\n inQuotes = false;\n }\n } else if (char === delimiter && !inQuotes) {\n currentRow.push(finalizeCell(i));\n cellStart = i + 1;\n cellHasQuotes = false;\n } else if (char === newline && !inQuotes) {\n currentRow.push(finalizeCell(i));\n cellStart = i + 1;\n cellHasQuotes = false;\n pushRow();\n }\n }\n\n // Final cell + row.\n currentRow.push(finalizeCell(len));\n pushRow();\n\n return rows;\n}\n\n/**\n * Strip surrounding quotes and unescape `\"\"` → `\"` from a cell value that\n * contained at least one quote character. Only invoked from the slow path\n * of {@link parseClipboardText}.\n */\nfunction unquoteCell(raw: string): string {\n let out = '';\n let inQuotes = false;\n for (let i = 0; i < raw.length; i++) {\n const c = raw[i];\n if (c === '\"') {\n if (!inQuotes) {\n inQuotes = true;\n } else if (raw[i + 1] === '\"') {\n out += '\"';\n i++;\n } else {\n inQuotes = false;\n }\n } else {\n out += c;\n }\n }\n return out;\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 { invalidateAccessorCache, readCellField, writeCellField } from '../../core/internal/value-accessor';\nimport type { GridElement } from '../../core/plugin/base-plugin';\nimport type { CellEditablePredicate } from '../../core/plugin/types';\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 * @since 0.4.2\n */\nexport type PasteHandler = (detail: PasteDetail, grid: GridElement) => boolean | void;\n\n/**\n * Options for programmatic copy operations.\n *\n * Allows callers to control exactly which columns and rows are included\n * in a copy, independently of the current selection state.\n *\n * @example Copy specific columns from selected rows\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * // User selected rows 0, 2, 4 via a dialog, chose columns to include\n * const text = await clipboard.copy({\n * rowIndices: [0, 2, 4],\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * ```\n * @since 1.14.0\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/**\n * Configuration options for the clipboard plugin\n *\n * @since 0.1.1\n */\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 /**\n * Neutralize spreadsheet formula injection (CWE-1236) by prefixing string\n * values that start with `=`, `+`, `-`, `@`, TAB or CR with a single quote,\n * so a paste into Excel / LibreOffice / Sheets renders them as text instead\n * of evaluating them (default: `true`).\n *\n * Grid-to-grid paste is unaffected — that path uses the structured\n * `text/html` payload, not the plain-text representation.\n *\n * @since 3.5.0\n */\n escapeFormulas?: boolean;\n /** Custom cell value processor for copy operations */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n /**\n * When `true`, pasting into a multi-cell selection larger than the clipboard\n * source tiles (repeats) the source to fill the whole selection: a single\n * copied cell fills every selected cell, a 1×2 source fills as\n * `val1, val2, val1, val2`, and a 2×2 block tiles across the selection.\n *\n * Only applies when a bounded (multi-cell) selection is active — it never\n * grows the grid. Defaults to `false` (paste writes only the source extent).\n *\n * @default false\n * @since 3.0.0\n */\n fillSelection?: boolean;\n /**\n * Custom paste handler that **fully replaces** {@link defaultPasteHandler}.\n *\n * ⚠️ **Prefer not to override this.** The default handler is no longer a thin\n * \"write text into cells\" routine — it now implements substantial behavior\n * that is easy to get subtly wrong when reimplemented:\n *\n * - editability resolution via the editing plugin (`getCellEditableResolver`,\n * including row-conditional `editable`);\n * - per-column {@link BaseColumnConfig.onPaste} reject / transform, plus the\n * `paste-rejected` event;\n * - structured (`rawRows`) same-grid / cross-window values so object cells\n * round-trip losslessly (not degraded to display text);\n * - fill-selection tiling of a smaller source across a bounded selection;\n * - routing edits through `grid.updateRows(…, 'paste')` so paste participates\n * in dirty tracking, undo/redo history, cancelable validation, and the\n * `'paste'` commit source — with a direct-write fallback for id-less rows;\n * - growing the grid for unbounded single-cell-expansion pastes.\n *\n * **Use an extension point instead of overriding, wherever possible:**\n * - reject / transform per cell → column {@link BaseColumnConfig.onPaste};\n * - coerce / veto committed values globally → the cancelable `cell-commit`\n * event (`detail.source === 'paste'` distinguishes a paste);\n * - observe the raw paste → the `paste` event;\n * - react to rejected cells → the `paste-rejected` event.\n *\n * Other values:\n * - `null` — disable auto-paste entirely (the `paste` event still fires).\n * - a function returning `false` — you handled it; skip the default.\n *\n * **If you must override** (e.g. bespoke target placement or side effects),\n * you are responsible for re-implementing the behaviors above. At minimum,\n * honor per-column `onPaste` with the exported {@link resolveColumnPaste} and\n * fire {@link emitPasteRejected} so `onPaste` and `paste-rejected` keep working:\n *\n * ```ts\n * import { resolveColumnPaste, emitPasteRejected } from '@toolbox-web/grid/plugins/clipboard';\n *\n * pasteHandler: (detail, grid) => {\n * const rejected = [];\n * for (const cell of myCells(detail)) {\n * const res = resolveColumnPaste(cell.column.onPaste, {\n * value: cell.value, field: cell.field, row: cell.row,\n * rowIndex: cell.rowIndex, oldValue: cell.oldValue, sourceField: cell.sourceField,\n * });\n * if (res.accepted) writeCell(cell, res.value);\n * else rejected.push({ field: cell.field, rowIndex: cell.rowIndex, row: cell.row, value: cell.value, reason: res.reason });\n * }\n * emitPasteRejected(grid, rejected);\n * return false; // handled\n * }\n * ```\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/**\n * Event detail emitted after a successful copy operation\n *\n * @since 0.1.1\n */\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/**\n * Target cell coordinates and bounds for paste operations\n *\n * @since 0.4.2\n */\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/**\n * Event detail emitted after a paste operation\n *\n * @since 0.1.1\n */\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 * When `fillSelection` is active, this spans the full selection width so the source can be tiled.\n */\n fields: string[];\n /**\n * When `true`, the paste handler tiles the clipboard source across the full\n * selection bounds (see {@link ClipboardConfig.fillSelection}). Set by the\n * plugin from config; only ever `true` when `target.bounds` is set.\n * @since 3.0.0\n */\n fillSelection?: boolean;\n /**\n * Raw (structured) cell values for a **same-grid** paste, aligned 1:1 with\n * {@link rows} (same dimensions, data rows only). Present only when the paste\n * text exactly matches what this grid last copied — so an object-valued cell\n * (e.g. `{id,name}`, arrays) round-trips losslessly instead of degrading to\n * the copied display text. `undefined` for external/cross-grid pastes, where\n * only the text is available. The default handler prefers `rawRows` over\n * `rows` for values (cloning each so targets don't share references).\n * @since 3.0.0\n */\n rawRows?: unknown[][];\n /**\n * Source column fields the pasted data was copied FROM, in the copied column\n * order (aligned with the columns of {@link rows} / {@link rawRows}). Lets a\n * column's {@link BaseColumnConfig.onPaste} know the origin column so it can\n * reject cross-column / cross-type pastes. Present for a **same-app** paste\n * (same grid via the in-memory buffer, or cross-grid / cross-window via the\n * structured `text/html` payload); `undefined` for external pastes (e.g. from\n * Excel), where only the text is available.\n * @since 3.0.0\n */\n sourceFields?: string[];\n}\n\n/**\n * Context passed to a column's {@link BaseColumnConfig.onPaste} guard/transform\n * for each cell a paste would write into.\n *\n * @since 3.0.0\n */\nexport interface PasteCellContext<TRow = unknown, TValue = unknown> {\n /** The incoming pasted value (the raw structured value for a same-grid paste). */\n value: TValue;\n /** The column field receiving the value. */\n field: string;\n /** The target row object (pre-paste state). */\n row: TRow;\n /** Index of the target row in the current data set. */\n rowIndex: number;\n /** The cell's current value before the paste. */\n oldValue: TValue;\n /**\n * The column field the value was copied FROM (the origin column), for a\n * same-app paste. `undefined` for an external paste (e.g. from Excel) or when\n * the source column is unknown. Use it to reject cross-column / cross-type\n * pastes (e.g. refuse a value copied from a \"car\" column into a \"fruit\"\n * column). To compare types, look up your own column config by this field.\n * @since 3.0.0\n */\n sourceField?: string;\n}\n\n/**\n * A column's paste guard / transform (`onPaste`). See {@link BaseColumnConfig.onPaste}.\n * @since 3.0.0\n */\nexport type ColumnPasteGuard<TRow = unknown, TValue = unknown> =\n boolean | ((ctx: PasteCellContext<TRow, TValue>) => boolean | { value: TValue });\n\n/**\n * Why a cell's paste was rejected: `'column'` = the column set `onPaste: false`;\n * `'cell'` = an `onPaste` callback returned `false`.\n * @since 3.0.0\n */\nexport type PasteRejectionReason = 'column' | 'cell';\n\n/** One cell whose paste a column's `onPaste` guard rejected. @since 3.0.0 */\nexport interface PasteRejectedCell {\n /** The column field. */\n field: string;\n /** Index of the target row in the current data set. */\n rowIndex: number;\n /** The target row object. */\n row: unknown;\n /** The incoming value that was rejected (before any transform). */\n value: unknown;\n /** Why it was rejected. */\n reason: PasteRejectionReason;\n}\n\n/**\n * Detail for the `paste-rejected` event: the cells a column's `onPaste` guard\n * rejected during a paste. Fires once per paste, only when at least one cell was\n * rejected, so a consumer can surface a message. Non-editable cells are skipped\n * silently and are NOT reported here.\n * @since 3.0.0\n */\nexport interface PasteRejectedDetail {\n /** Cells rejected by a column `onPaste` guard. */\n rejected: PasteRejectedCell[];\n}\n\n/** Result of {@link resolveColumnPaste}. @since 3.0.0 */\nexport type PasteResolution = { accepted: true; value: unknown } | { accepted: false; reason: PasteRejectionReason };\n\n/**\n * Resolve a column's {@link ColumnPasteGuard} (`onPaste`) for a single cell.\n *\n * Pure — never mutates or emits. Exposed so a **custom `pasteHandler`** can honor\n * per-column `onPaste` identically to {@link defaultPasteHandler}: call it per\n * cell, write `resolution.value` when accepted, and collect the rejected cells to\n * pass to {@link emitPasteRejected}.\n *\n * @param onPaste - The column's `onPaste` config (`column.onPaste`), if any.\n * @param ctx - The cell context (value, field, row, rowIndex, oldValue, sourceField).\n * @returns `{ accepted: true, value }` (value possibly transformed) or\n * `{ accepted: false, reason }`.\n *\n * @example\n * ```ts\n * // Inside a custom pasteHandler:\n * const rejected: PasteRejectedCell[] = [];\n * const res = resolveColumnPaste(column.onPaste, { value, field, row, rowIndex, oldValue });\n * if (res.accepted) row[field] = res.value;\n * else rejected.push({ field, rowIndex, row, value, reason: res.reason });\n * // …after writing all cells:\n * emitPasteRejected(grid, rejected);\n * ```\n * @since 3.0.0\n */\nexport function resolveColumnPaste(onPaste: ColumnPasteGuard | undefined, ctx: PasteCellContext): PasteResolution {\n if (onPaste === false) return { accepted: false, reason: 'column' };\n if (typeof onPaste === 'function') {\n const result = onPaste(ctx);\n if (result === false) return { accepted: false, reason: 'cell' };\n if (result && typeof result === 'object' && 'value' in result) {\n return { accepted: true, value: (result as { value: unknown }).value };\n }\n }\n return { accepted: true, value: ctx.value };\n}\n\n/**\n * Dispatch the `paste-rejected` event on the grid. No-op when `rejected` is empty.\n * Exposed so a custom `pasteHandler` can emit the same event the default handler\n * does, after resolving cells via {@link resolveColumnPaste}.\n * @since 3.0.0\n */\nexport function emitPasteRejected(grid: GridElement, rejected: PasteRejectedCell[]): void {\n if (rejected.length === 0) return;\n grid.dispatchEvent?.(new CustomEvent<PasteRejectedDetail>('paste-rejected', { detail: { rejected }, bubbles: true }));\n}\n\n/**\n * Default paste handler that applies pasted data to the grid.\n *\n * This is the built-in handler used when no custom `pasteHandler` is configured.\n *\n * Edits are routed through `grid.updateRows(…, 'paste')` so paste participates in\n * the full edit pipeline — dirty tracking, cancelable validation, undo/redo\n * history, and abortion — exactly like an interactive edit, and so a\n * `cell-commit` listener can tell a paste apart via `detail.source === 'paste'`.\n * Rows without a resolvable ID (no `getRowId`) fall back to a direct in-place\n * write, which still updates values but does not track them.\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 * - Fill-selection: when `detail.fillSelection` is set, the source is tiled\n * (repeated via modulo indexing) to fill the whole selection bounds\n * - Non-editable cells: values are skipped (column alignment preserved).\n * Editability is resolved by the editing plugin via the\n * `getCellEditableResolver` query — including row-conditional `editable`.\n * Without the editing plugin, no cell is editable and paste is a no-op.\n * - Per-column `onPaste`: after the editability check, a column's\n * {@link BaseColumnConfig.onPaste} may reject the cell (skipped, alignment\n * preserved) or transform the pasted value. Rejected cells are reported once\n * via the `paste-rejected` event ({@link PasteRejectedDetail}).\n *\n * @param detail - The parsed paste data from clipboard\n * @param grid - The grid element to update\n * @since 0.4.2\n */\nexport function defaultPasteHandler(detail: PasteDetail, grid: GridElement): void {\n const { rows: pastedRows, rawRows, target, fields, fillSelection, sourceFields } = detail;\n\n // No target = nothing to do\n if (!target || pastedRows.length === 0) return;\n\n // Prefer the raw structured values for a same-grid paste (lossless object\n // round-trip); fall back to the parsed text for external/cross-grid pastes.\n const valueRows: unknown[][] = rawRows ?? pastedRows;\n\n const currentRows = grid.rows as Record<string, unknown>[];\n const columns = grid.effectiveConfig.columns ?? [];\n const allFields = columns.map((col) => col.field);\n const columnByField = new Map(columns.map((col) => [col.field, col]));\n\n // Editability is owned by the editing plugin (row-conditional included). With\n // no editing plugin loaded, nothing is editable and paste is a no-op.\n const [canEditCell = () => false] = grid.query<CellEditablePredicate>('getCellEditableResolver');\n\n // Accumulate the intended edits per target row (honoring editability, tiling,\n // and selection bounds). Rows beyond current data are only created for an\n // unbounded (single-cell expansion) paste.\n const editsByRow = new Map<number, Record<string, unknown>>();\n let rowCountAfter = currentRows.length;\n // Cells a column's `onPaste` guard rejected — reported via `paste-rejected`.\n const rejected: PasteRejectedCell[] = [];\n\n const addEdit = (\n rowIndex: number,\n field: string | undefined,\n value: unknown,\n evalRow: Record<string, unknown>,\n sourceField?: string,\n ) => {\n if (!field || !canEditCell(field, evalRow)) return;\n // Per-column paste guard/transform (clipboard-augmented `onPaste`). Runs\n // after the editability check so it only sees cells paste could write.\n const resolution = resolveColumnPaste(columnByField.get(field)?.onPaste, {\n value,\n field,\n row: evalRow,\n rowIndex,\n oldValue: readCellField(evalRow, field),\n sourceField,\n });\n if (!resolution.accepted) {\n rejected.push({ field, rowIndex, row: evalRow, value, reason: resolution.reason });\n return; // reject this cell (alignment preserved, like a non-editable cell)\n }\n let changes = editsByRow.get(rowIndex);\n if (!changes) {\n changes = {};\n editsByRow.set(rowIndex, changes);\n }\n // Clone structured values so tiled/multi-target pastes never share a\n // reference (mutating one row's object would otherwise mutate the source\n // and every other target). No-op for primitives (the text path).\n changes[field] = cloneStructured(resolution.value);\n };\n\n if (fillSelection && target.bounds) {\n // Fill-selection (tile) mode: repeat the source across the selection bounds\n // using modulo indexing. Never grows the grid. Editability is resolved\n // against the pre-paste row (bounded mode never grows).\n const srcRows = valueRows.length;\n for (let rowIndex = target.row; rowIndex <= target.bounds.endRow; rowIndex++) {\n if (rowIndex >= currentRows.length) break;\n const sourceRow = valueRows[(rowIndex - target.row) % srcRows];\n const srcCols = sourceRow.length;\n if (srcCols === 0) continue;\n const evalRow = currentRows[rowIndex];\n fields.forEach((field, colOffset) =>\n addEdit(rowIndex, field, sourceRow[colOffset % srcCols], evalRow, sourceFields?.[colOffset % srcCols]),\n );\n }\n } else {\n const maxPasteRow = target.bounds ? target.bounds.endRow : Infinity;\n valueRows.forEach((rowData, rowOffset) => {\n const targetRowIndex = target.row + rowOffset;\n if (targetRowIndex > maxPasteRow) return;\n if (target.bounds && targetRowIndex >= currentRows.length) return; // bounded: don't grow\n if (!target.bounds && targetRowIndex >= rowCountAfter) rowCountAfter = targetRowIndex + 1;\n // Editability resolved against the pre-paste row (empty for grown rows).\n const evalRow = currentRows[targetRowIndex] ?? {};\n rowData.forEach((cellValue, colOffset) =>\n addEdit(targetRowIndex, fields[colOffset], cellValue, evalRow, sourceFields?.[colOffset]),\n );\n });\n }\n\n if (editsByRow.size === 0 && rowCountAfter === currentRows.length) {\n // Nothing accepted (e.g. every cell rejected) — still report the rejections.\n emitPasteRejected(grid, rejected);\n return;\n }\n\n // Grow the grid first for unbounded pastes that extend past existing data.\n // New rows start empty; their pasted values are applied in the write phase.\n if (rowCountAfter > currentRows.length) {\n const grown = [...currentRows];\n while (grown.length < rowCountAfter) {\n const emptyRow: Record<string, unknown> = {};\n allFields.forEach((f) => (emptyRow[f] = ''));\n grown.push(emptyRow);\n }\n grid.rows = grown;\n }\n\n const rowsNow = grid.rows as Record<string, unknown>[];\n\n // Route edits through updateRows so paste flows through the edit pipeline\n // (dirty tracking, validation, history, abortion). Rows without a resolvable\n // ID fall back to a direct in-place write.\n const updates: Array<{ id: string; changes: Record<string, unknown> }> = [];\n let directWrote = false;\n for (const [rowIndex, changes] of editsByRow) {\n const row = rowsNow[rowIndex];\n if (!row) continue;\n let id: string | undefined;\n try {\n id = grid.getRowId(row);\n } catch {\n id = undefined;\n }\n if (id == null) {\n // No stable ID → can't route through updateRow; write directly. Invalidate\n // the value-accessor cache per field (row identity is unchanged), matching\n // RowManager.updateRow — otherwise a `column.valueAccessor` display can go\n // stale after paste.\n for (const [field, value] of Object.entries(changes)) {\n writeCellField(row, field, value);\n invalidateAccessorCache(row as object, field);\n }\n directWrote = true;\n } else {\n updates.push({ id, changes });\n }\n }\n\n if (updates.length > 0) {\n grid.updateRows(updates, 'paste');\n } else if (directWrote && rowCountAfter === currentRows.length) {\n // Direct writes only, no structural grow above — trigger a render.\n grid.rows = [...rowsNow];\n }\n\n // Notify consumers of any cells a column's `onPaste` guard rejected.\n emitPasteRejected(grid, rejected);\n}\n\n/**\n * Deep-clone a structured cell value so tiled/multi-target pastes don't share a\n * reference. Primitives (and `null`) are returned as-is. Falls back to the\n * original value if it isn't structured-cloneable.\n * @internal\n */\nexport function cloneStructured(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n}\n\n// Module Augmentation - Register plugin name for type-safe getPluginByName()\ndeclare module '../../core/types' {\n interface DataGridEventMap {\n /** Fired after a successful copy operation. Provides the copied text, row count, and column count. @group Clipboard Events */\n copy: CopyDetail;\n /** Fired after a paste operation. Provides parsed rows, target cell, and column fields. @group Clipboard Events */\n paste: PasteDetail;\n /** Fired after a paste when one or more cells were rejected by a column's `onPaste` guard. @group Clipboard Events */\n 'paste-rejected': PasteRejectedDetail;\n }\n\n interface PluginNameMap {\n clipboard: import('./clipboard-plugin').ClipboardPlugin;\n }\n\n /** Clipboard contributes its own edit-origin tag so a `cell-commit` listener\n * can tell a paste from a user edit via `detail.source === 'paste'`. */\n interface UpdateSourceMap {\n /** A value written by a clipboard paste. @since 3.0.0 */\n paste: true;\n }\n\n interface BaseColumnConfig<TRow, TValue> {\n /**\n * Per-column paste guard / transform. Requires the ClipboardPlugin.\n *\n * Runs for each cell a paste would write into (after the editing plugin's\n * editability check), letting a consumer reject or rewrite pasted values\n * **per column** — finer-grained than the whole-operation\n * {@link ClipboardConfig.pasteHandler}.\n *\n * - `true` / omitted — accept pastes (default behavior).\n * - `false` — this column never accepts pastes; matching cells are skipped\n * (column alignment is preserved, like a non-editable cell).\n * - `(ctx) => …` — called per cell. Return `false` to reject just that cell,\n * `true` (or nothing) to accept as-is, or `{ value }` to write a\n * transformed value instead. Returning `{ value }` disambiguates a\n * transform from a boolean verdict, so boolean-valued columns stay safe.\n *\n * Synchronous only — the paste pipeline does not await. Rejected cells\n * (either form) are reported once per paste via the `paste-rejected` event\n * ({@link PasteRejectedDetail}), so a consumer can show a message.\n *\n * The callback context also carries `sourceField` — the column the value was\n * copied FROM (for a same-app paste; `undefined` for external pastes) — so a\n * column can reject cross-column / cross-type pastes (e.g. refuse a value\n * copied from a \"car\" column into a \"fruit\" column).\n *\n * @example\n * ```typescript\n * // Reject pastes into a locked column\n * { field: 'id', onPaste: false }\n *\n * // Reject invalid values, coerce the rest\n * {\n * field: 'price',\n * onPaste: ({ value }) => {\n * const n = Number(String(value).replace(/[^0-9.]/g, ''));\n * return Number.isFinite(n) ? { value: n } : false;\n * },\n * }\n * ```\n * @since 3.0.0\n */\n onPaste?: ColumnPasteGuard<TRow, TValue>;\n }\n}\n","/**\n * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport {\n BaseGridPlugin,\n type GridElement,\n type PluginDependency,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatValueAsText, resolveColumns, resolveRows } from '../shared/data-collection';\nimport { buildClipboardHtml, parseClipboardHtmlPayload } from './clipboard-payload';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n cloneStructured,\n defaultPasteHandler,\n type ClipboardConfig,\n type CopyDetail,\n type CopyOptions,\n type PasteDetail,\n type PasteTarget,\n} from './types';\n\n/**\n * Clipboard Plugin for tbw-grid\n *\n * Brings familiar copy/cut/paste functionality with full keyboard shortcut support\n * (Ctrl+C, Ctrl+X, Ctrl+V). Handles single cells, multi-cell selections, and integrates\n * seamlessly with Excel and other spreadsheet applications via tab-delimited output.\n *\n * > **Optional Dependency:** Works best with SelectionPlugin for copying/pasting selected\n * > cells. Without SelectionPlugin, copies the entire grid and pastes at row 0, column 0.\n *\n * ## Installation\n *\n * ```ts\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * ```\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n * | `Ctrl+X` / `Cmd+X` | Cut selected cells |\n *\n * ## Paste Behavior by Selection Type\n *\n * | Selection Type | Paste Behavior |\n * |----------------|----------------|\n * | Single cell | Paste expands freely from that cell |\n * | Range selection | Paste is clipped to fit within the selected range |\n * | Row selection | Paste is clipped to the selected rows |\n * | No selection | Paste starts at row 0, column 0 |\n *\n * With `fillSelection: true`, pasting a smaller source into a larger bounded\n * selection tiles the source to fill the whole selection (e.g. one cell fills\n * all selected cells; a 1×2 source fills as `val1, val2, val1, val2`).\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see SelectionPlugin for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n * @since 0.1.1\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin manifest — declares queries for inter-plugin communication.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [{ type: 'clipboard:copy', description: 'Triggers a copy operation and returns the copied text' }],\n };\n\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n /**\n * Raw (structured) values for the last copy, so a same-grid paste round-trips\n * object cells losslessly instead of degrading to the copied display text.\n * `text` is the exact clipboard text; a paste whose text matches restores\n * `rawRows` (data rows only, aligned with the copied columns). Cleared on\n * detach; a non-matching external paste simply ignores it.\n */\n #internalClipboard: { text: string; rawRows: unknown[][]; fields: string[] } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n grid.addEventListener('paste', (e) => this.#handleNativePaste(e), {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n this.#internalClipboard = null;\n }\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'clipboard:copy') {\n this.copy();\n return true;\n }\n return undefined;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n // Prevent the browser's default copy action so it doesn't overwrite\n // our clipboard write with whatever text is selected in the DOM.\n event.preventDefault();\n this.#handleCopy(event.target as HTMLElement);\n return true;\n }\n\n // For paste, we do NOT return true - let the native paste event fire\n // so we can access clipboardData synchronously in #handleNativePaste\n return false;\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Handle copy operation from keyboard shortcut.\n *\n * For keyboard-triggered copies, respects the current selection or\n * falls back to the focused cell from the DOM.\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n\n // Selection plugin exists but has no ranges → resolve the single active cell.\n // Range mode CLEARS `ranges` on plain keyboard navigation (arrow/Tab without\n // Shift), keeping the focused cell only as the selection `anchor`, and DOM\n // focus is NOT on a cell element after keyboard nav — so prefer the anchor\n // (a visible-column index) and only fall back to the focused DOM cell for\n // the mouse-focus / no-anchor edge. Without the anchor path, keyboard-nav\n // copy silently no-ops.\n if (selection && selection.ranges.length === 0) {\n let row: number | undefined;\n let field: string | undefined;\n if (selection.anchor) {\n row = selection.anchor.row;\n field = this.visibleColumns[selection.anchor.col]?.field;\n } else {\n const focused = this.#getFocusedCellFromDOM(target);\n if (focused) {\n row = focused.row;\n field = this.columns[focused.col]?.field;\n }\n }\n if (row == null || field == null) return;\n this.copy({ rowIndices: [row], columns: [field] });\n return;\n }\n\n // Delegate to the public copy() method (selection or full grid)\n this.copy();\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n // If the paste target is an editable form control or contenteditable element\n // (e.g. an active cell editor injected by EditingPlugin, a filter input, a\n // header search box), let the browser deliver the paste to that control\n // natively. Without this guard `event.preventDefault()` below would swallow\n // the user's keystroke and the editor input would never receive the text.\n if (this.#isEditablePasteTarget(event.target)) return;\n\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection via query\n const selection = this.#getSelection();\n const ranges = selection?.ranges ?? [];\n const firstRange = ranges[0];\n\n // Aggregate the bounding box across ALL selected ranges. A multi-cell\n // selection is frequently expressed as several single-cell ranges (clicking\n // or dragging cell-by-cell), so inspecting `ranges[0]` alone would treat it\n // as a single cell and skip fill/clip — pasting into only the first cell.\n // min/max also normalizes reversed (bottom-up / right-to-left) drags.\n let selMinRow = Infinity;\n let selMinCol = Infinity;\n let selMaxRow = -Infinity;\n let selMaxCol = -Infinity;\n for (const r of ranges) {\n selMinRow = Math.min(selMinRow, r.from.row, r.to.row);\n selMaxRow = Math.max(selMaxRow, r.from.row, r.to.row);\n selMinCol = Math.min(selMinCol, r.from.col, r.to.col);\n selMaxCol = Math.max(selMaxCol, r.from.col, r.to.col);\n }\n\n // Determine target cell (top-left of the whole selection). Range mode\n // CLEARS `ranges` on plain keyboard navigation (arrow/Tab without Shift),\n // keeping the focused cell only as the selection `anchor`. So when there are\n // no ranges, fall back to the anchor before defaulting to (0,0) — otherwise\n // \"copy, arrow to another cell, paste\" always lands on cell (0,0) instead of\n // the active cell. Mirrors the focused-cell fallback in #handleCopy.\n const anchor = selection?.anchor ?? null;\n const targetRow = firstRange ? selMinRow : (anchor?.row ?? 0);\n const targetCol = firstRange ? selMinCol : (anchor?.col ?? 0);\n\n // Multi-cell when the selection spans more than one cell in total, whether\n // it's one large range or many single-cell ranges.\n const isMultiCell =\n !!firstRange &&\n (selection?.mode === 'range' || selection?.mode === 'row') &&\n (selMinRow !== selMaxRow || selMinCol !== selMaxCol);\n\n const bounds = isMultiCell ? { endRow: selMaxRow, endCol: selMaxCol } : null;\n // Selection range indices are visible-column indices (from data-col)\n const maxCol = bounds?.endCol ?? this.visibleColumns.length - 1;\n\n // Drop a copied header row so a round-trip paste writes only values into\n // cells (never the header label). Strips when this grid is configured to\n // include headers AND every cell of the first parsed row is one of this\n // grid's own column labels — independent of which column is pasted INTO, so\n // cross-column pastes (e.g. \"Source terminal\" → \"Terminal route\") strip too.\n // External pastes (first row ≠ labels) are left intact.\n this.#dropCopiedHeaderRow(parsed);\n\n // Same-grid round-trip: when the pasted text is exactly what THIS grid last\n // copied, restore the raw structured values (lossless object cells) aligned\n // with the header-stripped text rows — this path preserves exact value types\n // (e.g. Date) since it never serializes. For a cross-grid / cross-window\n // paste the in-memory buffer misses, so fall back to the structured payload\n // embedded in the clipboard's text/html. External pastes have neither and\n // use the parsed text.\n let rawRows: unknown[][] | undefined;\n let sourceFields: string[] | undefined;\n if (\n this.#internalClipboard &&\n this.#internalClipboard.text === text &&\n this.#internalClipboard.rawRows.length === parsed.length\n ) {\n rawRows = this.#internalClipboard.rawRows;\n sourceFields = this.#internalClipboard.fields;\n } else {\n const payload = parseClipboardHtmlPayload(event.clipboardData?.getData('text/html'));\n if (payload && payload.rows.length === parsed.length) {\n rawRows = payload.rows;\n sourceFields = payload.fields;\n }\n }\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 // Fill-selection tiling only applies to a bounded (multi-cell) selection.\n const fillSelection = this.config.fillSelection === true && bounds !== null;\n\n // Build field list for paste width (constrained by bounds if set). When\n // filling the selection, extend fields across the full selection width so\n // the source can be tiled to fill every selected column; otherwise cap at\n // the clipboard's own width.\n const fields: string[] = [];\n const pasteWidth = parsed[0]?.length ?? 0;\n const fieldWidth = fillSelection ? maxCol - targetCol + 1 : pasteWidth;\n for (let i = 0; i < fieldWidth && 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, fillSelection, rawRows, sourceFields };\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 * Drop a header row that this grid itself copied, so a round-trip paste\n * never lands a header label in a data cell.\n *\n * A row copied with `includeHeaders` consists entirely of this grid's own\n * column labels (`header || field`). Detect that by matching every cell of the\n * first parsed row against the full set of column labels — independent of\n * which column the user pastes INTO. This is essential for **cross-column**\n * paste (e.g. copying \"Source terminal\" and pasting into \"Terminal route\"):\n * the copied header carries the SOURCE column's label, which does not equal\n * the target column's label but is still one of this grid's labels. Matching\n * the label set fixes cross-column paste while leaving external pastes (whose\n * first row is data, not labels) untouched.\n *\n * Guarded to avoid eating a legitimate first data row:\n * 1. The grid is configured with `includeHeaders` (it copies headers), and\n * 2. there is more than one row (never strip the only row), and\n * 3. every cell of the first row equals some column's label.\n */\n #dropCopiedHeaderRow(parsed: string[][]): void {\n if (!this.config.includeHeaders) return;\n // Never strip away the only row — that would make paste a no-op.\n if (parsed.length <= 1) return;\n\n const headerRow = parsed[0];\n if (headerRow.length === 0) return;\n\n const labels = this.#columnLabels();\n for (const cell of headerRow) {\n // A cell that isn't a known column label → this is real data, keep the row.\n if (!labels.has(cell)) return;\n }\n\n parsed.shift();\n }\n\n /**\n * Set of this grid's column labels (`header || field`), matching how\n * {@link buildClipboardText} serializes the copied header row. Used to detect\n * a header row this grid copied, regardless of paste position.\n */\n #columnLabels(): Set<string> {\n const labels = new Set<string>();\n for (const col of this.columns) {\n const label = col.header || col.field;\n if (label) labels.add(label);\n }\n return labels;\n }\n\n /**\n * True when the paste event originated from a focusable form control or\n * contenteditable element — i.e. somewhere the user expects the browser's\n * native paste behavior (typing into an editor input). Lets EditingPlugin\n * editors, filter inputs, and other text fields receive paste normally\n * instead of having ClipboardPlugin swallow the event.\n */\n #isEditablePasteTarget(target: EventTarget | null): boolean {\n if (!(target instanceof Element)) return false;\n if (target.closest('input, textarea, select, [contenteditable=\"\"], [contenteditable=\"true\"]')) {\n return true;\n }\n return false;\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection');\n return responses?.[0];\n }\n\n /**\n * Resolve columns and rows to include based on options and/or current selection.\n *\n * Priority for columns:\n * 1. `options.columns` (explicit field list)\n * 2. Selection union column bounds across ALL ranges (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 union row bounds across ALL ranges\n * 3. All rows\n *\n * `contains(rowOffset, colOffset)` (when non-null) reports whether a cell of\n * the resolved grid lies inside at least one selected range — callers use it\n * to blank the gaps between disjoint ranges, matching Excel's rectangular\n * multi-range copy.\n */\n #resolveData(options?: CopyOptions): {\n columns: ColumnConfig[];\n rows: Record<string, unknown>[];\n contains: ((rowOffset: number, colOffset: number) => boolean) | null;\n } {\n const selection = this.#getSelection();\n const ranges = selection?.ranges ?? [];\n\n // Union bounding box across ALL ranges. A multi-range selection (CTRL+drag\n // repeatedly) must copy every range, not just the last one drawn; min/max\n // also normalizes reversed (bottom-up / right-to-left) drags.\n let minRow = Infinity;\n let maxRow = -Infinity;\n let minCol = Infinity;\n let maxCol = -Infinity;\n for (const r of ranges) {\n minRow = Math.min(minRow, r.from.row, r.to.row);\n maxRow = Math.max(maxRow, r.from.row, r.to.row);\n minCol = Math.min(minCol, r.from.col, r.to.col);\n maxCol = Math.max(maxCol, r.from.col, r.to.col);\n }\n\n // --- Columns ---\n let columns: ColumnConfig[];\n // Absolute visible-column index per resolved column (null when the columns\n // did not come from the selection). `resolveColumns` may drop utility /\n // hidden columns from the slice, so offsets can't be derived arithmetically.\n let colIndices: number[] | null = null;\n if (options?.columns) {\n // Caller specified exact fields\n columns = resolveColumns(this.columns, options.columns);\n } else if (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 columns = resolveColumns(this.visibleColumns.slice(minCol, maxCol + 1));\n colIndices = columns.map((col) => this.visibleColumns.indexOf(col));\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 let rowIndices: number[] | null = null;\n if (options?.rowIndices) {\n // Caller specified exact row indices\n rows = resolveRows(this.rows as Record<string, unknown>[], options.rowIndices);\n } else if (ranges.length) {\n // Selection range: extract the union row span. Row mode selects WHOLE\n // rows and gets no column mask, so gaps between disjoint row ranges\n // (Ctrl+click rows 0, 5, 9) must be dropped outright rather than copied.\n const dropUnselectedRows = selection?.mode === 'row';\n const rowIsSelected = (r: number) =>\n ranges.some((g) => r >= Math.min(g.from.row, g.to.row) && r <= Math.max(g.from.row, g.to.row));\n rows = [];\n rowIndices = [];\n for (let r = minRow; r <= maxRow; r++) {\n const row = this.rows[r] as Record<string, unknown> | undefined;\n if (!row) continue;\n if (dropUnselectedRows && !rowIsSelected(r)) continue;\n rows.push(row);\n rowIndices.push(r);\n }\n } else {\n // No selection: all rows\n rows = this.rows as Record<string, unknown>[];\n }\n\n // Masking is only meaningful when BOTH axes came from the selection —\n // explicit `options.columns` / `options.rowIndices` (e.g. `copyRows()`)\n // would otherwise blank everything.\n const rowAbs = rowIndices;\n const colAbs = colIndices;\n const contains =\n rowAbs && colAbs\n ? (rowOffset: number, colOffset: number): boolean => {\n const row = rowAbs[rowOffset];\n const col = colAbs[colOffset];\n return ranges.some(\n (r) =>\n row >= Math.min(r.from.row, r.to.row) &&\n row <= Math.max(r.from.row, r.to.row) &&\n col >= Math.min(r.from.col, r.to.col) &&\n col <= Math.max(r.from.col, r.to.col),\n );\n }\n : null;\n\n return { columns, rows, contains };\n }\n\n /**\n * Build delimited text from resolved columns and rows.\n *\n * When no `processCell` callback is configured, uses \"copy what you see\" logic:\n * 1. Column `format` function (includes typeDefaults merged at config time)\n * 2. DOM cell textContent for columns with custom renderers (visible rows only)\n * 3. Raw value via `formatValueAsText` as final fallback\n */\n #buildText(\n columns: ColumnConfig[],\n rows: Record<string, unknown>[],\n options?: CopyOptions,\n contains?: ((rowOffset: number, colOffset: number) => boolean) | null,\n ): string {\n return this.#joinDisplayGrid(this.#buildDisplayGrid(columns, rows, options, contains), options);\n }\n\n /**\n * Build the 2D grid of DISPLAY strings for the given columns/rows (the same\n * WYSIWYG text used for `text/plain` and the `text/html` table). Header is\n * included only when configured.\n *\n * `contains` blanks cells that sit inside the selection's union bounding box\n * but outside every individual range, so a multi-range copy stays rectangular.\n */\n #buildDisplayGrid(\n columns: ColumnConfig[],\n rows: Record<string, unknown>[],\n options?: CopyOptions,\n contains?: ((rowOffset: number, colOffset: number) => boolean) | null,\n ): { header: string[] | null; rows: string[][] } {\n const includeHeaders = options?.includeHeaders ?? this.config.includeHeaders ?? false;\n const processCell = options?.processCell ?? this.config.processCell;\n const header = includeHeaders ? columns.map((c) => c.header || c.field) : null;\n const dataRows = rows.map((row, rowOffset) =>\n columns.map((col, colOffset) => {\n if (contains && !contains(rowOffset, colOffset)) return '';\n const value = resolveCellValue(row, col);\n if (processCell) return processCell(value, col.field, row);\n return this.#formatCellAsDisplayed(col, value, row);\n }),\n );\n return { header, rows: dataRows };\n }\n\n /** Join a display grid into delimited text (header row first when present). */\n #joinDisplayGrid(display: { header: string[] | null; rows: string[][] }, options?: CopyOptions): string {\n const delimiter = options?.delimiter ?? this.config.delimiter ?? '\\t';\n const newline = options?.newline ?? this.config.newline ?? '\\n';\n const lines: string[] = [];\n if (display.header) lines.push(display.header.join(delimiter));\n for (const cells of display.rows) lines.push(cells.join(delimiter));\n return lines.join(newline);\n }\n\n /**\n * Format a cell value the way the grid displays it.\n *\n * Priority:\n * 1. Column `format` function (includes typeDefaults applied at config merge time)\n * 2. DOM textContent for columns with a custom renderer (virtualized rows only)\n * 3. Raw value via `formatValueAsText`\n */\n #formatCellAsDisplayed(col: ColumnConfig, value: unknown, row: Record<string, unknown>): string {\n // 1. Column format function (covers col.format and typeDefaults)\n if (col.format) {\n try {\n const formatted = col.format(value, row);\n return formatted == null ? '' : String(formatted);\n } catch {\n // Format failed — fall through to next strategy\n }\n }\n\n // 2. DOM textContent for columns with custom renderers\n if (col.renderer || col.viewRenderer) {\n const text = this.#readCellTextFromDOM(col.field, row);\n if (text != null) return text;\n }\n\n // 3. Fallback to raw value formatting\n return formatValueAsText(value);\n }\n\n /**\n * Try to read a cell's displayed text from the DOM.\n *\n * Only works for rows currently rendered in the virtualized viewport.\n * Returns `null` if the row is not in the DOM (caller should fall back).\n */\n #readCellTextFromDOM(field: string, row: Record<string, unknown>): string | null {\n const host = this.gridElement;\n if (!host) return null;\n\n // Find the row index in the grid's current row array\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex === -1) return null;\n\n // Query the rendered cell by row index and field name\n const cell = host.querySelector<HTMLElement>(`.cell[data-row=\"${rowIndex}\"][data-field=\"${field}\"]`);\n if (!cell) return null;\n\n return cell.textContent?.trim() ?? null;\n }\n\n /**\n * Get focused cell coordinates from DOM.\n * Used as fallback when SelectionPlugin has no selection.\n */\n #getFocusedCellFromDOM(target: HTMLElement): { row: number; col: number } | null {\n // Cells carry `data-field` + `data-row` (see `data-field-cache` was never a\n // real attribute). Body cells have `data-row`; header cells don't, so the\n // `data-row` guard below excludes headers.\n const cell = target.closest('.cell[data-field]') as HTMLElement | null;\n if (!cell) return null;\n\n const field = cell.dataset.field;\n const rowIndexStr = cell.dataset.row;\n if (!field || !rowIndexStr) return null;\n\n const row = parseInt(rowIndexStr, 10);\n if (isNaN(row)) return null;\n\n const col = this.columns.findIndex((c) => c.field === field);\n if (col === -1) return null;\n\n return { row, col };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the text representation of the current selection (or specified data)\n * without writing to the system clipboard.\n *\n * Useful for previewing what would be copied, or for feeding the text into\n * a custom UI (e.g., a \"copy with column picker\" dialog).\n *\n * @param options - Control which columns/rows to include\n * @returns Delimited text, or empty string if nothing to copy\n *\n * @example Get text for specific columns\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * const text = clipboard.getSelectionAsText({\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * console.log(text);\n * // \"Name\\tEmail\\nAlice\\talice@example.com\\n...\"\n * ```\n */\n getSelectionAsText(options?: CopyOptions): string {\n const { columns, rows, contains } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) return '';\n return this.#buildText(columns, rows, options, contains);\n }\n\n /**\n * Copy data to the system clipboard.\n *\n * Without options, copies the current selection (or entire grid if no selection).\n * With options, copies exactly the specified columns and/or rows — ideal for\n * \"copy with column picker\" workflows where the user selects rows first,\n * then chooses which columns to include via a dialog.\n *\n * @param options - Control which columns/rows to include\n * @returns The copied text\n *\n * @example Copy current selection (default)\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * await clipboard.copy();\n * ```\n *\n * @example Copy specific columns from specific rows\n * ```ts\n * // User selected rows in the grid, then picked columns in a dialog\n * const selectedRowIndices = [0, 3, 7];\n * const chosenColumns = ['name', 'department', 'salary'];\n * await clipboard.copy({\n * rowIndices: selectedRowIndices,\n * columns: chosenColumns,\n * includeHeaders: true,\n * });\n * ```\n */\n async copy(options?: CopyOptions): Promise<string> {\n const { columns, rows, contains } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) {\n return '';\n }\n\n const display = this.#buildDisplayGrid(columns, rows, options, contains);\n const text = this.#joinDisplayGrid(display, options);\n // Snapshot the RAW cell values (same column order as the text) for a\n // structured round-trip. Cloned so later row mutations don't change it.\n // Masked gaps between disjoint ranges stay blank here too, so a same-app\n // paste can't resurrect values the user never selected.\n const rawRows = rows.map((row, rowOffset) =>\n columns.map((col, colOffset) =>\n contains && !contains(rowOffset, colOffset) ? '' : cloneStructured(resolveCellValue(row, col)),\n ),\n );\n const fields = columns.map((col) => col.field);\n // Write BOTH text/plain (WYSIWYG for external targets) and text/html (a\n // table that also embeds the structured payload) so a same-app paste — even\n // cross-grid or cross-window — restores object cells losslessly.\n await copyToClipboard(text, buildClipboardHtml(display.header, display.rows, { v: 1, fields, rows: rawRows }));\n this.lastCopied = { text, timestamp: Date.now() };\n this.#internalClipboard = { text, rawRows, fields };\n this.emit<CopyDetail>('copy', {\n text,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n return text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n *\n * Convenience wrapper around {@link copy} for row-based workflows.\n * Supports non-contiguous row indices (e.g., `[0, 3, 7]`).\n *\n * @param indices - Array of row indices to copy\n * @param options - Additional copy options (columns, headers, etc.)\n * @returns The copied text\n *\n * @example\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * // Copy only rows 0 and 5, including just name and email columns\n * await clipboard.copyRows([0, 5], { columns: ['name', 'email'] });\n * ```\n */\n async copyRows(indices: number[], options?: Omit<CopyOptions, 'rowIndices'>): Promise<string> {\n if (indices.length === 0) return '';\n return this.copy({ ...options, rowIndices: indices });\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: 'cell' | 'row' | 'range';\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, CopyOptions, PasteDetail } from './types';\n"],"mappings":"AA0BA,IAAM,iBAAgB,IAAI,QAO1B,SAAS,EAAY,GACnB,MAAe,cAAR,GAA+B,gBAAR,GAAiC,cAAR,CACzD,CAOA,IAAM,iBAAiB,IAAI,IAU3B,SAAgB,EAAe,GAC7B,IAA2B,IAAvB,EAAM,QAAQ,KAAa,OAAO,KACtC,IAAI,EAAW,EAAe,IAAI,GAKlC,YAJiB,IAAb,IACF,EAAW,OAAO,OAAO,EAAM,MAAM,MACrC,EAAe,IAAI,EAAO,IAErB,CACT,CAyDA,SAAgB,EAAc,EAAc,GAC1C,GAAW,MAAP,EAAa,OACjB,MAAM,EAAO,EAAe,GACtB,EAAI,EACV,OAAa,OAAT,EAAsB,EAAY,QAAS,EAAY,EAAE,GACzD,OAAO,UAAU,eAAe,KAAK,EAAG,GAAe,EAAE,GAtD/D,SAA0B,EAAc,GACtC,IAAI,EAAM,EACV,IAAK,IAAI,EAAI,EAAG,EAAI,EAAK,OAAQ,IAAK,C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hB,CAAE,MAAK,MAChB,CA0BA,kBAAA,CAAmB,GACjB,MAAM,QAAE,EAAA,KAAS,EAAA,SAAM,GAAa,MAAK,EAAa,GACtD,OAAuB,IAAnB,EAAQ,QAAgC,IAAhB,EAAK,OAAqB,GAC/C,MAAK,EAAW,EAAS,EAAM,EAAS,EACjD,CA+BA,UAAM,CAAK,GACT,MAAM,QAAE,EAAA,KAAS,EAAA,SAAM,GAAa,MAAK,EAAa,GACtD,GAAuB,IAAnB,EAAQ,QAAgC,IAAhB,EAAK,OAC/B,MAAO,GAGT,MAAM,EAAU,MAAK,EAAkB,EAAS,EAAM,EAAS,GACzD,EAAO,MAAK,EAAiB,EAAS,GAKtC,EAAU,EAAK,IAAA,CAAK,EAAK,IAC7B,EAAQ,IAAA,CAAK,EAAK,IAChB,IAAa,EAAS,EAAW,GAAa,GAAK,EAAgB,EAAiB,EAAK,MAGvF,EAAS,EAAQ,IAAK,GAAQ,EAAI,OAYxC,aARM,EAAgB,EAAM,EAAmB,EAAQ,OAAQ,EAAQ,KAAM,CAAE,EAAG,EAAG,SAAQ,KAAM,KACnG,KAAK,WAAa,CAAE,OAAM,UAAW,KAAK,OAC1C,MAAK,EAAqB,CAAE,OAAM,UAAS,UAC3C,KAAK,KAAiB,OAAQ,CAC5B,OACA,SAAU,EAAK,OACf,YAAa,EAAQ,SAEhB,CACT,CAmBA,cAAM,CAAS,EAAmB,GAChC,OAAuB,IAAnB,EAAQ,OAAqB,GAC1B,KAAK,KAAK,IAAK,EAAS,WAAY,GAC7C,CAMA,WAAM,GACJ,MAAM,QFjsBV,iBACE,IACE,aAAa,UAAU,UAAU,UACnC,CAAA,MAEE,MAAO,EACT,CACF,CE0rBuB,GACnB,OAAK,EACE,EAAmB,EAAM,KAAK,QADnB,IAEpB,CAMA,aAAA,GACE,OAAO,KAAK,UACd"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../../../libs/grid/src/lib/core/internal/value-accessor.ts","../../../../../../libs/grid/src/lib/core/defaults.ts","../../../../../../libs/grid/src/lib/core/internal/diagnostics.ts","../../../../../../libs/grid/src/lib/core/internal/sanitize.ts","../../../../../../libs/grid/src/lib/core/plugin/base-plugin.ts","../../../../../../libs/grid/src/lib/plugins/shared/data-collection.ts","../../../../../../libs/grid/src/lib/plugins/clipboard/clipboard-payload.ts","../../../../../../libs/grid/src/lib/plugins/clipboard/copy.ts","../../../../../../libs/grid/src/lib/plugins/clipboard/paste.ts","../../../../../../libs/grid/src/lib/plugins/clipboard/types.ts","../../../../../../libs/grid/src/lib/plugins/clipboard/clipboard-plugin.ts"],"sourcesContent":["/**\n * Value Accessor Module\n *\n * Single source of truth for resolving a column's value from a row.\n *\n * Resolution precedence:\n * 1. `column.valueAccessor({ row, column, rowIndex })` — when defined\n * 2. `row[column.field]` — direct field read (default)\n *\n * Per-column escape hatches (`sortComparator`, `filterValue`) still take\n * precedence over the accessor — the accessor is the *default* value source,\n * never an override. See {@link BaseColumnConfig.valueAccessor}.\n *\n * Performance: results are memoized per (row identity, column field) using a\n * `WeakMap`. Row identity changes (immutable updates) invalidate naturally;\n * in-place mutations must call {@link invalidateAccessorCache} on the row.\n */\n\nimport type { ColumnConfig } from '../types';\n\n// Box-wrapped values let the cache-hit path do a SINGLE `Map.get` instead of\n// `has()` + `get()`. A truthy box means cache hit (even when the cached value\n// itself is `undefined` / `null` / `0` / `''`).\ninterface CacheBox {\n v: unknown;\n}\nconst accessorCache = new WeakMap<object, Map<string, CacheBox>>();\n\n// #region Nested dotted-path field access (issue #438)\n\n// Prototype-pollution guard applied to every path segment on read AND write.\n// Uses explicit `===` comparisons (not a Set lookup) so static analyzers\n// recognize the barrier guarding the assignments in `setByPath`/`writeCellField`.\nfunction isUnsafeKey(key: string): boolean {\n return key === '__proto__' || key === 'constructor' || key === 'prototype';\n}\n\n// Parsed dotted-path cache: field string → segments. Only **dotted** fields are\n// cached; a plain key is recognised by a single `indexOf` scan, which is cheaper\n// than hashing the string for a Map probe and — critically — keeps the cache\n// from growing without bound when a plugin mints synthetic field names at\n// runtime (PivotPlugin derives one column per distinct pivot value).\nconst fieldPathCache = new Map<string, readonly string[]>();\n\n/**\n * Parse a column `field` into path segments, or `null` when it is a plain\n * top-level key (contains no `.`). Dotted results are memoized.\n *\n * @param field - The column field key (may be a dotted path like `a.b.c`).\n * @returns Frozen segment array for dotted paths, else `null`.\n * @since 3.3.0\n */\nexport function parseFieldPath(field: string): readonly string[] | null {\n if (field.indexOf('.') === -1) return null;\n let segments = fieldPathCache.get(field);\n if (segments === undefined) {\n segments = Object.freeze(field.split('.'));\n fieldPathCache.set(field, segments);\n }\n return segments;\n}\n\n/**\n * Read a nested value from `row` by pre-parsed path segments. Returns\n * `undefined` on any nullish/non-object hop. Prototype-pollution safe.\n *\n * @since 3.3.0\n */\nexport function getByPath(row: unknown, path: readonly string[]): unknown {\n let cur = row as Record<string, unknown> | null | undefined;\n for (let i = 0; i < path.length; i++) {\n if (cur == null || typeof cur !== 'object') return undefined;\n const seg = path[i];\n if (isUnsafeKey(seg)) return undefined;\n cur = cur[seg] as Record<string, unknown>;\n }\n return cur;\n}\n\n/**\n * Write `value` into `row` at the location described by pre-parsed path\n * segments. Walks **existing** objects only — it does NOT fabricate missing\n * intermediates — and returns `true` only when the write happened.\n * Prototype-pollution safe (every segment is guarded).\n *\n * @since 3.3.0\n */\nexport function setByPath(row: unknown, path: readonly string[], value: unknown): boolean {\n if (row == null || typeof row !== 'object') return false;\n let cur = row as Record<string, unknown>;\n for (let i = 0; i < path.length - 1; i++) {\n const seg = path[i];\n if (isUnsafeKey(seg)) return false;\n const next = cur[seg];\n if (next == null || typeof next !== 'object') return false;\n cur = next as Record<string, unknown>;\n }\n const last = path[path.length - 1];\n if (isUnsafeKey(last)) return false;\n cur[last] = value;\n return true;\n}\n\n/**\n * Read the raw stored value for `field` from `row`, honoring nested dotted\n * paths — the non-accessor counterpart to {@link resolveCellValue}.\n *\n * Resolution rules (back-compat critical, see `grid-core.md` DECIDED #438):\n * 1. Plain field (no `.`) → direct `row[field]` (identical to legacy path),\n * except prototype-polluting keys (`__proto__`/`constructor`/`prototype`)\n * which return `undefined` — symmetric with {@link writeCellField}.\n * 2. Dotted field whose literal key is an **own property** of `row` → that\n * flat value wins (preserves synthetic-key rows that really store `'a.b'`).\n * 3. Otherwise → nested traversal via {@link getByPath}.\n *\n * @since 3.3.0\n */\nexport function readCellField(row: unknown, field: string): unknown {\n if (row == null) return undefined;\n const path = parseFieldPath(field);\n const r = row as Record<string, unknown>;\n if (path === null) return isUnsafeKey(field) ? undefined : r[field];\n if (Object.prototype.hasOwnProperty.call(r, field)) return r[field];\n return getByPath(r, path);\n}\n\n/**\n * A precompiled reader that extracts one column's raw value from a row.\n *\n * @since 3.4.0\n */\nexport type FieldReader = (row: unknown) => unknown;\n\n/**\n * Build a {@link FieldReader} for `field`, resolving the plain / unsafe /\n * dotted decision **once** instead of on every cell read.\n *\n * Hoist the reader out of any per-row loop (sort comparators, compiled filter\n * predicates, aggregators, export writers). Semantics are identical to\n * {@link readCellField}; only the dispatch is paid up front.\n *\n * @param field - The column field key (may be a dotted path like `a.b.c`).\n * @returns A single-argument reader closure.\n *\n * @example\n * ```typescript\n * const read = createFieldReader(column.field);\n * rows.sort((a, b) => compare(read(a), read(b)));\n * ```\n * @since 3.4.0\n */\nexport function createFieldReader(field: string): FieldReader {\n const path = parseFieldPath(field);\n if (path === null) {\n if (isUnsafeKey(field)) return () => undefined;\n return (row) => (row == null ? undefined : (row as Record<string, unknown>)[field]);\n }\n return (row) => {\n if (row == null) return undefined;\n const r = row as Record<string, unknown>;\n // A literal own key containing a dot wins over traversal (see readCellField).\n if (Object.prototype.hasOwnProperty.call(r, field)) return r[field];\n return getByPath(r, path);\n };\n}\n\n/**\n * Whether `field` is a plain, safe top-level key — i.e. `row[field]` is exactly\n * equivalent to {@link readCellField} and callers may inline the property read.\n *\n * Used by benchmarked hot loops (compiled filter predicates) that keep a\n * hand-inlined fast path and only fall back to a {@link FieldReader} for the\n * dotted/unsafe minority.\n *\n * @since 3.4.0\n */\nexport function isPlainField(field: string): boolean {\n return field.indexOf('.') === -1 && !isUnsafeKey(field);\n}\n\n/**\n * Write `value` into `row` for `field`, honoring nested dotted paths and the\n * same back-compat precedence as {@link readCellField}. Returns `true` when a\n * write occurred. Prototype-pollution safe.\n *\n * @since 3.3.0\n */\nexport function writeCellField(row: unknown, field: string, value: unknown): boolean {\n if (row == null || typeof row !== 'object') return false;\n const path = parseFieldPath(field);\n const r = row as Record<string, unknown>;\n if (path === null) {\n if (isUnsafeKey(field)) return false;\n r[field] = value;\n return true;\n }\n // A literal own key containing a dot wins over traversal (symmetric with\n // readCellField). Such a key always contains `.`, so it can never be an\n // unsafe prototype key.\n if (Object.prototype.hasOwnProperty.call(r, field)) {\n r[field] = value;\n return true;\n }\n return setByPath(r, path, value);\n}\n\n// #endregion\n\n/**\n * Resolve the cell value for a column, honoring `valueAccessor` if defined,\n * otherwise reading `row[column.field]` (with nested dotted-path support).\n *\n * @param row - The row object\n * @param column - The column definition\n * @param rowIndex - The visible row index (passed to accessor; defaults to -1)\n * @returns The resolved cell value\n *\n * @example\n * ```typescript\n * const value = resolveCellValue(row, column);\n * ```\n * @since 2.2.0\n */\nexport function resolveCellValue<TRow>(row: TRow, column: ColumnConfig<TRow>, rowIndex = -1): unknown {\n if (!column.valueAccessor) {\n return readCellField(row, column.field);\n }\n // Non-object rows (primitives, null) bypass the cache.\n if (typeof row !== 'object' || row === null) {\n return column.valueAccessor({ row, column, rowIndex });\n }\n // After the guard above, `row` is provably a non-null object. Single\n // assertion (no `as unknown as`) bridges the generic `TRow` to the WeakMap\n // key type; see `.github/instructions/typescript-conventions.instructions.md`.\n const rowKey = row as object;\n const key = column.field;\n let cellMap = accessorCache.get(rowKey);\n if (cellMap) {\n const box = cellMap.get(key);\n if (box !== undefined) return box.v;\n } else {\n cellMap = new Map();\n accessorCache.set(rowKey, cellMap);\n }\n const value = column.valueAccessor({ row, column, rowIndex });\n cellMap.set(key, { v: value });\n return value;\n}\n\n/**\n * Invalidate cached accessor values for a row (after in-place mutation),\n * a single (row, field) pair, or — when called with no argument — clear\n * the entire cache. Immutable updates auto-invalidate via row identity.\n *\n * Edit/transaction paths that mutate row objects in-place must call this.\n * @since 2.2.0\n */\nexport function invalidateAccessorCache(row?: object, field?: string): void {\n if (!row) {\n // WeakMap can't be cleared in O(1); the GC handles unreferenced rows.\n // For an explicit full reset, callers should mutate row identities instead.\n return;\n }\n if (!field) {\n accessorCache.delete(row);\n return;\n }\n accessorCache.get(row)?.delete(field);\n}\n\n/**\n * Build a `(value, row) => unknown` extractor compatible with\n * `filterValue`-style APIs from a column's `valueAccessor`. Returns `undefined`\n * when the column has no accessor.\n *\n * Used by FilteringPlugin to bridge the two API shapes without duplicating\n * cache lookups.\n */\nexport function accessorAsFilterValue<TRow>(\n column: ColumnConfig<TRow>,\n): ((value: unknown, row: TRow) => unknown) | undefined {\n if (!column.valueAccessor) return undefined;\n return (_value, row) => resolveCellValue(row, column);\n}\n","/**\n * Runtime default values for grid configuration.\n *\n * Kept out of `core/types.ts` so that file stays type-only apart from the two\n * enum-like consts whose `type` aliases are derived from them via `typeof`.\n * Import types from `./types`; import the values that back them from here.\n */\n\nimport type { A11yMessages, AnimationConfig, GridIcons } from './types';\n\n/**\n * Default English announcement messages.\n * Used when no custom messages are provided via {@link A11yConfig.messages}.\n * @since 2.0.0\n */\nexport const DEFAULT_A11Y_MESSAGES: Required<A11yMessages> = {\n sortApplied: (column, direction) => `Sorted by ${column}, ${direction}`,\n sortCleared: () => 'Sort cleared',\n filterApplied: (column) => `Filter applied on ${column}`,\n filterCleared: (column) => `Filter cleared from ${column}`,\n allFiltersCleared: () => 'All filters cleared',\n groupExpanded: (name, count) => `Group ${name} expanded, ${count} rows`,\n groupCollapsed: (name) => `Group ${name} collapsed`,\n selectionChanged: (count) => `${count} rows selected`,\n selectAllRows: () => 'Select all rows',\n selectRow: (rowIndex) => `Select row ${rowIndex + 1}`,\n columnSelected: (label) => `Column ${label} selected`,\n columnSelectionChanged: (count) => `${count} columns selected`,\n columnSelectionCleared: () => 'Column selection cleared',\n selectionAxisChanged: (toAxis) =>\n toAxis === 'column'\n ? 'Row selection cleared, column selection active'\n : 'Column selection cleared, row selection active',\n rangeSpanSelected: (axis, count) =>\n count === 1 ? `${axis === 'row' ? 'Row' : 'Column'} selected` : `${count} ${axis}s selected`,\n editingStarted: (rowIndex) => `Editing row ${rowIndex + 1}`,\n editingCommitted: (rowIndex) => `Row ${rowIndex + 1} saved`,\n dataLoaded: (count) => `${count} rows loaded`,\n};\n\n/**\n * Default animation configuration\n * @since 0.2.7\n */\nexport const DEFAULT_ANIMATION_CONFIG: Required<Omit<AnimationConfig, 'sort'>> = {\n mode: 'reduced-motion',\n duration: 200,\n easing: 'ease-out',\n};\n\n/**\n * Default icons used when not overridden. Most entries are short text/emoji;\n * `filter` and `filterActive` are empty strings because the actual rendering\n * is driven by the `--tbw-icon-filter[-active]-mask` CSS custom properties\n * (see `core/styles/variables.css`). Userland that wants an HTML/SVG fallback\n * via `gridConfig.icons.filter = '<svg…>'` is unaffected — that path overrides this default.\n * @since 0.1.1\n */\nexport const DEFAULT_GRID_ICONS: Required<GridIcons> = {\n expand: '▶',\n collapse: '▼',\n sortAsc: '▲',\n sortDesc: '▼',\n sortNone: '⇅',\n submenuArrow: '▶',\n dragHandle: '⋮⋮',\n toolPanel: '☰',\n filter: '',\n filterActive: '',\n print: '🖨️',\n};\n","/**\n * Centralized diagnostic messages for @toolbox-web/grid.\n *\n * Every user-facing warning, error, or info message in the grid has a unique\n * diagnostic code (e.g. `TBW001`). Each code maps to a section on the online\n * troubleshooting page, giving developers a direct link to resolution steps.\n *\n * ## Usage\n *\n * ```ts\n * import { MISSING_BREAKPOINT, warnDiagnostic, throwDiagnostic } from './diagnostics';\n *\n * // Warn with a code\n * warnDiagnostic(MISSING_BREAKPOINT, 'Set a breakpoint...', gridId);\n *\n * // Throw with a code\n * throwDiagnostic(MISSING_ROW_ID, 'Configure getRowId...', gridId);\n * ```\n *\n * Plugins should prefer `this.warn(MISSING_BREAKPOINT, message)` via BaseGridPlugin\n * instead of importing this module directly.\n *\n * @internal\n */\n\n// #region Grid Prefix\n\n/**\n * Build the `[tbw-grid]` or `[tbw-grid#my-id]` log prefix.\n * Pass `pluginName` for a scoped prefix like `[tbw-grid:SelectionPlugin]`.\n */\nexport function gridPrefix(gridId?: string, pluginName?: string): string {\n const id = gridId ? `#${gridId}` : '';\n const plugin = pluginName ? `:${pluginName}` : '';\n return `[tbw-grid${id}${plugin}]`;\n}\n\n// #endregion\n\n// #region Diagnostic Codes\n\n/**\n * Diagnostic codes used across the grid library.\n *\n * Each code is an individual export so that unused codes are tree-shaken\n * from bundles that don't reference them (esbuild can't tree-shake\n * properties from a single object).\n *\n * Naming: TBW + 3-digit number.\n * Ranges:\n * 001–019 Configuration validation (missing plugins, bad config)\n * 020–029 Plugin lifecycle (dependencies, incompatibilities, alias collapse)\n * 030–039 Feature registry\n * 040–049 Row operations (row ID, row mutations)\n * 050–059 Column operations (width, template)\n * 060–069 Rendering (callbacks, formatters, external views)\n * 070–079 Shell (tool panels, header/toolbar content)\n * 080–089 Editing & editors\n * 090–099 Print\n * 100–109 Clipboard\n * 110–119 Plugin-specific (responsive, undo-redo, grouping-columns)\n * 120–129 Style injection\n * 130–139 Attribute parsing\n * 140–149 DataSource / ServerSide\n */\n\n// --- Config validation (001–019) ---\n/** Column uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN = 'TBW001' as const;\n/** Grid config uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN_CONFIG = 'TBW002' as const;\n/** Plugin config rule violation (error severity). */\nexport const CONFIG_RULE_ERROR = 'TBW003' as const;\n/** Plugin config rule violation (warning severity). */\nexport const CONFIG_RULE_WARN = 'TBW004' as const;\n\n// --- Plugin lifecycle (020–029) ---\n/** Required plugin dependency is missing. */\nexport const MISSING_DEPENDENCY = 'TBW020' as const;\n/** Optional plugin dependency is missing. */\nexport const OPTIONAL_DEPENDENCY = 'TBW021' as const;\n/** Two loaded plugins are incompatible. */\nexport const INCOMPATIBLE_PLUGINS = 'TBW022' as const;\n/** Two plugin instances resolve to the same canonical name (alias collapse). */\nexport const PLUGIN_ALIAS_COLLAPSE = 'TBW023' as const;\n/** Error thrown inside a plugin event handler. */\nexport const PLUGIN_EVENT_ERROR = 'TBW024' as const;\n/** Conflicting config values found while merging alias-collapsed plugin instances. */\nexport const PLUGIN_ALIAS_CONFIG_CONFLICT = 'TBW025' as const;\n\n// --- Feature registry (030–039) ---\n/** Feature was re-registered (overwritten). */\nexport const FEATURE_REREGISTERED = 'TBW030' as const;\n/** Feature configured but not imported. */\nexport const FEATURE_NOT_IMPORTED = 'TBW031' as const;\n/** Feature depends on another feature that is not enabled. */\nexport const FEATURE_MISSING_DEP = 'TBW032' as const;\n\n// --- Row operations (040–049) ---\n/** Cannot determine row ID (no getRowId and no id property). */\nexport const MISSING_ROW_ID = 'TBW040' as const;\n/** Row with given ID not found. */\nexport const ROW_NOT_FOUND = 'TBW041' as const;\n\n// --- Column operations (050–059) ---\n/** Column has an invalid CSS width value. */\nexport const INVALID_COLUMN_WIDTH = 'TBW050' as const;\n\n// --- Rendering callbacks (060–069) ---\n/** rowClass callback threw an error. */\nexport const ROW_CLASS_ERROR = 'TBW060' as const;\n/** cellClass callback threw an error. */\nexport const CELL_CLASS_ERROR = 'TBW061' as const;\n/** Column format function threw an error. */\nexport const FORMAT_ERROR = 'TBW062' as const;\n/** External view mount() threw an error. */\nexport const VIEW_MOUNT_ERROR = 'TBW063' as const;\n/** External view event dispatch error. */\nexport const VIEW_DISPATCH_ERROR = 'TBW064' as const;\n\n// --- Shell (070–079) ---\n/** Tool panel missing required id. */\nexport const TOOL_PANEL_MISSING_ATTR = 'TBW070' as const;\n/** No tool panels registered. */\nexport const NO_TOOL_PANELS = 'TBW071' as const;\n/** Tool panel section not found. */\nexport const TOOL_PANEL_NOT_FOUND = 'TBW072' as const;\n/** Tool panel already registered. */\nexport const TOOL_PANEL_DUPLICATE = 'TBW073' as const;\n/** Header content already registered. */\nexport const HEADER_CONTENT_DUPLICATE = 'TBW074' as const;\n/** Toolbar content already registered. */\nexport const TOOLBAR_CONTENT_DUPLICATE = 'TBW075' as const;\n\n// --- Editing & editors (080–089) ---\n/** External editor mount() threw an error. */\nexport const EDITOR_MOUNT_ERROR = 'TBW080' as const;\n\n// --- Print (090–099) ---\n/** Print already in progress. */\nexport const PRINT_IN_PROGRESS = 'TBW090' as const;\n/** Grid not available for printing. */\nexport const PRINT_NO_GRID = 'TBW091' as const;\n/** Print operation failed. */\nexport const PRINT_FAILED = 'TBW092' as const;\n/** Multiple elements share the same grid ID (print isolation issue). */\nexport const PRINT_DUPLICATE_ID = 'TBW093' as const;\n\n// --- Clipboard (100–109) ---\n/** Clipboard API write failed. */\nexport const CLIPBOARD_FAILED = 'TBW100' as const;\n\n// --- Plugin-specific (110–119) ---\n/** ResponsivePlugin: no breakpoint configured. */\nexport const MISSING_BREAKPOINT = 'TBW110' as const;\n/** UndoRedoPlugin: transaction already in progress. */\nexport const TRANSACTION_IN_PROGRESS = 'TBW111' as const;\n/** UndoRedoPlugin: no transaction in progress. */\nexport const NO_TRANSACTION = 'TBW112' as const;\n/** GroupingColumnsPlugin: missing id or header on column group definition. */\nexport const COLUMN_GROUP_NO_ID = 'TBW113' as const;\n/** GroupingColumnsPlugin: conflicting columnGroups sources. */\nexport const COLUMN_GROUPS_CONFLICT = 'TBW114' as const;\n\n// --- Style injection (120–129) ---\n/** Failed to extract grid.css from document stylesheets. */\nexport const STYLE_EXTRACT_FAILED = 'TBW120' as const;\n/** Could not find grid.css in document.styleSheets. */\nexport const STYLE_NOT_FOUND = 'TBW121' as const;\n\n// --- Attribute parsing (130–139) ---\n/** Invalid JSON in an HTML attribute. */\nexport const INVALID_ATTRIBUTE_JSON = 'TBW130' as const;\n\n// --- DataSource / ServerSide (140–149) ---\n/** ServerSidePlugin: getRows() rejected. */\nexport const DATASOURCE_FETCH_ERROR = 'TBW140' as const;\n/** ServerSidePlugin: getChildRows() rejected. */\nexport const DATASOURCE_CHILD_FETCH_ERROR = 'TBW141' as const;\n/** ServerSidePlugin: getChildRows() not implemented but a plugin queried for children. */\nexport const DATASOURCE_NO_CHILD_HANDLER = 'TBW142' as const;\n/** ServerSidePlugin: concurrent request limit reached, request deferred. */\nexport const DATASOURCE_THROTTLED = 'TBW143' as const;\n\nexport type DiagnosticCode =\n | typeof MISSING_PLUGIN\n | typeof MISSING_PLUGIN_CONFIG\n | typeof CONFIG_RULE_ERROR\n | typeof CONFIG_RULE_WARN\n | typeof MISSING_DEPENDENCY\n | typeof OPTIONAL_DEPENDENCY\n | typeof INCOMPATIBLE_PLUGINS\n | typeof PLUGIN_ALIAS_COLLAPSE\n | typeof PLUGIN_EVENT_ERROR\n | typeof PLUGIN_ALIAS_CONFIG_CONFLICT\n | typeof FEATURE_REREGISTERED\n | typeof FEATURE_NOT_IMPORTED\n | typeof FEATURE_MISSING_DEP\n | typeof MISSING_ROW_ID\n | typeof ROW_NOT_FOUND\n | typeof INVALID_COLUMN_WIDTH\n | typeof ROW_CLASS_ERROR\n | typeof CELL_CLASS_ERROR\n | typeof FORMAT_ERROR\n | typeof VIEW_MOUNT_ERROR\n | typeof VIEW_DISPATCH_ERROR\n | typeof TOOL_PANEL_MISSING_ATTR\n | typeof NO_TOOL_PANELS\n | typeof TOOL_PANEL_NOT_FOUND\n | typeof TOOL_PANEL_DUPLICATE\n | typeof HEADER_CONTENT_DUPLICATE\n | typeof TOOLBAR_CONTENT_DUPLICATE\n | typeof EDITOR_MOUNT_ERROR\n | typeof PRINT_IN_PROGRESS\n | typeof PRINT_NO_GRID\n | typeof PRINT_FAILED\n | typeof PRINT_DUPLICATE_ID\n | typeof CLIPBOARD_FAILED\n | typeof MISSING_BREAKPOINT\n | typeof TRANSACTION_IN_PROGRESS\n | typeof NO_TRANSACTION\n | typeof COLUMN_GROUP_NO_ID\n | typeof COLUMN_GROUPS_CONFLICT\n | typeof STYLE_EXTRACT_FAILED\n | typeof STYLE_NOT_FOUND\n | typeof INVALID_ATTRIBUTE_JSON\n | typeof DATASOURCE_FETCH_ERROR\n | typeof DATASOURCE_CHILD_FETCH_ERROR\n | typeof DATASOURCE_NO_CHILD_HANDLER\n | typeof DATASOURCE_THROTTLED;\n\n// #endregion\n\n// #region Docs URL\n\nconst DOCS_BASE = 'https://toolboxjs.com/grid/errors';\n\n/** Build a direct link to the troubleshooting section for a code. */\nfunction docsUrl(code: DiagnosticCode): string {\n return `${DOCS_BASE}#${code.toLowerCase()}`;\n}\n\n// #endregion\n\n// #region Formatting\n\n/**\n * Format a diagnostic message with prefix, code, and docs link.\n *\n * Output format:\n * ```\n * [tbw-grid#my-id] TBW001: Your message here.\n *\n * → More info: https://toolboxjs.com/grid/errors#tbw001\n * ```\n */\nexport function formatDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): string {\n const prefix = gridPrefix(gridId, pluginName);\n return `${prefix} ${code}: ${message}\\n\\n → More info: ${docsUrl(code)}`;\n}\n\n// #endregion\n\n// #region Public API\n\n/**\n * Throw an error with a diagnostic code and docs link.\n * Use for configuration errors and API misuse that should halt execution.\n */\nexport function throwDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): never {\n throw new Error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a warning with a diagnostic code and docs link.\n * Use for recoverable issues the developer should fix.\n */\nexport function warnDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.warn(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a debug message with a diagnostic code and docs link.\n * Use for optional/soft dependency notifications — visible only when\n * the browser DevTools \"Verbose\" log level is enabled.\n */\nexport function debugDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.debug(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log an error with a diagnostic code and docs link.\n * Use for non-throwing errors (e.g., failed async operations).\n */\nexport function errorDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n// #endregion\n","// Centralized template expression evaluation & sanitization utilities.\n// Responsible for safely interpolating {{ }} expressions while blocking\n// access to dangerous globals / reflective capabilities.\nimport type { CompiledViewFunction, EvalContext } from '../types';\n\n// #region Constants\nconst EXPR_RE = /{{\\s*([^}]+)\\s*}}/g;\nconst EMPTY_SENTINEL = '__DG_EMPTY__';\nconst SAFE_EXPR = /^[\\w$. '?+\\-*/%:()!<>=,&|]+$/;\n\n// Forbidden identifiers built at runtime to avoid static analysis scanners\n// from flagging string literals (e.g. socket.dev \"network access\" / \"uses eval\").\n// Stored as reversed, pipe-delimited tokens — reversed back when constructing the regex.\nconst _F =\n '__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles'\n .split('|')\n .map((s) => s.split('').reverse().join(''));\nconst FORBIDDEN = new RegExp(`__(proto|defineGetter|defineSetter)|${_F.slice(3).join('|')}|this\\\\b`);\n// #endregion\n\n// #region HTML Sanitization\n\n/**\n * Escape a plain text string for safe insertion into HTML.\n * Converts special HTML characters to their entity equivalents.\n *\n * @param text - Plain text string to escape\n * @returns HTML-safe string\n */\nexport function escapeHtml(text: string): string {\n if (!text || typeof text !== 'string') return '';\n return text\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n/**\n * Tags that are considered dangerous and will be completely removed.\n * These can execute scripts, load external resources, or manipulate the page.\n */\nconst DANGEROUS_TAGS = new Set(\n 'script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing|math'.split(\n '|',\n ),\n);\n\n/**\n * Attributes that are considered dangerous - event handlers and data loading.\n */\nconst DANGEROUS_ATTR_PATTERN = /^on\\w+$/i;\n\n/**\n * Attributes that can contain URLs which might be javascript: or data: URIs.\n */\nconst URL_ATTRS = new Set('href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset'.split('|'));\n\n/**\n * Protocol patterns that are dangerous in URLs.\n */\nconst DANGEROUS_URL_PROTOCOL = /^\\s*(javascript|vbscript|data|blob):/i;\n\n/**\n * Sanitize an HTML string by removing dangerous tags and attributes.\n *\n * Prefer {@link setSanitizedHTML} wherever the result is destined for an\n * element: this function has to re-serialize the sanitized tree back to a\n * string, and the caller's `innerHTML =` then re-parses it. That\n * parse→serialize→parse round trip is the classic mutation-XSS vector, and it\n * costs a second parse. Use this overload only when a string is genuinely\n * required (e.g. the value is stored, compared, or handed to another API).\n *\n * @param html - Raw HTML string to sanitize\n * @returns Sanitized HTML string safe for innerHTML\n */\nexport function sanitizeHTML(html: string): string {\n if (!html || typeof html !== 'string') return '';\n\n // Fast path: if no HTML tags at all, return as-is (already safe)\n if (html.indexOf('<') === -1) return html;\n\n const template = document.createElement('template');\n template.innerHTML = html;\n\n sanitizeNode(template.content);\n\n return template.innerHTML;\n}\n\n/**\n * Parse and sanitize an HTML string into a detached {@link DocumentFragment}.\n *\n * This is the primitive {@link setSanitizedHTML} builds on, exposed for callers\n * that need to inspect or relocate the nodes before insertion.\n *\n * @param html - Raw HTML string to sanitize\n * @returns Fragment containing the sanitized nodes (empty for falsy input)\n */\nexport function sanitizeToFragment(html: string): DocumentFragment {\n const template = document.createElement('template');\n if (html && typeof html === 'string') {\n template.innerHTML = html;\n sanitizeNode(template.content);\n }\n return template.content;\n}\n\n/**\n * Replace an element's children with the sanitized parse of `html`.\n *\n * **This is the canonical sink for user-supplied markup** — cell/header/group\n * renderer string returns, `gridConfig.icons.*`, light-DOM tool panel fallback\n * content, and any new extension point that turns a user string into markup.\n * `textContent` is wrong here (it renders SVG icon strings as literal text) and\n * raw `innerHTML` is wrong (it is an XSS sink).\n *\n * Nodes are moved from the parse fragment rather than re-serialized, so the\n * sanitized tree is exactly what lands in the document.\n *\n * @param el - Element whose children are replaced\n * @param html - Raw HTML string to sanitize and insert\n */\nexport function setSanitizedHTML(el: Element, html: string): void {\n if (!html || typeof html !== 'string') {\n el.replaceChildren();\n return;\n }\n // Nothing for the parser to do: no markup and no entities to decode.\n if (html.indexOf('<') === -1 && html.indexOf('&') === -1) {\n el.textContent = html;\n return;\n }\n el.replaceChildren(sanitizeToFragment(html));\n}\n\n/**\n * Recursively sanitize a DOM node tree.\n */\nfunction sanitizeNode(root: DocumentFragment | Element): void {\n const toRemove: Element[] = [];\n\n // Use querySelectorAll to find all elements, then filter\n const elements = root.querySelectorAll('*');\n\n for (const el of elements) {\n const tagName = el.tagName.toLowerCase();\n\n // Check if tag is dangerous\n if (DANGEROUS_TAGS.has(tagName)) {\n toRemove.push(el);\n continue;\n }\n\n // SVG elements need special handling - they can contain script-like behavior\n if (tagName === 'svg' || el.namespaceURI === 'http://www.w3.org/2000/svg') {\n // Remove entire SVG if it has any suspicious attributes\n const hasDangerousContent = Array.from(el.attributes).some(\n (attr) => DANGEROUS_ATTR_PATTERN.test(attr.name) || attr.name === 'href' || attr.name === 'xlink:href',\n );\n if (hasDangerousContent) {\n toRemove.push(el);\n continue;\n }\n }\n\n // Check and remove dangerous attributes\n const attrsToRemove: string[] = [];\n for (const attr of el.attributes) {\n const attrName = attr.name.toLowerCase();\n\n // Event handlers (onclick, onerror, onload, etc.)\n if (DANGEROUS_ATTR_PATTERN.test(attrName)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // `is=` upgrades a plain tag into a registered customized built-in, so it\n // can smuggle behaviour past the tag-name check above.\n if (attrName === 'is') {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // URL attributes with dangerous protocols\n if (URL_ATTRS.has(attrName) && DANGEROUS_URL_PROTOCOL.test(attr.value)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // style attribute can contain expressions (IE) or url() with javascript:\n if (attrName === 'style' && /expression\\s*\\(|javascript:|behavior\\s*:/i.test(attr.value)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n }\n\n attrsToRemove.forEach((name) => el.removeAttribute(name));\n }\n\n // Remove dangerous elements (do this after iteration to avoid modifying during traversal)\n toRemove.forEach((el) => el.remove());\n}\n\n// #endregion\n\n// #region Template Evaluation\n\n// #region Safe Expression Evaluator\n// A minimal recursive-descent evaluator for the token set allowed by SAFE_EXPR.\n// Replaces `new Function()` to avoid dynamic code execution warnings from\n// static analysis tools (socket.dev, npm audit) while maintaining identical\n// functionality for expressions that pass the allowlist guards.\n//\n// Supported grammar (matching SAFE_EXPR = /^[\\w$. '?+\\-*/%:()!<>=,&|]+$/):\n// ternary → logicalOr ('?' ternary ':' ternary)?\n// logicalOr → logicalAnd ('||' logicalAnd)*\n// logicalAnd → equality ('&&' equality)*\n// equality → comparison (('==' | '!=' | '===' | '!==') comparison)*\n// comparison → additive (('<' | '>' | '<=' | '>=') additive)*\n// additive → multiplicative (('+' | '-') multiplicative)*\n// multiplicative → unary (('*' | '/' | '%') unary)*\n// unary → '!' unary | primary\n// primary → NUMBER | STRING | IDENT ('.' IDENT)? | '(' ternary ')'\n\ntype Token =\n { type: 'num'; v: number } | { type: 'str'; v: string } | { type: 'id'; v: string } | { type: 'op'; v: string };\n\nfunction tokenize(expr: string): Token[] | null {\n const tokens: Token[] = [];\n let i = 0;\n while (i < expr.length) {\n const ch = expr[i];\n if (ch === ' ') {\n i++;\n continue;\n }\n\n // Numbers\n if ((ch >= '0' && ch <= '9') || (ch === '.' && i + 1 < expr.length && expr[i + 1] >= '0' && expr[i + 1] <= '9')) {\n const start = i;\n while (i < expr.length && ((expr[i] >= '0' && expr[i] <= '9') || expr[i] === '.')) i++;\n tokens.push({ type: 'num', v: Number(expr.slice(start, i)) });\n continue;\n }\n\n // String literals (single-quoted only, per SAFE_EXPR)\n if (ch === \"'\") {\n let s = '';\n i++; // skip opening quote\n while (i < expr.length && expr[i] !== \"'\") s += expr[i++];\n if (i >= expr.length) return null; // unterminated\n i++; // skip closing quote\n tokens.push({ type: 'str', v: s });\n continue;\n }\n\n // Identifiers (value, row, row.field)\n if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '_' || ch === '$') {\n const start = i;\n while (i < expr.length && /[\\w$.]/.test(expr[i])) i++;\n tokens.push({ type: 'id', v: expr.slice(start, i) });\n continue;\n }\n\n // Multi-char operators\n if (i + 2 < expr.length) {\n const tri = expr.slice(i, i + 3);\n if (tri === '===' || tri === '!==') {\n tokens.push({ type: 'op', v: tri });\n i += 3;\n continue;\n }\n }\n if (i + 1 < expr.length) {\n const bi = expr.slice(i, i + 2);\n if (bi === '==' || bi === '!=' || bi === '<=' || bi === '>=' || bi === '&&' || bi === '||') {\n tokens.push({ type: 'op', v: bi });\n i += 2;\n continue;\n }\n }\n\n // Single-char operators\n if ('+-*/%<>!?:(),'.includes(ch)) {\n tokens.push({ type: 'op', v: ch });\n i++;\n continue;\n }\n\n return null; // unexpected character\n }\n return tokens;\n}\n\nfunction safeEval(expr: string, ctx: EvalContext): unknown {\n const toks = tokenize(expr);\n if (!toks) return undefined;\n const tokens: Token[] = toks;\n let pos = 0;\n\n function peek(): Token | undefined {\n return tokens[pos];\n }\n function advance(): Token {\n return tokens[pos++];\n }\n function match(type: string, val?: string): boolean {\n const t = peek();\n if (!t) return false;\n if (t.type !== type) return false;\n if (val !== undefined && t.v !== val) return false;\n return true;\n }\n\n function resolveId(name: string): unknown {\n if (name === 'value') return ctx.value;\n if (name.startsWith('row.')) {\n const key = name.slice(4);\n return ctx.row ? ctx.row[key] : undefined;\n }\n if (name.startsWith('typeDefault.')) {\n const key = name.slice('typeDefault.'.length);\n return ctx.typeDefault ? ctx.typeDefault[key] : undefined;\n }\n // bare 'row' reference\n if (name === 'row') return ctx.row;\n if (name === 'typeDefault') return ctx.typeDefault;\n return undefined;\n }\n\n function parseTernary(): unknown {\n const result = parseLogicalOr();\n if (match('op', '?')) {\n advance(); // consume '?'\n const consequent = parseTernary();\n if (!match('op', ':')) return undefined;\n advance(); // consume ':'\n const alternate = parseTernary();\n return result ? consequent : alternate;\n }\n return result;\n }\n\n function parseLogicalOr(): unknown {\n let left = parseLogicalAnd();\n while (match('op', '||')) {\n advance();\n left = left || parseLogicalAnd();\n }\n return left;\n }\n\n function parseLogicalAnd(): unknown {\n let left = parseEquality();\n while (match('op', '&&')) {\n advance();\n left = left && parseEquality();\n }\n return left;\n }\n\n function parseEquality(): unknown {\n let left = parseComparison();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '===') {\n advance();\n left = left === parseComparison();\n } else if (t.v === '!==') {\n advance();\n left = left !== parseComparison();\n } else if (t.v === '==') {\n advance();\n left = left == parseComparison();\n } else if (t.v === '!=') {\n advance();\n left = left != parseComparison();\n } else break;\n }\n return left;\n }\n\n function parseComparison(): unknown {\n let left = parseAdditive();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '<') {\n advance();\n left = (left as number) < (parseAdditive() as number);\n } else if (t.v === '>') {\n advance();\n left = (left as number) > (parseAdditive() as number);\n } else if (t.v === '<=') {\n advance();\n left = (left as number) <= (parseAdditive() as number);\n } else if (t.v === '>=') {\n advance();\n left = (left as number) >= (parseAdditive() as number);\n } else break;\n }\n return left;\n }\n\n function parseAdditive(): unknown {\n let left = parseMultiplicative();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '+') {\n advance();\n left = (left as number) + (parseMultiplicative() as number);\n } else if (t.v === '-') {\n advance();\n left = (left as number) - (parseMultiplicative() as number);\n } else break;\n }\n return left;\n }\n\n function parseMultiplicative(): unknown {\n let left = parseUnary();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '*') {\n advance();\n left = (left as number) * (parseUnary() as number);\n } else if (t.v === '/') {\n advance();\n left = (left as number) / (parseUnary() as number);\n } else if (t.v === '%') {\n advance();\n left = (left as number) % (parseUnary() as number);\n } else break;\n }\n return left;\n }\n\n function parseUnary(): unknown {\n if (match('op', '!')) {\n advance();\n return !parseUnary();\n }\n return parsePrimary();\n }\n\n function parsePrimary(): unknown {\n const t = peek();\n if (!t) return undefined;\n if (t.type === 'num') {\n advance();\n return t.v;\n }\n if (t.type === 'str') {\n advance();\n return t.v;\n }\n if (t.type === 'id') {\n advance();\n return resolveId(t.v as string);\n }\n if (t.type === 'op' && t.v === '(') {\n advance(); // consume '('\n const result = parseTernary();\n if (match('op', ')')) advance(); // consume ')'\n return result;\n }\n // Unary minus for negative numbers\n if (t.type === 'op' && t.v === '-') {\n advance();\n return -(parsePrimary() as number);\n }\n return undefined;\n }\n\n const result = parseTernary();\n // Ensure all tokens were consumed\n if (pos < tokens.length) return undefined;\n return result;\n}\n// #endregion\n\nexport function evalTemplateString(raw: string, ctx: EvalContext): string {\n if (!raw || raw.indexOf('{{') === -1) return raw; // fast path (no expressions)\n const parts: { expr: string; result: string }[] = [];\n const evaluated = raw.replace(EXPR_RE, (_m, expr) => {\n const res = evalSingle(expr, ctx);\n parts.push({ expr: expr.trim(), result: res });\n // The template markup is author-controlled; the interpolated data is not.\n // Escaping here stops row data from injecting elements or breaking out of\n // an attribute (sanitizeHTML downstream only strips *dangerous* markup).\n return res === EMPTY_SENTINEL ? res : escapeHtml(res);\n });\n const finalStr = postProcess(evaluated);\n // If every part evaluated to EMPTY_SENTINEL we treat this as intentionally blank.\n // If any expression was blocked due to forbidden token (EMPTY_SENTINEL) we *still* only output ''\n // but do not escalate to BLOCKED_SENTINEL unless the original contained explicit forbidden tokens.\n const allEmpty = parts.length && parts.every((p) => p.result === '' || p.result === EMPTY_SENTINEL);\n const hadForbidden = REFLECTIVE_RE.test(raw);\n if (hadForbidden || allEmpty) return '';\n return finalStr;\n}\n\nfunction evalSingle(expr: string, ctx: EvalContext): string {\n expr = (expr || '').trim();\n if (!expr) return EMPTY_SENTINEL;\n if (REFLECTIVE_RE.test(expr)) return EMPTY_SENTINEL;\n if (expr === 'value') return ctx.value == null ? EMPTY_SENTINEL : String(ctx.value);\n if (expr.startsWith('row.') && !/[()?]/.test(expr) && !expr.includes(':')) {\n const key = expr.slice(4);\n const v = ctx.row ? ctx.row[key] : undefined;\n return v == null ? EMPTY_SENTINEL : String(v);\n }\n if (expr.startsWith('typeDefault.') && !/[()?]/.test(expr) && !expr.includes(':')) {\n const key = expr.slice('typeDefault.'.length);\n const v = ctx.typeDefault ? ctx.typeDefault[key] : undefined;\n return v == null ? EMPTY_SENTINEL : String(v);\n }\n if (expr.length > 80) return EMPTY_SENTINEL;\n if (!SAFE_EXPR.test(expr) || FORBIDDEN.test(expr)) return EMPTY_SENTINEL;\n const dotChain = expr.match(/\\./g);\n if (dotChain && dotChain.length > 1) return EMPTY_SENTINEL;\n try {\n const out = safeEval(expr, ctx);\n const str = out == null ? '' : String(out);\n if (REFLECTIVE_RE.test(str)) return EMPTY_SENTINEL;\n return str || EMPTY_SENTINEL;\n } catch {\n return EMPTY_SENTINEL;\n }\n}\n// #endregion\n\n// #region Cell Scrubbing\n/** Pattern matching reflective/introspective APIs that must be stripped from output. */\nconst REFLECTIVE_RE = /Reflect|Proxy|ownKeys/;\n\nfunction postProcess(s: string): string {\n if (!s) return s;\n return s.replace(new RegExp(EMPTY_SENTINEL, 'g'), '').replace(/Reflect\\.[^<>{}\\s]+|\\bProxy\\b|ownKeys\\([^)]*\\)/g, '');\n}\n\nexport function finalCellScrub(cell: HTMLElement): void {\n if (!REFLECTIVE_RE.test(cell.textContent || '')) return;\n // First pass: clear only text nodes containing forbidden tokens\n for (const n of cell.childNodes) {\n if (n.nodeType === Node.TEXT_NODE && REFLECTIVE_RE.test(n.textContent || '')) n.textContent = '';\n }\n // If forbidden tokens persist in element nodes, nuke everything\n if (REFLECTIVE_RE.test(cell.textContent || '')) {\n cell.textContent = '';\n }\n}\n// #endregion\n\n// #region Template Compilation\nexport function compileTemplate(raw: string) {\n if (REFLECTIVE_RE.test(raw)) {\n const fn = (() => '') as CompiledViewFunction;\n fn.__blocked = true;\n return fn;\n }\n const fn = ((ctx: EvalContext) => evalTemplateString(raw, ctx)) as CompiledViewFunction;\n fn.__blocked = false;\n return fn;\n}\n// #endregion\n","/**\n * Base Grid Plugin Class\n *\n * All plugins extend this abstract class.\n * Plugins are instantiated per-grid and manage their own state.\n */\n\n// Injected by Vite at build time from package.json (same as grid.ts)\ndeclare const __GRID_VERSION__: string;\n\nimport type { HeaderContentDefinition, ToolPanelDefinition } from '../../plugins/shell/types';\nimport { DEFAULT_GRID_ICONS } from '../defaults';\nimport {\n type DiagnosticCode,\n PLUGIN_ALIAS_CONFIG_CONFLICT,\n formatDiagnostic,\n gridPrefix,\n} from '../internal/diagnostics';\nimport { setSanitizedHTML } from '../internal/sanitize';\nimport type {\n ColumnConfig,\n ColumnState,\n GridConfig,\n GridIcons,\n GridPlugin,\n IconValue,\n PluginNameMap,\n Translate,\n} from '../types';\n\n// Re-export shared plugin types for convenience\nexport type {\n AfterCellRenderContext,\n AfterRowRenderContext,\n CellClickEvent,\n CellCoords,\n CellEditor,\n CellMouseEvent,\n CellRenderer,\n ContextMenuItem,\n ContextMenuParams,\n GridElementRef,\n HeaderClickEvent,\n HeaderRenderer,\n KeyboardModifiers,\n PluginCellRenderContext,\n PluginQuery,\n RowClickEvent,\n ScrollEvent,\n} from './types';\n\nimport type {\n AfterCellRenderContext,\n AfterRowRenderContext,\n CellClickEvent,\n CellEditor,\n CellMouseEvent,\n CellRenderer,\n GridElementRef,\n HeaderClickEvent,\n HeaderRenderer,\n PluginQuery,\n RowClickEvent,\n ScrollEvent,\n} from './types';\n\n/**\n * Grid element interface for plugins.\n * Extends GridElementRef with plugin-specific methods.\n * Note: effectiveConfig is already available from GridElementRef.\n */\nexport interface GridElement extends GridElementRef {\n getPlugin<T extends GridPlugin>(PluginClass: new (...args: any[]) => T): T | undefined;\n getPluginByName<K extends string>(\n name: K,\n ): (K extends keyof PluginNameMap ? PluginNameMap[K] : BaseGridPlugin) | undefined;\n /**\n * Get a plugin's state by plugin name.\n * This is a loose-coupling method for plugins to access other plugins' state\n * without importing the plugin class directly.\n * @internal Plugin API\n */\n getPluginState?(name: string): unknown;\n\n // Focus Management\n /** Register an external DOM element as a logical focus container. @internal Plugin API */\n registerExternalFocusContainer?(el: Element): void;\n /** Unregister a previously registered external focus container. @internal Plugin API */\n unregisterExternalFocusContainer?(el: Element): void;\n /** Check whether focus is logically inside this grid (own DOM + external containers). @internal Plugin API */\n containsFocus?(node?: Node | null): boolean;\n}\n\n/**\n * Header render context for plugin header renderers.\n */\nexport interface PluginHeaderRenderContext {\n /** Column configuration */\n column: ColumnConfig;\n /** Column index */\n colIndex: number;\n}\n\n// ============================================================================\n// Plugin Dependency Types\n// ============================================================================\n\n/**\n * Declares a dependency on another plugin.\n *\n * @category Plugin Development\n * @example\n * ```typescript\n * export class UndoRedoPlugin extends BaseGridPlugin {\n * static readonly dependencies: PluginDependency[] = [\n * { name: 'editing', required: true },\n * ];\n * }\n * ```\n * @since 0.4.1\n */\nexport interface PluginDependency {\n /**\n * The name of the required plugin (matches the plugin's `name` property).\n * Use string names for loose coupling - avoids static imports.\n */\n name: string;\n\n /**\n * Whether this dependency is required (hard) or optional (soft).\n * - `true`: Plugin cannot function without it. Throws error if missing.\n * - `false`: Plugin works with reduced functionality. Silent if missing\n * (set {@link severity} to `'warn'` or `'info'` to opt into a message).\n * @default true\n */\n required?: boolean;\n\n /**\n * Explicit severity when this dependency is missing. Overrides the default\n * derived from {@link required}.\n * - `'error'`: throw (halts grid setup). Default when `required` is not `false`.\n * - `'warn'`: log a console warning and continue (development only).\n * - `'info'`: log a verbose console.debug message and continue (development only).\n *\n * When omitted, a missing hard dependency throws and a missing soft\n * dependency is silent — preserving backward-compatible behavior.\n * @since 2.16.0\n */\n severity?: 'error' | 'warn' | 'info';\n\n /**\n * Optional predicate that gates whether this dependency applies, evaluated\n * against the depending plugin's own resolved configuration (defaults merged\n * with user config). Return `false` to skip the dependency entirely.\n *\n * Lets a plugin require/recommend another plugin only under certain config\n * — e.g. a plugin that needs a tool-panel host only when its tool panel is\n * enabled. When omitted, the dependency always applies.\n * @example when: (cfg: PivotConfig) => cfg.showToolPanel === true\n * @since 2.16.0\n */\n when?: (pluginConfig: unknown) => boolean;\n\n /**\n * Human-readable reason for this dependency.\n * Shown in error/info messages to help users understand why.\n * @example \"UndoRedoPlugin needs EditingPlugin to track cell edits\"\n */\n reason?: string;\n}\n\n/**\n * Declares an incompatibility between plugins.\n * When both plugins are loaded, a warning is logged to help users understand the conflict.\n *\n * @category Plugin Development\n */\nexport interface PluginIncompatibility {\n /**\n * The name of the incompatible plugin (matches the plugin's `name` property).\n */\n name: string;\n\n /**\n * Human-readable reason for the incompatibility.\n * Should explain why the plugins conflict and any workarounds.\n * @example \"Both transform the entire row model in different ways\"\n */\n reason: string;\n}\n\n// ============================================================================\n// Plugin Query & Event Definitions\n// ============================================================================\n\n/**\n * Defines a query that a plugin can handle.\n * Other plugins or the grid can send this query type to retrieve data.\n *\n * @category Plugin Development\n *\n * @example\n * ```typescript\n * // In manifest\n * queries: [\n * {\n * type: 'canMoveColumn',\n * description: 'Check if a column can be moved/reordered',\n * },\n * ]\n *\n * // In plugin class\n * handleQuery(query: PluginQuery): unknown {\n * if (query.type === 'canMoveColumn') {\n * return this.canMoveColumn(query.context);\n * }\n * }\n * ```\n * @since 1.8.0\n */\nexport interface QueryDefinition {\n /**\n * The query type identifier (e.g., 'canMoveColumn', 'getContextMenuItems').\n * Should be unique across all plugins.\n */\n type: string;\n\n /**\n * Human-readable description of what the query does.\n */\n description?: string;\n}\n\n/**\n * Defines an event that a plugin can emit.\n * Other plugins can subscribe to these events via the Event Bus.\n *\n * @category Plugin Development\n *\n * @example\n * ```typescript\n * // In manifest\n * events: [\n * {\n * type: 'filter-change',\n * description: 'Emitted when filter criteria change',\n * },\n * ]\n *\n * // In plugin class - emit\n * this.emitPluginEvent('filter-change', { field: 'name', value: 'Alice' });\n *\n * // In another plugin - subscribe\n * this.on('filter-change', (detail) => console.log('Filter changed:', detail));\n * ```\n * @since 1.8.0\n */\nexport interface EventDefinition {\n /**\n * The event type identifier (e.g., 'filter-change', 'selection-change').\n * Used when emitting and subscribing to events.\n */\n type: string;\n\n /**\n * Human-readable description of what the event represents.\n */\n description?: string;\n\n /**\n * Whether this event is cancelable via `event.preventDefault()`.\n * @default false\n */\n cancelable?: boolean;\n}\n\n// ============================================================================\n// Plugin Manifest Types\n// ============================================================================\n\n/**\n * Defines a property that a plugin \"owns\" - used for configuration validation.\n * When this property is used without the owning plugin loaded, an error is thrown.\n *\n * @category Plugin Development\n */\nexport interface PluginPropertyDefinition {\n /** The property name on column or grid config */\n property: string;\n /** Whether this is a column-level or config-level property */\n level: 'column' | 'config';\n /** Human-readable description for error messages (e.g., 'the \"editable\" column property') */\n description: string;\n /** Import path hint for error messages (e.g., \"import { EditingPlugin } from '@toolbox-web/grid/plugins/editing';\") */\n importHint?: string;\n /** Custom check for whether property is considered \"used\" (default: truthy value check) */\n isUsed?: (value: unknown) => boolean;\n}\n\n/**\n * A configuration validation rule for detecting invalid/conflicting settings.\n * Plugins declare rules in their manifest; the validator executes them during grid initialization.\n *\n * @category Plugin Development\n * @template TConfig - The plugin's configuration type\n */\nexport interface PluginConfigRule<TConfig = unknown> {\n /** Rule identifier for debugging (e.g., 'selection/range-dblclick') */\n id: string;\n /** Severity: 'error' throws, 'warn' logs warning */\n severity: 'error' | 'warn';\n /** Human-readable message shown when rule is violated */\n message: string;\n /** Predicate returning true if the rule is VIOLATED (i.e., config is invalid) */\n check: (pluginConfig: TConfig) => boolean;\n}\n\n/**\n * Hook names that can have execution priority configured.\n *\n * @category Plugin Development\n */\nexport type HookName =\n | 'processColumns'\n | 'processConfig'\n | 'processRows'\n | 'afterStructuralRender'\n | 'afterRender'\n | 'afterCellRender'\n | 'afterRowRender'\n | 'onCellClick'\n | 'onCellMouseDown'\n | 'onCellMouseMove'\n | 'onCellMouseUp'\n | 'onHeaderClick'\n | 'onKeyDown'\n | 'onRowClick'\n | 'onScroll'\n | 'onScrollRender';\n\n/**\n * Static metadata about a plugin's capabilities and requirements.\n * Declared as a static property on plugin classes.\n *\n * @category Plugin Development\n * @template TConfig - The plugin's configuration type\n *\n * @example\n * ```typescript\n * export class MyPlugin extends BaseGridPlugin<MyConfig> {\n * static override readonly manifest: PluginManifest<MyConfig> = {\n * ownedProperties: [\n * { property: 'myProp', level: 'column', description: 'the \"myProp\" column property' },\n * ],\n * configRules: [\n * { id: 'my-plugin/invalid-combo', severity: 'warn', message: '...', check: (c) => c.a && c.b },\n * ],\n * };\n * readonly name = 'myPlugin';\n * }\n * ```\n * @since 1.1.0\n */\nexport interface PluginManifest<TConfig = unknown> {\n /**\n * Properties this plugin owns - validated by validate-config.ts.\n * If a user uses one of these properties without loading the plugin, an error is thrown.\n */\n ownedProperties?: PluginPropertyDefinition[];\n\n /**\n * Hook execution priority (higher = later, default 0).\n * Use negative values to run earlier, positive to run later.\n */\n hookPriority?: Partial<Record<HookName, number>>;\n\n /**\n * Configuration validation rules - checked during grid initialization.\n * Rules with severity 'error' throw, 'warn' logs to console.\n */\n configRules?: PluginConfigRule<TConfig>[];\n\n /**\n * Plugins that are incompatible with this plugin.\n * When both plugins are loaded together, a warning is shown.\n *\n * @example\n * ```typescript\n * incompatibleWith: [\n * { name: 'tree', reason: 'Both transform the entire row model in different ways' },\n * ],\n * ```\n */\n incompatibleWith?: PluginIncompatibility[];\n\n /**\n * Queries this plugin can handle.\n * Declares what query types this plugin responds to via `handleQuery()`.\n * This replaces the centralized PLUGIN_QUERIES approach with manifest-declared queries.\n *\n * @example\n * ```typescript\n * queries: [\n * { type: 'canMoveColumn', description: 'Check if a column can be moved' },\n * ],\n * ```\n */\n queries?: QueryDefinition[];\n\n /**\n * Events this plugin can emit.\n * Declares what event types other plugins can subscribe to via `on()`.\n *\n * @example\n * ```typescript\n * events: [\n * { type: 'filter-change', description: 'Emitted when filter criteria change' },\n * ],\n * ```\n */\n events?: EventDefinition[];\n\n /**\n * Whether this plugin's `processRows` hook injects or removes rows\n * (group headers, tree nodes, pivot aggregates, placeholders, etc.).\n *\n * When true, the core sorting module delegates to the render scheduler\n * instead of sorting `_rows` in-place, because `_rows` may contain\n * plugin-generated marker objects that would be corrupted by a direct sort.\n *\n * Plugins that only **filter** or **reorder** existing rows (e.g. Filtering,\n * MultiSort) should leave this unset or set it to `false`.\n */\n modifiesRowStructure?: boolean;\n}\n\n/** Convert camelCase icon key to kebab-case data-icon attribute value. */\nexport function toIconAttr(key: string): string {\n return key.replace(/([A-Z])/g, '-$1').toLowerCase();\n}\n\n/**\n * Abstract base class for all grid plugins.\n *\n * @category Plugin Development\n * @template TConfig - Configuration type for the plugin\n * @since 0.1.1\n */\nexport abstract class BaseGridPlugin<TConfig = unknown> implements GridPlugin {\n /**\n * Plugin dependencies - declare other plugins this one requires.\n *\n * Dependencies are validated when the plugin is attached.\n * Required dependencies throw an error if missing. Optional dependencies are\n * silent by default; set a {@link PluginDependency.severity} of `'warn'` or\n * `'info'` to opt into a development-only log.\n *\n * @example\n * ```typescript\n * static readonly dependencies: PluginDependency[] = [\n * { name: 'editing', required: true, reason: 'Tracks cell edits for undo/redo' },\n * { name: 'selection', required: false, reason: 'Enables selection-based undo' },\n * ];\n * ```\n */\n static readonly dependencies?: PluginDependency[];\n\n /**\n * Plugin manifest - declares owned properties, config rules, and hook priorities.\n *\n * This is read by the configuration validator to:\n * - Validate that required plugins are loaded when their properties are used\n * - Execute configRules to detect invalid/conflicting settings\n * - Order hook execution based on priority\n *\n * @example\n * ```typescript\n * static override readonly manifest: PluginManifest<MyConfig> = {\n * ownedProperties: [\n * { property: 'myProp', level: 'column', description: 'the \"myProp\" column property' },\n * ],\n * configRules: [\n * { id: 'myPlugin/conflict', severity: 'warn', message: '...', check: (c) => c.a && c.b },\n * ],\n * };\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static readonly manifest?: PluginManifest<any>;\n\n /** Unique plugin identifier (derived from class name by default) */\n abstract readonly name: string;\n\n /**\n * Alternative names for backward compatibility.\n * `getPluginByName()` matches against both `name` and `aliases`.\n * @internal\n */\n readonly aliases?: readonly string[];\n\n /**\n * Plugin version - defaults to grid version for built-in plugins.\n * Third-party plugins can override with their own semver.\n */\n readonly version: string = typeof __GRID_VERSION__ !== 'undefined' ? __GRID_VERSION__ : 'dev';\n\n /** CSS styles to inject via `document.adoptedStyleSheets` */\n readonly styles?: string;\n\n /** Custom cell renderers keyed by type name */\n readonly cellRenderers?: Record<string, CellRenderer>;\n\n /** Custom header renderers keyed by type name */\n readonly headerRenderers?: Record<string, HeaderRenderer>;\n\n /** Custom cell editors keyed by type name */\n readonly cellEditors?: Record<string, CellEditor>;\n\n /** The grid instance this plugin is attached to */\n protected grid!: GridElement;\n\n /** Plugin configuration - merged with defaults in attach() */\n protected config!: TConfig;\n\n /** User-provided configuration from constructor */\n protected readonly userConfig: Partial<TConfig>;\n\n /**\n * Plugin-level AbortController for event listener cleanup.\n * Created fresh in attach(), aborted in detach().\n * This ensures event listeners are properly cleaned up when plugins are re-attached.\n */\n #abortController?: AbortController;\n\n /**\n * Default configuration - subclasses should override this getter.\n * Note: This must be a getter (not property initializer) for proper inheritance\n * since property initializers run after parent constructor.\n */\n protected get defaultConfig(): Partial<TConfig> {\n return {};\n }\n\n constructor(config: Partial<TConfig> = {}) {\n this.userConfig = config;\n }\n\n /**\n * Effective configuration (defaults merged with user config), resolved\n * eagerly so it is available **before** {@link attach} runs. Dependency\n * validation happens before `attach()` merges {@link config}, so config\n * -conditional dependency `when` predicates evaluate against this getter.\n *\n * While attached, returns the already-merged {@link config}; otherwise\n * recomputes `defaultConfig` + `userConfig` fresh. `config` is intentionally\n * **not** trusted when detached because {@link detach} does not clear it — a\n * re-validated plugin would otherwise see stale config from a prior\n * attachment. The {@link attach}-managed abort controller is the\n * attached/detached signal.\n * @internal Plugin infrastructure (used by `validatePluginDependencies`).\n */\n get resolvedConfig(): TConfig {\n return (this.#abortController ? this.config : { ...this.defaultConfig, ...this.userConfig }) as TConfig;\n }\n\n /**\n * Merge user-supplied configuration from other plugin instances into this\n * plugin's `userConfig`. Used by `PluginManager.attachAll()`'s alias-collapse\n * pre-pass: when a consumer instantiates the same plugin more than once (or\n * under an alias name), only one instance is attached, and the other\n * instances' configs are folded in via this method.\n *\n * Merge rules (shallow):\n *\n * - Same key, **same value** → silent.\n * - Same key, **different values** (incl. function vs function) → throws\n * a diagnostic naming the conflicting key. Conflicting callbacks\n * (`canDrag`, `canDrop`, etc.) cannot be reconciled automatically.\n * - **Disjoint keys** → merged cleanly.\n *\n * Subclasses may override to implement custom deep-merge logic, but should\n * call `super.mergeConfigsFrom(others)` to inherit the conflict-detection.\n *\n * @internal Plugin infrastructure (used by `PluginManager.attachAll`).\n * @throws Error with diagnostic code `TBW025` when configs conflict.\n */\n mergeConfigsFrom(others: readonly BaseGridPlugin<TConfig>[]): void {\n if (others.length === 0) return;\n const merged = { ...this.userConfig } as Record<string, unknown>;\n const sources: Record<string, BaseGridPlugin<TConfig>> = {};\n for (const key of Object.keys(merged)) sources[key] = this;\n for (const other of others) {\n const otherConfig = other.userConfig as Record<string, unknown>;\n for (const [key, value] of Object.entries(otherConfig)) {\n if (value === undefined) continue;\n if (!(key in merged)) {\n merged[key] = value;\n sources[key] = other;\n continue;\n }\n if (merged[key] === value) continue;\n // Conflict\n const ownerA = sources[key]?.constructor.name ?? this.constructor.name;\n const ownerB = other.constructor.name;\n const code = formatDiagnostic(\n PLUGIN_ALIAS_CONFIG_CONFLICT,\n `Cannot merge plugin configs for \"${this.name}\": conflicting value for \"${key}\" supplied by both ${ownerA} and ${ownerB}. Pass the option on a single instance, or remove the duplicate.`,\n undefined,\n this.name,\n );\n throw new Error(code);\n }\n }\n // Mutate userConfig in place so re-attach picks it up via attach().\n // `userConfig` is declared `readonly` to prevent reassigning the binding,\n // but the object's own properties are intentionally mutable for this\n // alias-collapse pre-pass. A single cast to a record is enough — no\n // `as unknown as` double-cast needed.\n Object.assign(this.userConfig as Record<string, unknown>, merged);\n }\n\n /**\n * Replace this plugin's `userConfig` with a freshly-resolved sibling\n * instance's config. Used by the grid's per-grid feature-instance gate\n * (`#initializePlugins`): when a feature is re-resolved across a config\n * change, the **existing** instance is reused — so its accumulated state\n * survives — but it must adopt the latest `gridConfig.features.<name>`\n * value. Unlike {@link mergeConfigsFrom}, this is last-write-wins with no\n * conflict detection: the re-resolved instance is authoritative.\n *\n * `attach()` recomputes {@link config} from `userConfig`, so updating\n * `userConfig` here is enough for the reused instance to pick up the new\n * config on its next attach during the same `#initializePlugins` pass.\n *\n * @internal Plugin infrastructure (used by the grid feature gate).\n */\n refreshUserConfigFrom(other: BaseGridPlugin<TConfig>): void {\n const target = this.userConfig as Record<string, unknown>;\n // Snapshot the source BEFORE clearing `target`. A feature factory may\n // store the consumer's config object by reference (e.g. `new\n // ContextMenuPlugin(config)`), and a consumer that passes the *same* config\n // object across re-resolutions (common when `gridConfig` is a recomputed\n // Angular `computed()`) makes `this.userConfig === other.userConfig`.\n // Without this snapshot, the `delete` loop below would empty that shared\n // object first, then `Object.assign` would copy back nothing — silently\n // wiping the config and falling back to plugin defaults. (#contextMenu)\n const source = { ...(other.userConfig as Record<string, unknown>) };\n for (const key of Object.keys(target)) delete target[key];\n Object.assign(target, source);\n }\n\n /**\n * Called when the plugin is attached to a grid.\n * Override to set up event listeners, initialize state, etc.\n *\n * @example\n * ```ts\n * attach(grid: GridElement): void {\n * super.attach(grid);\n * // Set up document-level listeners with auto-cleanup\n * document.addEventListener('keydown', this.handleEscape, {\n * signal: this.disconnectSignal\n * });\n * }\n * ```\n */\n attach(grid: GridElement): void {\n // Abort any previous abort controller (in case of re-attach without detach)\n this.#abortController?.abort();\n // Create fresh abort controller for this attachment\n this.#abortController = new AbortController();\n\n this.grid = grid;\n // Merge config here (after subclass construction is complete)\n this.config = { ...this.defaultConfig, ...this.userConfig } as TConfig;\n }\n\n /**\n * Called when the plugin is detached from a grid.\n * Override to clean up event listeners, timers, etc.\n *\n * @example\n * ```ts\n * detach(): void {\n * // Clean up any state not handled by disconnectSignal\n * this.selectedRows.clear();\n * this.cache = null;\n * }\n * ```\n */\n detach(): void {\n // Abort the plugin's abort controller to clean up all event listeners\n // registered with { signal: this.disconnectSignal }\n this.#abortController?.abort();\n this.#abortController = undefined;\n // Override in subclass for additional cleanup\n }\n\n /**\n * Called when another plugin is attached to the same grid.\n * Use for inter-plugin coordination, e.g., to integrate with new plugins.\n *\n * @param name - The name of the plugin that was attached\n * @param plugin - The plugin instance (for direct access if needed)\n *\n * @example\n * ```ts\n * onPluginAttached(name: string, plugin: BaseGridPlugin): void {\n * if (name === 'selection') {\n * // Integrate with selection plugin\n * this.selectionPlugin = plugin as SelectionPlugin;\n * }\n * }\n * ```\n */\n onPluginAttached?(name: string, plugin: BaseGridPlugin): void;\n\n /**\n * Called when another plugin is detached from the same grid.\n * Use to clean up inter-plugin references.\n *\n * @param name - The name of the plugin that was detached\n *\n * @example\n * ```ts\n * onPluginDetached(name: string): void {\n * if (name === 'selection') {\n * this.selectionPlugin = undefined;\n * }\n * }\n * ```\n */\n onPluginDetached?(name: string): void;\n\n /**\n * Get another plugin instance from the same grid.\n * Use for inter-plugin communication.\n *\n * **Prefer {@link BaseGridPlugin.grid grid.getPluginByName()}** when you don't need the class import.\n *\n * @example\n * ```ts\n * // Preferred: by name\n * const selection = this.grid?.getPluginByName('selection');\n *\n * // Alternative: by class\n * const selection = this.getPlugin(SelectionPlugin);\n * if (selection) {\n * const selectedRows = selection.getSelectedRows();\n * }\n * ```\n */\n protected getPlugin<T extends BaseGridPlugin>(PluginClass: new (...args: any[]) => T): T | undefined {\n return this.grid?.getPlugin(PluginClass);\n }\n\n /**\n * Emit a custom event from the grid.\n */\n protected emit<T>(eventName: string, detail: T): void {\n this.grid?.dispatchEvent?.(new CustomEvent(eventName, { detail, bubbles: true }));\n }\n\n /**\n * Emit a cancelable custom event from the grid.\n * @returns `true` if the event was cancelled (preventDefault called), `false` otherwise\n */\n protected emitCancelable<T>(eventName: string, detail: T): boolean {\n const event = new CustomEvent(eventName, { detail, bubbles: true, cancelable: true });\n this.grid?.dispatchEvent?.(event);\n return event.defaultPrevented;\n }\n\n // =========================================================================\n // Event Bus - Plugin-to-Plugin Communication\n // =========================================================================\n\n /**\n * Subscribe to an event from another plugin.\n * The subscription is automatically cleaned up when this plugin is detached.\n *\n * @category Plugin Development\n * @param eventType - The event type to listen for (e.g., 'filter-change')\n * @param callback - The callback to invoke when the event is emitted\n *\n * @example\n * ```typescript\n * // In attach() or other initialization\n * this.on('filter-change', (detail) => {\n * console.log('Filter changed:', detail);\n * });\n * ```\n */\n protected on<T = unknown>(eventType: string, callback: (detail: T) => void): void {\n this.grid?._pluginManager?.subscribe(this, eventType, callback as (detail: unknown) => void);\n }\n\n /**\n * Unsubscribe from a plugin event.\n *\n * @category Plugin Development\n * @param eventType - The event type to stop listening for\n *\n * @example\n * ```typescript\n * this.off('filter-change');\n * ```\n */\n protected off(eventType: string): void {\n this.grid?._pluginManager?.unsubscribe(this, eventType);\n }\n\n /**\n * Emit an event to other plugins via the Event Bus.\n * This is for inter-plugin communication only; it does NOT dispatch DOM events.\n * Use `emit()` to dispatch DOM events that external consumers can listen to.\n *\n * @category Plugin Development\n * @param eventType - The event type to emit (should be declared in manifest.events)\n * @param detail - The event payload\n *\n * @example\n * ```typescript\n * // Emit to other plugins (not DOM)\n * this.emitPluginEvent('filter-change', { field: 'name', value: 'Alice' });\n *\n * // For DOM events that consumers can addEventListener to:\n * this.emit('filter-change', { field: 'name', value: 'Alice' });\n * ```\n */\n protected emitPluginEvent<T>(eventType: string, detail: T): void {\n this.grid?._pluginManager?.emitPluginEvent(eventType, detail);\n }\n\n /**\n * Emit an event to **both** the plugin Event Bus (for inter-plugin communication)\n * **and** the DOM (for external consumers via `addEventListener`).\n *\n * Use this when a state change is relevant to both other plugins and external\n * consumers. For example, `sort-change` needs to invalidate Selection (plugin bus)\n * and notify the host application (DOM event).\n *\n * @category Plugin Development\n * @param eventType - The event type to broadcast\n * @param detail - The event payload\n *\n * @example\n * ```typescript\n * // Notify both plugins and consumers of a sort change\n * this.broadcast('sort-change', { sortModel: [...this.sortModel] });\n * ```\n */\n protected broadcast<T>(eventType: string, detail: T): void {\n this.emitPluginEvent(eventType, detail);\n this.emit(eventType, detail);\n }\n\n /**\n * Run a yes/no plugin query and reduce the responses to a single boolean.\n *\n * `grid.query()` always returns an **array** of responses (empty when no\n * plugin handles the query), and `[]` is truthy in JavaScript — so testing\n * the raw result directly (`if (grid.query(...))`) is always `true` and\n * silently takes the \"some plugin said yes\" branch even when nothing\n * answered. Always route boolean queries through this helper.\n *\n * @category Plugin Development\n * @param type - The query type to dispatch\n * @param context - Optional query context passed to the handlers\n * @returns `true` only when at least one plugin answered truthily\n *\n * @example\n * ```typescript\n * if (this.queryBoolean('datasource:is-active')) {\n * // A ServerSide data source really is installed\n * }\n * ```\n * @since 3.4.0\n */\n protected queryBoolean(type: string, context: unknown = null): boolean {\n const responses = this.grid?.query?.(type, context);\n // Tolerate hosts/tests that hand back a bare value instead of the array.\n return Array.isArray(responses) ? responses.some(Boolean) : !!responses;\n }\n\n /**\n * Request a re-render of the grid.\n * Uses ROWS phase - does NOT trigger processColumns hooks.\n */\n protected requestRender(): void {\n this.grid?.requestRender?.();\n }\n\n /**\n * Request a columns re-render of the grid.\n * Uses COLUMNS phase - triggers processColumns hooks.\n * Use this when your plugin needs to reprocess column configuration.\n */\n protected requestColumnsRender(): void {\n (this.grid as { requestColumnsRender?: () => void })?.requestColumnsRender?.();\n }\n\n /**\n * Request a re-render and restore focus styling afterward.\n * Use this when a plugin action (like expand/collapse) triggers a render\n * but needs to maintain keyboard navigation focus.\n */\n protected requestRenderWithFocus(): void {\n this.grid?.requestRenderWithFocus?.();\n }\n\n /**\n * Request a lightweight style update without rebuilding DOM.\n * Use this instead of requestRender() when only CSS classes need updating.\n */\n protected requestAfterRender(): void {\n this.grid?.requestAfterRender?.();\n }\n\n /**\n * Re-render visible rows without rebuilding the row model or recalculating geometry.\n * Use this when row data has been updated in-place (e.g., server-side block loads)\n * and only the visible viewport needs to re-render.\n */\n protected requestVirtualRefresh(): void {\n this.grid?.requestVirtualRefresh?.();\n }\n\n /**\n * Get the current rows from the grid.\n */\n protected get rows(): any[] {\n return this.grid?.rows ?? [];\n }\n\n /**\n * Get the original unfiltered/unprocessed rows from the grid.\n * Use this when you need all source data regardless of active filters.\n */\n protected get sourceRows(): any[] {\n return this.grid?.sourceRows ?? [];\n }\n\n /**\n * Get the current columns from the grid.\n */\n protected get columns(): ColumnConfig[] {\n return this.grid?.columns ?? [];\n }\n\n /**\n * Get only visible columns from the grid (excludes hidden).\n * Use this for rendering that needs to match the grid template.\n */\n protected get visibleColumns(): ColumnConfig[] {\n return this.grid?._visibleColumns ?? [];\n }\n\n /**\n * Get the grid as an HTMLElement for direct DOM operations.\n * Use sparingly - prefer the typed GridElementRef API when possible.\n *\n * @example\n * ```ts\n * const width = this.gridElement.clientWidth;\n * this.gridElement.classList.add('my-plugin-active');\n * ```\n */\n protected get gridElement(): HTMLElement {\n return this.grid?._hostElement;\n }\n\n /**\n * Get the disconnect signal for event listener cleanup.\n * This signal is aborted when the grid disconnects from the DOM.\n * Use this when adding event listeners that should be cleaned up automatically.\n *\n * Best for:\n * - Document/window-level listeners added in attach()\n * - Listeners on the grid element itself\n * - Any listener that should persist across renders\n *\n * Not needed for:\n * - Listeners on elements created in afterRender() (removed with element)\n *\n * @example\n * element.addEventListener('click', handler, { signal: this.disconnectSignal });\n * document.addEventListener('keydown', handler, { signal: this.disconnectSignal });\n */\n protected get disconnectSignal(): AbortSignal {\n // Return the plugin's own abort signal for proper cleanup on detach/re-attach\n // Falls back to grid's signal if plugin's controller not yet created\n return this.#abortController?.signal ?? this.grid?.disconnectSignal;\n }\n\n /**\n * Get the grid-level icons configuration.\n * Returns merged icons (user config + defaults).\n */\n protected get gridIcons(): Required<GridIcons> {\n const userIcons = this.grid?.gridConfig?.icons ?? {};\n return { ...DEFAULT_GRID_ICONS, ...userIcons };\n }\n\n /**\n * Resolve a user-visible string from {@link GridConfig.locale}, falling back to\n * the English default supplied at the call site.\n *\n * The fallback is passed inline rather than read from a shipped default map so\n * that a plugin's strings live in the plugin's own chunk.\n *\n * @param key - Namespaced message id, e.g. `'filter.apply'`.\n * @param fallback - English text used when the key is not overridden.\n * @since 3.5.0\n *\n * @example\n * ```ts\n * applyBtn.textContent = this.t('filter.apply', 'Apply');\n * ```\n */\n protected t(key: string, fallback: string): string {\n return this.grid?.effectiveConfig?.locale?.[key] ?? fallback;\n }\n\n /**\n * A bound `t()` suitable for handing to standalone renderer\n * helpers and public renderer callbacks.\n * @since 3.5.0\n */\n protected get translate(): Translate {\n return (key, fallback) => this.t(key, fallback);\n }\n\n // #region Animation Helpers\n\n /**\n * Check if animations are enabled at the grid level.\n * Respects gridConfig.animation.mode and the CSS variable set by the grid.\n *\n * Plugins should use this to skip animations when:\n * - Animation mode is 'off' or `false`\n * - User prefers reduced motion and mode is 'reduced-motion' (default)\n *\n * @example\n * ```ts\n * private get animationStyle(): 'slide' | 'fade' | false {\n * if (!this.isAnimationEnabled) return false;\n * return this.config.animation ?? 'slide';\n * }\n * ```\n */\n protected get isAnimationEnabled(): boolean {\n const mode = this.grid?.effectiveConfig?.animation?.mode ?? 'reduced-motion';\n\n // Explicit off = disabled\n if (mode === false || mode === 'off') return false;\n\n // Explicit on = always enabled\n if (mode === true || mode === 'on') return true;\n\n // reduced-motion: check CSS variable (set by grid based on media query)\n const host = this.gridElement;\n if (host) {\n const enabled = getComputedStyle(host).getPropertyValue('--tbw-animation-enabled').trim();\n return enabled !== '0';\n }\n\n return true; // Default to enabled\n }\n\n /**\n * Get the animation duration in milliseconds from CSS variable.\n * Falls back to 200ms if not set.\n *\n * Plugins can use this for their animation timing to stay consistent\n * with the grid-level animation.duration setting.\n *\n * @example\n * ```ts\n * element.animate(keyframes, { duration: this.animationDuration });\n * ```\n */\n protected get animationDuration(): number {\n const host = this.gridElement;\n if (host) {\n const durationStr = getComputedStyle(host).getPropertyValue('--tbw-animation-duration').trim();\n const parsed = parseInt(durationStr, 10);\n if (!isNaN(parsed)) return parsed;\n }\n return 200; // Default\n }\n\n // #endregion\n\n /**\n * Set an icon on an element using the CSS-first hybrid approach.\n *\n * Sets `data-icon` for CSS pseudo-element rendering and `data-expanded` for\n * expand/collapse toggle elements. Only injects DOM content when a JS override\n * is present (via `gridConfig.icons` or `pluginOverride`), which naturally\n * suppresses the CSS `::before` via the `:empty` selector.\n *\n * @param element - The element to set the icon on\n * @param iconKey - The icon key in GridIcons (e.g., 'expand', 'collapse')\n * @param pluginOverride - Optional plugin-level override (string or HTMLElement)\n */\n protected setIcon(element: HTMLElement, iconKey: keyof GridIcons, pluginOverride?: IconValue): void {\n // Set data-icon attribute for CSS targeting (always)\n element.dataset.icon = toIconAttr(iconKey);\n\n // Set data-expanded for toggle elements (tree, group, master-detail)\n if (iconKey === 'collapse') {\n element.dataset.expanded = '';\n } else if (iconKey === 'expand') {\n delete element.dataset.expanded;\n }\n\n // Resolve JS-only icon (returns undefined when CSS default should be used)\n const jsIcon = this.#resolveJsIcon(iconKey, pluginOverride);\n\n if (jsIcon !== undefined) {\n // JS override: inject content (suppresses CSS ::before via :empty)\n if (typeof jsIcon === 'string') {\n setSanitizedHTML(element, jsIcon);\n } else if (jsIcon instanceof HTMLElement) {\n element.replaceChildren(jsIcon.cloneNode(true));\n }\n } else {\n // CSS path: ensure element is empty so ::before renders\n element.innerHTML = '';\n }\n }\n\n /**\n * Resolve JS-only icon override. Returns undefined if CSS default should render.\n * Only returns a value when the user explicitly set gridConfig.icons[key] or\n * the plugin passed an override.\n */\n #resolveJsIcon(iconKey: keyof GridIcons, pluginOverride?: IconValue): IconValue | undefined {\n if (pluginOverride !== undefined) return pluginOverride;\n return this.grid?.gridConfig?.icons?.[iconKey];\n }\n\n /**\n * Create or replace a sort indicator on a header cell.\n *\n * Handles the full lifecycle: removes any existing indicator, creates a new\n * `<span part=\"sort-indicator\" class=\"sort-indicator\">` with the appropriate\n * icon, sets `aria-sort` / `data-sort` attributes, and inserts it before the\n * filter button or resize handle.\n *\n * Plugins decide **which** cells and **when** — this method handles **how**.\n *\n * @param cell - The header cell element\n * @param direction - `'asc'` | `'desc'` for sorted, `null` for unsorted idle state\n * @returns The created indicator element (useful for appending badges, etc.)\n */\n protected updateSortIndicator(cell: Element, direction: 'asc' | 'desc' | null): HTMLElement {\n // Remove any existing indicator (core uses part, plugins use class)\n cell.querySelector('[part~=\"sort-indicator\"], .sort-indicator')?.remove();\n\n const indicator = document.createElement('span');\n indicator.setAttribute('part', 'sort-indicator');\n indicator.className = 'sort-indicator';\n\n if (direction) {\n cell.setAttribute('aria-sort', direction === 'asc' ? 'ascending' : 'descending');\n cell.setAttribute('data-sort', direction);\n this.setIcon(indicator, direction === 'asc' ? 'sortAsc' : 'sortDesc');\n } else {\n cell.setAttribute('aria-sort', 'none');\n cell.removeAttribute('data-sort');\n this.setIcon(indicator, 'sortNone');\n }\n\n // Insert before filter button or resize handle to maintain DOM order\n const insertBefore = cell.querySelector('.tbw-filter-btn') ?? cell.querySelector('.resize-handle');\n if (insertBefore) {\n cell.insertBefore(indicator, insertBefore);\n } else {\n cell.appendChild(indicator);\n }\n\n return indicator;\n }\n\n /**\n * Log a warning with an optional diagnostic code.\n *\n * When a diagnostic code is provided, the message is formatted with the code\n * and a link to the troubleshooting docs.\n *\n * @example\n * ```ts\n * this.warn('Something went wrong'); // plain\n * this.warn(MISSING_BREAKPOINT, 'Set a breakpoint'); // with code + docs link\n * ```\n */\n protected warn(message: string): void;\n protected warn(code: DiagnosticCode, message: string): void;\n protected warn(codeOrMessage: DiagnosticCode | string, message?: string): void {\n if (message !== undefined) {\n // Called with (code, message)\n console.warn(formatDiagnostic(codeOrMessage as DiagnosticCode, message, this.gridElement.id, this.name));\n } else {\n // Called with (message) — plain warning, no diagnostic code\n console.warn(`${gridPrefix(this.gridElement.id, this.name)} ${codeOrMessage}`);\n }\n }\n\n /**\n * Throw an error with a diagnostic code and docs link.\n * Use for configuration errors and API misuse that should halt execution.\n */\n protected throwDiagnostic(code: DiagnosticCode, message: string): never {\n throw new Error(formatDiagnostic(code, message, this.gridElement.id, this.name));\n }\n\n // #region Lifecycle Hooks\n\n /**\n * Transform rows before rendering.\n * Called during each render cycle before rows are rendered to the DOM.\n * Use this to filter, sort, or add computed properties to rows.\n *\n * @param rows - The current rows array (readonly to encourage returning a new array)\n * @returns The modified rows array to render\n *\n * @example\n * ```ts\n * processRows(rows: readonly any[]): any[] {\n * // Filter out hidden rows\n * return rows.filter(row => !row._hidden);\n * }\n * ```\n *\n * @example\n * ```ts\n * processRows(rows: readonly any[]): any[] {\n * // Add computed properties\n * return rows.map(row => ({\n * ...row,\n * _fullName: `${row.firstName} ${row.lastName}`\n * }));\n * }\n * ```\n */\n processRows?(rows: readonly any[]): any[];\n\n /**\n * Contribute to the grid's effective configuration during each config merge.\n * Called by {@link ConfigManager.merge} after the base config is assembled,\n * before it becomes `effectiveConfig`. Mutate `config` in place to inject\n * plugin-derived settings (e.g. the shell plugin folds its light-DOM /\n * API-registered state into `config.shell`).\n *\n * This is the config-pipeline counterpart to {@link processColumns} /\n * {@link processRows}: it keeps the core config merge free of any plugin\n * knowledge — each plugin owns the shape it contributes.\n *\n * @param config - The mutable base config being assembled into effectiveConfig.\n *\n * @example\n * ```ts\n * processConfig(config: GridConfig): void {\n * config.shell = { ...config.shell, header: { title: this.#title } };\n * }\n * ```\n */\n processConfig?(config: GridConfig): void;\n\n /**\n * Transform columns before rendering.\n * Called during each render cycle before column headers and cells are rendered.\n * Use this to add, remove, or modify column definitions.\n *\n * @param columns - The current columns array (readonly to encourage returning a new array)\n * @returns The modified columns array to render\n *\n * @example\n * ```ts\n * processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n * // Add a selection checkbox column\n * return [\n * { field: '_select', header: '', width: 40 },\n * ...columns\n * ];\n * }\n * ```\n */\n processColumns?(columns: readonly ColumnConfig[]): ColumnConfig[];\n\n /**\n * Called before each render cycle begins.\n * Use this to prepare state or cache values needed during rendering.\n *\n * **Note:** This hook is currently a placeholder for future implementation.\n * It is defined in the interface but not yet invoked by the grid's render pipeline.\n * If you need this functionality, please open an issue or contribute an implementation.\n *\n * @example\n * ```ts\n * beforeRender(): void {\n * this.visibleRowCount = this.calculateVisibleRows();\n * }\n * ```\n */\n beforeRender?(): void;\n\n /**\n * Called after each render cycle completes.\n * Use this for DOM manipulation, adding event listeners to rendered elements,\n * or applying visual effects like selection highlights.\n *\n * @example\n * ```ts\n * afterRender(): void {\n * // Apply selection styling to rendered rows\n * const rows = this.gridElement?.querySelectorAll('.data-grid-row');\n * rows?.forEach((row, i) => {\n * row.classList.toggle('selected', this.selectedRows.has(i));\n * });\n * }\n * ```\n */\n afterRender?(): void;\n\n /**\n * Called synchronously immediately after the grid (re)builds its root DOM\n * structure, before the browser has a chance to paint.\n *\n * Unlike {@link afterRender} (which runs in the scheduler's STYLE phase and\n * may be deferred), this hook fires inside the same task as the structural\n * DOM build. It is the correct place for plugins that need to wrap, relocate,\n * or augment the freshly built grid DOM without a flash of unstyled/unwrapped\n * content — e.g. a shell that moves the grid content into a chrome wrapper.\n *\n * The grid emits this hook every time it performs a full structural rebuild\n * (initial connect and structural changes), but NOT on the scroll/data hot\n * path. Implementations MUST be idempotent: a full rebuild discards any DOM a\n * previous invocation produced, so re-create it, and no-op when the desired\n * structure is already present.\n *\n * @example\n * ```ts\n * afterStructuralRender(): void {\n * const root = this.grid?._renderRoot;\n * if (!root || root.querySelector('.my-wrapper > .tbw-grid-content')) return;\n * // build wrapper, move .tbw-grid-content inside it\n * }\n * ```\n */\n afterStructuralRender?(): void;\n\n /**\n * Called synchronously by the grid immediately before it tears down and\n * rebuilds its root DOM structure (a structural re-render). Plugins that\n * relocated existing light-DOM nodes into their own chrome (e.g. a shell that\n * moves toolbar buttons into the header bar) use this to move those nodes back\n * to their original container so they survive the rebuild. Generic\n * counterpart to {@link afterStructuralRender}. MUST be idempotent.\n */\n beforeStructuralRender?(): void;\n\n /**\n * Called by the grid after a config merge to ask whether the change requires a\n * full structural re-render (rather than a cheaper in-place update). A plugin\n * returns `true` when its rendered DOM signature no longer matches the new\n * effective config — e.g. a shell header appearing/disappearing or a tool\n * panel's count/position/mode changing. The grid performs a structural\n * re-render if ANY plugin returns `true`. MUST be side-effect free.\n */\n needsStructuralRerender?(): boolean;\n\n /**\n * Called by the grid to let a plugin (re-)parse its own light-DOM\n * contributions into plugin state ahead of a config merge. Generic seam that\n * keeps core free of plugin-specific light-DOM tag knowledge (the plugin reads\n * `this.grid._hostElement`). MUST be idempotent.\n */\n parseLightDom?(): void;\n\n /**\n * Called by the grid (from `refreshColumns` and the light-DOM observer) to\n * let a plugin re-parse its light-DOM contributions AND refresh any\n * already-rendered chrome in place when something changed — e.g. a shell\n * title or tool buttons that a framework projected asynchronously after the\n * initial render. Distinct from {@link parseLightDom}, which only updates\n * plugin state. Generic seam — core holds no plugin-specific knowledge. MUST\n * be idempotent and a no-op when the plugin's chrome is not yet rendered.\n */\n syncLightDom?(): void;\n\n /**\n * Called after each cell is rendered.\n * This hook is more efficient than `afterRender()` for cell-level modifications\n * because you receive the cell context directly - no DOM queries needed.\n *\n * Use cases:\n * - Adding selection/highlight classes to specific cells\n * - Injecting badges or decorations\n * - Applying conditional styling based on cell value\n *\n * Performance note: Called for every visible cell during render. Keep implementation fast.\n * This hook is also called during scroll when cells are recycled.\n *\n * @param context - The cell render context with row, column, value, and elements\n *\n * @example\n * ```ts\n * afterCellRender(context: AfterCellRenderContext): void {\n * // Add selection class without DOM queries\n * if (this.isSelected(context.rowIndex, context.colIndex)) {\n * context.cellElement.classList.add('selected');\n * }\n *\n * // Add validation error styling\n * if (this.hasError(context.row, context.column.field)) {\n * context.cellElement.classList.add('has-error');\n * }\n * }\n * ```\n */\n afterCellRender?(context: AfterCellRenderContext): void;\n\n /**\n * Called after a row is fully rendered (all cells complete).\n * Use this for row-level decorations, styling, or ARIA attributes.\n *\n * Common use cases:\n * - Adding selection classes to entire rows (row-focus, selected)\n * - Setting row-level ARIA attributes\n * - Applying row validation highlighting\n * - Tree indentation styling\n *\n * Performance note: Called for every visible row during render. Keep implementation fast.\n * This hook is also called during scroll when rows are recycled.\n *\n * @param context - The row render context with row data and element\n *\n * @example\n * ```ts\n * afterRowRender(context: AfterRowRenderContext): void {\n * // Add row selection class without DOM queries\n * if (this.isRowSelected(context.rowIndex)) {\n * context.rowElement.classList.add('selected', 'row-focus');\n * }\n *\n * // Add validation error styling\n * if (this.rowHasErrors(context.row)) {\n * context.rowElement.classList.add('has-errors');\n * }\n * }\n * ```\n */\n afterRowRender?(context: AfterRowRenderContext): void;\n\n /**\n * Called after scroll-triggered row rendering completes.\n * This is a lightweight hook for applying visual state to recycled DOM elements.\n * Use this instead of afterRender when you need to reapply styling during scroll.\n *\n * Performance note: This is called frequently during scroll. Keep implementation fast.\n *\n * @example\n * ```ts\n * onScrollRender(): void {\n * // Reapply selection state to visible cells\n * this.applySelectionToVisibleCells();\n * }\n * ```\n */\n onScrollRender?(): void;\n\n /**\n * Get the height of a specific row.\n * Used for synthetic rows (group headers, detail panels, etc.) that have fixed heights.\n * Return undefined if this plugin does not manage the height for this row.\n *\n * This hook is called during position cache rebuilds for variable row height virtualization.\n * Plugins that create synthetic rows should implement this to provide accurate heights.\n *\n * @param row - The row data\n * @param index - The row index in the processed rows array\n * @returns The row height in pixels, or undefined if not managed by this plugin\n */\n getRowHeight?(row: unknown, index: number): number | undefined;\n\n /**\n * Adjust the virtualization start index to render additional rows before the visible range.\n * Use this when expanded content (like detail rows) needs its parent row to remain rendered\n * even when the parent row itself has scrolled above the viewport.\n *\n * @param start - The calculated start row index\n * @param scrollTop - The current scroll position\n * @param rowHeight - The height of a single row\n * @returns The adjusted start index (lower than or equal to original start)\n *\n * @example\n * ```ts\n * adjustVirtualStart(start: number, scrollTop: number, rowHeight: number): number {\n * // If row 5 is expanded and scrolled partially, keep it rendered\n * for (const expandedRowIndex of this.expandedRowIndices) {\n * const expandedRowTop = expandedRowIndex * rowHeight;\n * const expandedRowBottom = expandedRowTop + rowHeight + this.detailHeight;\n * if (expandedRowBottom > scrollTop && expandedRowIndex < start) {\n * return expandedRowIndex;\n * }\n * }\n * return start;\n * }\n * ```\n */\n adjustVirtualStart?(start: number, scrollTop: number, rowHeight: number): number;\n\n /**\n * Render a custom row, bypassing the default row rendering.\n * Use this for special row types like group headers, detail rows, or footers.\n *\n * @param row - The row data object\n * @param rowEl - The row DOM element to render into\n * @param rowIndex - The index of the row in the data array\n * @returns `true` if the plugin handled rendering (prevents default), `false`/`void` for default rendering\n *\n * @example\n * ```ts\n * renderRow(row: any, rowEl: HTMLElement, rowIndex: number): boolean | void {\n * if (row._isGroupHeader) {\n * rowEl.innerHTML = `<div class=\"group-header\">${row._groupLabel}</div>`;\n * return true; // Handled - skip default rendering\n * }\n * // Return void to let default rendering proceed\n * }\n * ```\n */\n renderRow?(row: any, rowEl: HTMLElement, rowIndex: number): boolean | void;\n\n // #endregion\n\n // #region Inter-Plugin Communication\n\n /**\n * Handle queries from other plugins or the grid.\n *\n * Queries are declared in `manifest.queries` and dispatched via `grid.query()`.\n * This enables type-safe, discoverable inter-plugin communication.\n *\n * @category Plugin Development\n * @param query - The query object with type and context\n * @returns Query-specific response, or undefined if not handling this query\n *\n * @example\n * ```ts\n * // In manifest\n * static override readonly manifest: PluginManifest = {\n * queries: [\n * { type: 'canMoveColumn', description: 'Check if a column can be moved' },\n * ],\n * };\n *\n * // In plugin class\n * handleQuery(query: PluginQuery): unknown {\n * if (query.type === 'canMoveColumn') {\n * const column = query.context as ColumnConfig;\n * return !column.sticky; // Can't move sticky columns\n * }\n * }\n * ```\n */\n handleQuery?(query: PluginQuery): unknown;\n\n // #endregion\n\n // #region Interaction Hooks\n\n /**\n * Handle keyboard events on the grid.\n * Called when a key is pressed while the grid or a cell has focus.\n *\n * @param event - The native KeyboardEvent\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onKeyDown(event: KeyboardEvent): boolean | void {\n * // Handle Ctrl+A for select all\n * if (event.ctrlKey && event.key === 'a') {\n * this.selectAllRows();\n * return true; // Prevent default browser select-all\n * }\n * }\n * ```\n */\n onKeyDown?(event: KeyboardEvent): boolean | void;\n\n /**\n * Handle cell click events.\n * Called when a data cell is clicked (not headers).\n *\n * @param event - Cell click event with row/column context\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onCellClick(event: CellClickEvent): boolean | void {\n * if (event.field === '_select') {\n * this.toggleRowSelection(event.rowIndex);\n * return true; // Handled\n * }\n * }\n * ```\n */\n onCellClick?(event: CellClickEvent): boolean | void;\n\n /**\n * Handle row click events.\n * Called when any part of a data row is clicked.\n * Note: This is called in addition to onCellClick, not instead of.\n *\n * @param event - Row click event with row context\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onRowClick(event: RowClickEvent): boolean | void {\n * if (this.config.mode === 'row') {\n * this.selectRow(event.rowIndex, event.originalEvent);\n * return true;\n * }\n * }\n * ```\n */\n onRowClick?(event: RowClickEvent): boolean | void;\n\n /**\n * Handle header click events.\n * Called when a column header is clicked. Commonly used for sorting.\n *\n * @param event - Header click event with column context\n * @returns `true` to prevent default behavior and stop propagation, `false`/`void` to allow default\n *\n * @example\n * ```ts\n * onHeaderClick(event: HeaderClickEvent): boolean | void {\n * if (event.column.sortable !== false) {\n * this.toggleSort(event.field);\n * return true;\n * }\n * }\n * ```\n */\n onHeaderClick?(event: HeaderClickEvent): boolean | void;\n\n /**\n * Handle scroll events on the grid viewport.\n * Called during scrolling. Note: This may be called frequently; debounce if needed.\n *\n * @param event - Scroll event with scroll position and viewport dimensions\n *\n * @example\n * ```ts\n * onScroll(event: ScrollEvent): void {\n * // Update sticky column positions\n * this.updateStickyPositions(event.scrollLeft);\n * }\n * ```\n */\n onScroll?(event: ScrollEvent): void;\n\n /**\n * Handle cell mousedown events.\n * Used for initiating drag operations like range selection or column resize.\n *\n * @param event - Mouse event with cell context\n * @returns `true` to indicate drag started (prevents text selection), `false`/`void` otherwise\n *\n * @example\n * ```ts\n * onCellMouseDown(event: CellMouseEvent): boolean | void {\n * if (event.rowIndex !== undefined && this.config.mode === 'range') {\n * this.startDragSelection(event.rowIndex, event.colIndex);\n * return true; // Prevent text selection\n * }\n * }\n * ```\n */\n onCellMouseDown?(event: CellMouseEvent): boolean | void;\n\n /**\n * Handle cell mousemove events during drag operations.\n * Only called when a drag is in progress (after mousedown returned true).\n *\n * @param event - Mouse event with current cell context\n * @returns `true` to continue handling the drag, `false`/`void` otherwise\n *\n * @example\n * ```ts\n * onCellMouseMove(event: CellMouseEvent): boolean | void {\n * if (this.isDragging && event.rowIndex !== undefined) {\n * this.extendSelection(event.rowIndex, event.colIndex);\n * return true;\n * }\n * }\n * ```\n */\n onCellMouseMove?(event: CellMouseEvent): boolean | void;\n\n /**\n * Handle cell mouseup events to end drag operations.\n *\n * @param event - Mouse event with final cell context\n * @returns `true` if drag was finalized, `false`/`void` otherwise\n *\n * @example\n * ```ts\n * onCellMouseUp(event: CellMouseEvent): boolean | void {\n * if (this.isDragging) {\n * this.finalizeDragSelection();\n * this.isDragging = false;\n * return true;\n * }\n * }\n * ```\n */\n onCellMouseUp?(event: CellMouseEvent): boolean | void;\n\n // Note: Context menu items are provided via handleQuery('getContextMenuItems').\n // This keeps the core decoupled from the context-menu plugin specifics.\n\n // #endregion\n\n // #region Column State Hooks\n\n /**\n * Contribute plugin-specific state for a column.\n * Called by the grid when collecting column state for serialization.\n * Plugins can add their own properties to the column state.\n *\n * @param field - The field name of the column\n * @returns Partial column state with plugin-specific properties, or undefined if no state to contribute\n *\n * @example\n * ```ts\n * getColumnState(field: string): Partial<ColumnState> | undefined {\n * const filterModel = this.filterModels.get(field);\n * if (filterModel) {\n * // Uses module augmentation to add filter property to ColumnState\n * return { filter: filterModel } as Partial<ColumnState>;\n * }\n * return undefined;\n * }\n * ```\n */\n getColumnState?(field: string): Partial<ColumnState> | undefined;\n\n /**\n * Apply plugin-specific state to a column.\n * Called by the grid when restoring column state from serialized data.\n * Plugins should restore their internal state based on the provided state.\n *\n * @param field - The field name of the column\n * @param state - The column state to apply (may contain plugin-specific properties)\n *\n * @example\n * ```ts\n * applyColumnState(field: string, state: ColumnState): void {\n * // Check for filter property added via module augmentation\n * const filter = (state as any).filter;\n * if (filter) {\n * this.filterModels.set(field, filter);\n * this.applyFilter();\n * }\n * }\n * ```\n */\n applyColumnState?(field: string, state: ColumnState): void;\n\n // #endregion\n\n // #region Scroll Boundary Hooks\n\n /**\n * Report horizontal scroll boundary offsets for this plugin.\n * Plugins that obscure part of the scroll area (e.g., pinned/sticky columns)\n * should return how much space they occupy on each side.\n * The keyboard navigation uses this to ensure focused cells are fully visible.\n *\n * @param rowEl - The row element (optional, for calculating widths from rendered cells)\n * @param focusedCell - The currently focused cell element (optional, to determine if scrolling should be skipped)\n * @returns Object with left/right pixel offsets and optional skipScroll flag, or undefined if plugin has no offsets\n *\n * @example\n * ```ts\n * getHorizontalScrollOffsets(rowEl?: HTMLElement, focusedCell?: HTMLElement): { left: number; right: number; skipScroll?: boolean } | undefined {\n * // Calculate total width of left-pinned columns\n * const leftCells = rowEl?.querySelectorAll('.sticky-left') ?? [];\n * let left = 0;\n * leftCells.forEach(el => { left += (el as HTMLElement).offsetWidth; });\n * // Skip scroll if focused cell is pinned (always visible)\n * const skipScroll = focusedCell?.classList.contains('sticky-left');\n * return { left, right: 0, skipScroll };\n * }\n * ```\n */\n getHorizontalScrollOffsets?(\n rowEl?: HTMLElement,\n focusedCell?: HTMLElement,\n ): { left: number; right: number; skipScroll?: boolean } | undefined;\n\n /**\n * Report vertical scroll boundary offsets for this plugin.\n * Plugins that overlay the top or bottom of the rows viewport (e.g. sticky\n * row clones) should return how much space they obscure on each edge, so\n * keyboard navigation can scroll a focused row clear of the overlay rather\n * than leaving it hidden underneath — WCAG 2.2 SC 2.4.11 Focus Not Obscured.\n *\n * Only report space that is painted *over* the scrollable rows. Content that\n * takes part in normal flow (pinned-row bars, the column header) already\n * shrinks the viewport and must NOT be reported here, or rows would scroll\n * twice as far as needed.\n *\n * @param focusedRowIndex - Index of the row being scrolled into view, so a plugin can report `skipScroll` when it already renders that row in a permanently visible overlay\n * @returns Object with top/bottom pixel offsets and optional skipScroll flag, or undefined if plugin obscures nothing\n *\n * @example\n * ```ts\n * getVerticalScrollOffsets(focusedRowIndex?: number): { top: number; bottom: number; skipScroll?: boolean } | undefined {\n * if (!this.overlayEl) return undefined;\n * // The row is already pinned in the overlay — it is visible where it is.\n * if (focusedRowIndex != null && this.stuckIndices.includes(focusedRowIndex)) {\n * return { top: 0, bottom: 0, skipScroll: true };\n * }\n * return { top: this.overlayEl.offsetHeight, bottom: 0 };\n * }\n * ```\n *\n * @since 3.6.0\n */\n getVerticalScrollOffsets?(\n focusedRowIndex?: number,\n ): { top: number; bottom: number; skipScroll?: boolean } | undefined;\n\n // #endregion\n\n // #region Shell Integration Hooks\n\n /**\n * Register a tool panel for this plugin.\n * Return undefined if plugin has no tool panel.\n * The shell will create a toolbar toggle button and render the panel content\n * when the user opens the panel.\n *\n * @returns Tool panel definition, or undefined if plugin has no panel\n *\n * @example\n * ```ts\n * getToolPanel(): ToolPanelDefinition | undefined {\n * return {\n * id: 'columns',\n * title: 'Columns',\n * icon: '☰',\n * tooltip: 'Show/hide columns',\n * order: 10,\n * render: (container) => {\n * this.renderColumnList(container);\n * return () => this.cleanup();\n * },\n * };\n * }\n * ```\n */\n getToolPanel?(): ToolPanelDefinition | undefined;\n\n /**\n * Register content for the shell header center section.\n * Return undefined if plugin has no header content.\n * Examples: search input, selection summary, status indicators.\n *\n * @returns Header content definition, or undefined if plugin has no header content\n *\n * @example\n * ```ts\n * getHeaderContent(): HeaderContentDefinition | undefined {\n * return {\n * id: 'quick-filter',\n * order: 10,\n * render: (container) => {\n * const input = document.createElement('input');\n * input.type = 'text';\n * input.placeholder = 'Search...';\n * input.addEventListener('input', this.handleInput);\n * container.appendChild(input);\n * return () => input.removeEventListener('input', this.handleInput);\n * },\n * };\n * }\n * ```\n */\n getHeaderContent?(): HeaderContentDefinition | undefined;\n\n // #endregion\n}\n","/**\n * Shared Data Collection Utilities\n *\n * Pure functions for resolving columns and formatting values, shared between\n * the Clipboard and Export plugins. Each plugin bundles its own copy of this\n * module (no chunk splitting) since plugin builds inline sibling imports.\n *\n * @internal\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Resolve which columns to include in a data export or copy operation.\n *\n * Filters out hidden columns, utility columns (`meta.utility`), and\n * internal columns (`__`-prefixed fields). Optionally restricts to an\n * explicit set of field names.\n *\n * @param columns - All column configurations\n * @param fields - If provided, only include columns whose field is in this list\n * @param onlyVisible - When `true` (default), exclude hidden and internal columns\n * @returns Filtered column array preserving original order\n */\nexport function resolveColumns(\n columns: readonly ColumnConfig[],\n fields?: string[],\n onlyVisible = true,\n): ColumnConfig[] {\n let result = columns as ColumnConfig[];\n\n if (onlyVisible) {\n result = result.filter((c) => !c.hidden && !c.field.startsWith('__') && c.utility !== true);\n }\n\n if (fields?.length) {\n const fieldSet = new Set(fields);\n result = result.filter((c) => fieldSet.has(c.field));\n }\n\n return result;\n}\n\n/**\n * Resolve which rows to include, optionally filtered to specific indices.\n *\n * @param rows - All row data\n * @param indices - If provided, only include rows at these indices (sorted ascending)\n * @returns Filtered row array\n */\nexport function resolveRows<T>(rows: readonly T[], indices?: number[]): T[] {\n if (!indices?.length) return rows as T[];\n\n return [...indices]\n .sort((a, b) => a - b)\n .map((i) => rows[i])\n .filter((r): r is T => r != null);\n}\n\n/**\n * Format a raw cell value as a text string.\n *\n * Provides the common null / Date / object → string conversion shared by\n * both clipboard and export output builders.\n *\n * @param value - The cell value to format\n * @returns A plain-text representation of the value\n */\nexport function formatValueAsText(value: unknown): string {\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n\n/**\n * Leading characters that make Excel / LibreOffice / Google Sheets treat a cell\n * as a formula rather than text.\n */\nconst FORMULA_TRIGGER_RE = /^[=+\\-@\\t\\r]/;\n\n/**\n * Options for {@link formatDelimitedValue}.\n *\n * @since 3.5.0\n */\nexport interface DelimitedFormatOptions {\n /** Field separator (`,` for CSV, `\\t` for clipboard). */\n delimiter: string;\n /** Row separator. */\n newline: string;\n /**\n * `'auto'` (default) quotes only strings containing a separator or quote,\n * `'always'` quotes every string, `'never'` disables quoting entirely.\n */\n quoting?: 'auto' | 'always' | 'never';\n /**\n * Prefix formula-triggering strings with `'` so spreadsheets treat them as\n * text. Defaults to `true`.\n */\n escapeFormulas?: boolean;\n}\n\n/**\n * Format a cell value for a delimiter-separated text format (CSV export or\n * clipboard copy).\n *\n * Only string values are formula-escaped: numbers such as `-5` stringify to a\n * leading `-` but are unambiguously numeric to a spreadsheet, and escaping them\n * would turn every negative number into text.\n *\n * Dispatch order is `typeof`-first because string + number cover the vast\n * majority of cell values; the cheap typeof check skips an `instanceof Date`\n * probe (which V8 cannot fold into a fast path) for every plain string cell.\n *\n * @param value - The cell value to format\n * @param opts - Delimiter, newline, quoting and formula-escaping behaviour\n * @returns The value as a delimiter-safe string\n * @since 3.5.0\n */\nexport function formatDelimitedValue(value: unknown, opts: DelimitedFormatOptions): string {\n // Hot path: strings (most cells).\n if (typeof value === 'string') {\n const text = opts.escapeFormulas !== false && FORMULA_TRIGGER_RE.test(value) ? `'${value}` : value;\n const quoting = opts.quoting ?? 'auto';\n if (\n quoting === 'always' ||\n (quoting === 'auto' &&\n (text.includes(opts.delimiter) ||\n text.includes(opts.newline) ||\n text.includes('\"') ||\n text.includes('\\n') ||\n text.includes('\\r')))\n ) {\n return `\"${text.replace(/\"/g, '\"\"')}\"`;\n }\n return text;\n }\n if (typeof value === 'number') return String(value);\n if (typeof value === 'boolean') return value ? 'true' : 'false';\n if (value == null) return '';\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'object') return JSON.stringify(value);\n // Symbols, bigints, etc.\n return String(value);\n}\n","/**\n * Structured clipboard payload codec.\n *\n * Copy writes both `text/plain` (WYSIWYG for external targets) and `text/html`.\n * The HTML is a real `<table>` of the display text whose root element also\n * carries a base64-encoded structured payload in a `data-tbw-clip` attribute.\n * A same-app paste — even **cross-grid or cross-window** — can then recover the\n * raw cell values losslessly, while external targets just see the table/text.\n *\n * Kept in its own module so `copy.ts` and `paste.ts` share the format without\n * importing each other.\n */\nimport { escapeHtml } from '../../core/internal/sanitize';\n\n/**\n * Structured clipboard payload carried in `text/html`. `rows` are the RAW cell\n * values (data rows only), `fields` the source column fields in the same order.\n * @internal\n */\nexport interface ClipboardPayload {\n /** Payload schema version. */\n v: 1;\n /** Source column fields, in column order. */\n fields: string[];\n /** Raw cell values, one inner array per data row (no header). */\n rows: unknown[][];\n}\n\n/** Attribute (on the payload table) that marks our structured HTML clipboard. */\nexport const CLIPBOARD_PAYLOAD_ATTR = 'data-tbw-clip';\n\n/** Unicode-safe base64 encode of a JSON payload for an HTML attribute. */\nfunction encodePayload(payload: ClipboardPayload): string {\n return btoa(encodeURIComponent(JSON.stringify(payload)));\n}\n\n/**\n * Build the `text/html` clipboard representation: a real `<table>` of the\n * DISPLAY text (so external targets like Excel get a proper table) whose root\n * element carries the base64-encoded structured {@link ClipboardPayload} in a\n * `data-tbw-clip` attribute for lossless same-app paste.\n */\nexport function buildClipboardHtml(\n header: string[] | null,\n displayRows: string[][],\n payload: ClipboardPayload,\n): string {\n const thead = header ? `<thead><tr>${header.map((h) => `<th>${escapeHtml(h)}</th>`).join('')}</tr></thead>` : '';\n const tbody = `<tbody>${displayRows\n .map((r) => `<tr>${r.map((c) => `<td>${escapeHtml(c)}</td>`).join('')}</tr>`)\n .join('')}</tbody>`;\n return `<table ${CLIPBOARD_PAYLOAD_ATTR}=\"${encodePayload(payload)}\">${thead}${tbody}</table>`;\n}\n\n/**\n * Extract the structured {@link ClipboardPayload} embedded in a `text/html`\n * clipboard representation written by {@link buildClipboardHtml}. Enables a\n * lossless **cross-grid / cross-window** paste of object-valued cells (the\n * in-memory buffer only covers the same grid instance).\n *\n * Returns `null` when the HTML has no `data-tbw-clip` marker (e.g. an external\n * paste from Excel) or the payload can't be decoded. Parsing is defensive —\n * malformed input never throws.\n *\n * @param html - Raw `text/html` from `clipboardData.getData('text/html')`\n */\nexport function parseClipboardHtmlPayload(html: string | undefined | null): ClipboardPayload | null {\n if (!html || html.indexOf(CLIPBOARD_PAYLOAD_ATTR) === -1) return null;\n try {\n // Extract only our own base64 payload attribute with a targeted match rather\n // than parsing the whole (untrusted) clipboard HTML through a DOM sink\n // (DOMParser) — the latter feeds attacker-controlled markup to the parser and\n // trips CodeQL js/xss. The attribute value is base64 (btoa output), whose\n // alphabet excludes quotes and tag characters, so a simple attribute match is\n // both safe and sufficient.\n const match = html.match(new RegExp(`${CLIPBOARD_PAYLOAD_ATTR}=\"([A-Za-z0-9+/=]*)\"`));\n const encoded = match?.[1];\n if (!encoded) return null;\n const payload = JSON.parse(decodeURIComponent(atob(encoded))) as ClipboardPayload;\n if (payload && Array.isArray(payload.rows) && Array.isArray(payload.fields)) {\n return payload;\n }\n return null;\n } catch {\n return null;\n }\n}\n","/**\n * Clipboard Copy Logic\n *\n * Pure functions for copying grid data to clipboard.\n */\n\nimport { CLIPBOARD_FAILED, warnDiagnostic } from '../../core/internal/diagnostics';\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatDelimitedValue, type DelimitedFormatOptions } from '../shared/data-collection';\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 return formatDelimitedValue(value, toFormatOptions(config));\n}\n\n/** Map the plugin config onto the shared delimited-format options. */\nfunction toFormatOptions(config: ClipboardConfig): DelimitedFormatOptions {\n return {\n delimiter: config.delimiter ?? '\\t',\n newline: config.newline ?? '\\n',\n quoting: config.quoteStrings ? 'always' : 'auto',\n escapeFormulas: config.escapeFormulas,\n };\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 // Built once — this runs per cell across the whole selection.\n const format = toFormatOptions(config);\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 const value = resolveCellValue(row, col);\n return config.processCell\n ? config.processCell(value, col.field, row)\n : formatDelimitedValue(value, format);\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 * When `html` is supplied, writes BOTH `text/plain` and `text/html` via\n * `ClipboardItem` so a same-app paste (even cross-grid or cross-window) can\n * recover a structured payload embedded in the HTML, while external targets\n * (Excel, editors) still get the plain text. Silently falls back to text-only\n * when `ClipboardItem` / `clipboard.write` is unavailable or rejects.\n *\n * @param text - The text to copy (`text/plain`)\n * @param html - Optional rich `text/html` representation (may embed a payload)\n * @returns Promise resolving to true if successful, false otherwise\n */\nexport async function copyToClipboard(text: string, html?: string): Promise<boolean> {\n if (html && typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {\n try {\n await navigator.clipboard.write([\n new ClipboardItem({\n 'text/plain': new Blob([text], { type: 'text/plain' }),\n 'text/html': new Blob([html], { type: 'text/html' }),\n }),\n ]);\n return true;\n } catch {\n // Fall through to text-only write below.\n }\n }\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch (err) {\n warnDiagnostic(CLIPBOARD_FAILED, `Clipboard API failed: ${err}`);\n // Fallback for older browsers or when Clipboard API is not available\n const textarea = document.createElement('textarea');\n textarea.value = text;\n textarea.style.position = 'fixed';\n textarea.style.opacity = '0';\n textarea.style.pointerEvents = 'none';\n document.body.appendChild(textarea);\n textarea.select();\n const success = document.execCommand('copy');\n document.body.removeChild(textarea);\n return success;\n }\n}\n","/**\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 * Implementation: char-by-char state machine for delimiter/newline/quote\n * detection, but cell values are extracted via `slice(start, end)` rather\n * than `+= char` accumulation. The vast majority of cells have no quotes,\n * so the hot path is a single substring slice per cell. Cells that did\n * contain quotes fall back to {@link unquoteCell} for the strip + escape\n * pass.\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 // Normalize Windows / old-Mac line endings.\n const normalized = text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n const len = normalized.length;\n\n const rows: string[][] = [];\n let currentRow: string[] = [];\n let cellStart = 0;\n let inQuotes = false;\n let cellHasQuotes = false;\n\n const finalizeCell = (endIdx: number): string => {\n const raw = normalized.slice(cellStart, endIdx);\n return cellHasQuotes ? unquoteCell(raw) : raw;\n };\n\n const pushRow = () => {\n // Filter purely-empty rows (single empty cell or all-whitespace cells),\n // matching the original char-by-char implementation's contract.\n if (currentRow.length > 1 || currentRow.some((c) => c.trim() !== '')) {\n rows.push(currentRow);\n }\n currentRow = [];\n };\n\n for (let i = 0; i < len; i++) {\n const char = normalized[i];\n\n if (char === '\"') {\n cellHasQuotes = true;\n if (!inQuotes) {\n inQuotes = true;\n } else if (normalized[i + 1] === '\"') {\n // Escaped quote (\"\") — skip the second quote, stay inside the quoted run.\n i++;\n } else {\n inQuotes = false;\n }\n } else if (char === delimiter && !inQuotes) {\n currentRow.push(finalizeCell(i));\n cellStart = i + 1;\n cellHasQuotes = false;\n } else if (char === newline && !inQuotes) {\n currentRow.push(finalizeCell(i));\n cellStart = i + 1;\n cellHasQuotes = false;\n pushRow();\n }\n }\n\n // Final cell + row.\n currentRow.push(finalizeCell(len));\n pushRow();\n\n return rows;\n}\n\n/**\n * Strip surrounding quotes and unescape `\"\"` → `\"` from a cell value that\n * contained at least one quote character. Only invoked from the slow path\n * of {@link parseClipboardText}.\n */\nfunction unquoteCell(raw: string): string {\n let out = '';\n let inQuotes = false;\n for (let i = 0; i < raw.length; i++) {\n const c = raw[i];\n if (c === '\"') {\n if (!inQuotes) {\n inQuotes = true;\n } else if (raw[i + 1] === '\"') {\n out += '\"';\n i++;\n } else {\n inQuotes = false;\n }\n } else {\n out += c;\n }\n }\n return out;\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 { invalidateAccessorCache, readCellField, writeCellField } from '../../core/internal/value-accessor';\nimport type { GridElement } from '../../core/plugin/base-plugin';\nimport type { CellEditablePredicate } from '../../core/plugin/types';\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 * @since 0.4.2\n */\nexport type PasteHandler = (detail: PasteDetail, grid: GridElement) => boolean | void;\n\n/**\n * Options for programmatic copy operations.\n *\n * Allows callers to control exactly which columns and rows are included\n * in a copy, independently of the current selection state.\n *\n * @example Copy specific columns from selected rows\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * // User selected rows 0, 2, 4 via a dialog, chose columns to include\n * const text = await clipboard.copy({\n * rowIndices: [0, 2, 4],\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * ```\n * @since 1.14.0\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/**\n * Configuration options for the clipboard plugin\n *\n * @since 0.1.1\n */\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 /**\n * Neutralize spreadsheet formula injection (CWE-1236) by prefixing string\n * values that start with `=`, `+`, `-`, `@`, TAB or CR with a single quote,\n * so a paste into Excel / LibreOffice / Sheets renders them as text instead\n * of evaluating them (default: `true`).\n *\n * Grid-to-grid paste is unaffected — that path uses the structured\n * `text/html` payload, not the plain-text representation.\n *\n * @since 3.5.0\n */\n escapeFormulas?: boolean;\n /** Custom cell value processor for copy operations */\n processCell?: (value: unknown, field: string, row: unknown) => string;\n /**\n * When `true`, pasting into a multi-cell selection larger than the clipboard\n * source tiles (repeats) the source to fill the whole selection: a single\n * copied cell fills every selected cell, a 1×2 source fills as\n * `val1, val2, val1, val2`, and a 2×2 block tiles across the selection.\n *\n * Only applies when a bounded (multi-cell) selection is active — it never\n * grows the grid. Defaults to `false` (paste writes only the source extent).\n *\n * @default false\n * @since 3.0.0\n */\n fillSelection?: boolean;\n /**\n * Custom paste handler that **fully replaces** {@link defaultPasteHandler}.\n *\n * ⚠️ **Prefer not to override this.** The default handler is no longer a thin\n * \"write text into cells\" routine — it now implements substantial behavior\n * that is easy to get subtly wrong when reimplemented:\n *\n * - editability resolution via the editing plugin (`getCellEditableResolver`,\n * including row-conditional `editable`);\n * - per-column {@link BaseColumnConfig.onPaste} reject / transform, plus the\n * `paste-rejected` event;\n * - structured (`rawRows`) same-grid / cross-window values so object cells\n * round-trip losslessly (not degraded to display text);\n * - fill-selection tiling of a smaller source across a bounded selection;\n * - routing edits through `grid.updateRows(…, 'paste')` so paste participates\n * in dirty tracking, undo/redo history, cancelable validation, and the\n * `'paste'` commit source — with a direct-write fallback for id-less rows;\n * - growing the grid for unbounded single-cell-expansion pastes.\n *\n * **Use an extension point instead of overriding, wherever possible:**\n * - reject / transform per cell → column {@link BaseColumnConfig.onPaste};\n * - coerce / veto committed values globally → the cancelable `cell-commit`\n * event (`detail.source === 'paste'` distinguishes a paste);\n * - observe the raw paste → the `paste` event;\n * - react to rejected cells → the `paste-rejected` event.\n *\n * Other values:\n * - `null` — disable auto-paste entirely (the `paste` event still fires).\n * - a function returning `false` — you handled it; skip the default.\n *\n * **If you must override** (e.g. bespoke target placement or side effects),\n * you are responsible for re-implementing the behaviors above. At minimum,\n * honor per-column `onPaste` with the exported {@link resolveColumnPaste} and\n * fire {@link emitPasteRejected} so `onPaste` and `paste-rejected` keep working:\n *\n * ```ts\n * import { resolveColumnPaste, emitPasteRejected } from '@toolbox-web/grid/plugins/clipboard';\n *\n * pasteHandler: (detail, grid) => {\n * const rejected = [];\n * for (const cell of myCells(detail)) {\n * const res = resolveColumnPaste(cell.column.onPaste, {\n * value: cell.value, field: cell.field, row: cell.row,\n * rowIndex: cell.rowIndex, oldValue: cell.oldValue, sourceField: cell.sourceField,\n * });\n * if (res.accepted) writeCell(cell, res.value);\n * else rejected.push({ field: cell.field, rowIndex: cell.rowIndex, row: cell.row, value: cell.value, reason: res.reason });\n * }\n * emitPasteRejected(grid, rejected);\n * return false; // handled\n * }\n * ```\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/**\n * Event detail emitted after a successful copy operation\n *\n * @since 0.1.1\n */\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/**\n * Target cell coordinates and bounds for paste operations\n *\n * @since 0.4.2\n */\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/**\n * Event detail emitted after a paste operation\n *\n * @since 0.1.1\n */\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 * When `fillSelection` is active, this spans the full selection width so the source can be tiled.\n */\n fields: string[];\n /**\n * When `true`, the paste handler tiles the clipboard source across the full\n * selection bounds (see {@link ClipboardConfig.fillSelection}). Set by the\n * plugin from config; only ever `true` when `target.bounds` is set.\n * @since 3.0.0\n */\n fillSelection?: boolean;\n /**\n * Raw (structured) cell values for a **same-grid** paste, aligned 1:1 with\n * {@link rows} (same dimensions, data rows only). Present only when the paste\n * text exactly matches what this grid last copied — so an object-valued cell\n * (e.g. `{id,name}`, arrays) round-trips losslessly instead of degrading to\n * the copied display text. `undefined` for external/cross-grid pastes, where\n * only the text is available. The default handler prefers `rawRows` over\n * `rows` for values (cloning each so targets don't share references).\n * @since 3.0.0\n */\n rawRows?: unknown[][];\n /**\n * Source column fields the pasted data was copied FROM, in the copied column\n * order (aligned with the columns of {@link rows} / {@link rawRows}). Lets a\n * column's {@link BaseColumnConfig.onPaste} know the origin column so it can\n * reject cross-column / cross-type pastes. Present for a **same-app** paste\n * (same grid via the in-memory buffer, or cross-grid / cross-window via the\n * structured `text/html` payload); `undefined` for external pastes (e.g. from\n * Excel), where only the text is available.\n * @since 3.0.0\n */\n sourceFields?: string[];\n}\n\n/**\n * Context passed to a column's {@link BaseColumnConfig.onPaste} guard/transform\n * for each cell a paste would write into.\n *\n * @since 3.0.0\n */\nexport interface PasteCellContext<TRow = unknown, TValue = unknown> {\n /** The incoming pasted value (the raw structured value for a same-grid paste). */\n value: TValue;\n /** The column field receiving the value. */\n field: string;\n /** The target row object (pre-paste state). */\n row: TRow;\n /** Index of the target row in the current data set. */\n rowIndex: number;\n /** The cell's current value before the paste. */\n oldValue: TValue;\n /**\n * The column field the value was copied FROM (the origin column), for a\n * same-app paste. `undefined` for an external paste (e.g. from Excel) or when\n * the source column is unknown. Use it to reject cross-column / cross-type\n * pastes (e.g. refuse a value copied from a \"car\" column into a \"fruit\"\n * column). To compare types, look up your own column config by this field.\n * @since 3.0.0\n */\n sourceField?: string;\n}\n\n/**\n * A column's paste guard / transform (`onPaste`). See {@link BaseColumnConfig.onPaste}.\n * @since 3.0.0\n */\nexport type ColumnPasteGuard<TRow = unknown, TValue = unknown> =\n boolean | ((ctx: PasteCellContext<TRow, TValue>) => boolean | { value: TValue });\n\n/**\n * Why a cell's paste was rejected: `'column'` = the column set `onPaste: false`;\n * `'cell'` = an `onPaste` callback returned `false`.\n * @since 3.0.0\n */\nexport type PasteRejectionReason = 'column' | 'cell';\n\n/** One cell whose paste a column's `onPaste` guard rejected. @since 3.0.0 */\nexport interface PasteRejectedCell {\n /** The column field. */\n field: string;\n /** Index of the target row in the current data set. */\n rowIndex: number;\n /** The target row object. */\n row: unknown;\n /** The incoming value that was rejected (before any transform). */\n value: unknown;\n /** Why it was rejected. */\n reason: PasteRejectionReason;\n}\n\n/**\n * Detail for the `paste-rejected` event: the cells a column's `onPaste` guard\n * rejected during a paste. Fires once per paste, only when at least one cell was\n * rejected, so a consumer can surface a message. Non-editable cells are skipped\n * silently and are NOT reported here.\n * @since 3.0.0\n */\nexport interface PasteRejectedDetail {\n /** Cells rejected by a column `onPaste` guard. */\n rejected: PasteRejectedCell[];\n}\n\n/** Result of {@link resolveColumnPaste}. @since 3.0.0 */\nexport type PasteResolution = { accepted: true; value: unknown } | { accepted: false; reason: PasteRejectionReason };\n\n/**\n * Resolve a column's {@link ColumnPasteGuard} (`onPaste`) for a single cell.\n *\n * Pure — never mutates or emits. Exposed so a **custom `pasteHandler`** can honor\n * per-column `onPaste` identically to {@link defaultPasteHandler}: call it per\n * cell, write `resolution.value` when accepted, and collect the rejected cells to\n * pass to {@link emitPasteRejected}.\n *\n * @param onPaste - The column's `onPaste` config (`column.onPaste`), if any.\n * @param ctx - The cell context (value, field, row, rowIndex, oldValue, sourceField).\n * @returns `{ accepted: true, value }` (value possibly transformed) or\n * `{ accepted: false, reason }`.\n *\n * @example\n * ```ts\n * // Inside a custom pasteHandler:\n * const rejected: PasteRejectedCell[] = [];\n * const res = resolveColumnPaste(column.onPaste, { value, field, row, rowIndex, oldValue });\n * if (res.accepted) row[field] = res.value;\n * else rejected.push({ field, rowIndex, row, value, reason: res.reason });\n * // …after writing all cells:\n * emitPasteRejected(grid, rejected);\n * ```\n * @since 3.0.0\n */\nexport function resolveColumnPaste(onPaste: ColumnPasteGuard | undefined, ctx: PasteCellContext): PasteResolution {\n if (onPaste === false) return { accepted: false, reason: 'column' };\n if (typeof onPaste === 'function') {\n const result = onPaste(ctx);\n if (result === false) return { accepted: false, reason: 'cell' };\n if (result && typeof result === 'object' && 'value' in result) {\n return { accepted: true, value: (result as { value: unknown }).value };\n }\n }\n return { accepted: true, value: ctx.value };\n}\n\n/**\n * Dispatch the `paste-rejected` event on the grid. No-op when `rejected` is empty.\n * Exposed so a custom `pasteHandler` can emit the same event the default handler\n * does, after resolving cells via {@link resolveColumnPaste}.\n * @since 3.0.0\n */\nexport function emitPasteRejected(grid: GridElement, rejected: PasteRejectedCell[]): void {\n if (rejected.length === 0) return;\n grid.dispatchEvent?.(new CustomEvent<PasteRejectedDetail>('paste-rejected', { detail: { rejected }, bubbles: true }));\n}\n\n/**\n * Default paste handler that applies pasted data to the grid.\n *\n * This is the built-in handler used when no custom `pasteHandler` is configured.\n *\n * Edits are routed through `grid.updateRows(…, 'paste')` so paste participates in\n * the full edit pipeline — dirty tracking, cancelable validation, undo/redo\n * history, and abortion — exactly like an interactive edit, and so a\n * `cell-commit` listener can tell a paste apart via `detail.source === 'paste'`.\n * Rows without a resolvable ID (no `getRowId`) fall back to a direct in-place\n * write, which still updates values but does not track them.\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 * - Fill-selection: when `detail.fillSelection` is set, the source is tiled\n * (repeated via modulo indexing) to fill the whole selection bounds\n * - Non-editable cells: values are skipped (column alignment preserved).\n * Editability is resolved by the editing plugin via the\n * `getCellEditableResolver` query — including row-conditional `editable`.\n * Without the editing plugin, no cell is editable and paste is a no-op.\n * - Per-column `onPaste`: after the editability check, a column's\n * {@link BaseColumnConfig.onPaste} may reject the cell (skipped, alignment\n * preserved) or transform the pasted value. Rejected cells are reported once\n * via the `paste-rejected` event ({@link PasteRejectedDetail}).\n *\n * @param detail - The parsed paste data from clipboard\n * @param grid - The grid element to update\n * @since 0.4.2\n */\nexport function defaultPasteHandler(detail: PasteDetail, grid: GridElement): void {\n const { rows: pastedRows, rawRows, target, fields, fillSelection, sourceFields } = detail;\n\n // No target = nothing to do\n if (!target || pastedRows.length === 0) return;\n\n // Prefer the raw structured values for a same-grid paste (lossless object\n // round-trip); fall back to the parsed text for external/cross-grid pastes.\n const valueRows: unknown[][] = rawRows ?? pastedRows;\n\n const currentRows = grid.rows as Record<string, unknown>[];\n const columns = grid.effectiveConfig.columns ?? [];\n const allFields = columns.map((col) => col.field);\n const columnByField = new Map(columns.map((col) => [col.field, col]));\n\n // Editability is owned by the editing plugin (row-conditional included). With\n // no editing plugin loaded, nothing is editable and paste is a no-op.\n const [canEditCell = () => false] = grid.query<CellEditablePredicate>('getCellEditableResolver');\n\n // Accumulate the intended edits per target row (honoring editability, tiling,\n // and selection bounds). Rows beyond current data are only created for an\n // unbounded (single-cell expansion) paste.\n const editsByRow = new Map<number, Record<string, unknown>>();\n let rowCountAfter = currentRows.length;\n // Cells a column's `onPaste` guard rejected — reported via `paste-rejected`.\n const rejected: PasteRejectedCell[] = [];\n\n const addEdit = (\n rowIndex: number,\n field: string | undefined,\n value: unknown,\n evalRow: Record<string, unknown>,\n sourceField?: string,\n ) => {\n if (!field || !canEditCell(field, evalRow)) return;\n // Per-column paste guard/transform (clipboard-augmented `onPaste`). Runs\n // after the editability check so it only sees cells paste could write.\n const resolution = resolveColumnPaste(columnByField.get(field)?.onPaste, {\n value,\n field,\n row: evalRow,\n rowIndex,\n oldValue: readCellField(evalRow, field),\n sourceField,\n });\n if (!resolution.accepted) {\n rejected.push({ field, rowIndex, row: evalRow, value, reason: resolution.reason });\n return; // reject this cell (alignment preserved, like a non-editable cell)\n }\n let changes = editsByRow.get(rowIndex);\n if (!changes) {\n changes = {};\n editsByRow.set(rowIndex, changes);\n }\n // Clone structured values so tiled/multi-target pastes never share a\n // reference (mutating one row's object would otherwise mutate the source\n // and every other target). No-op for primitives (the text path).\n changes[field] = cloneStructured(resolution.value);\n };\n\n if (fillSelection && target.bounds) {\n // Fill-selection (tile) mode: repeat the source across the selection bounds\n // using modulo indexing. Never grows the grid. Editability is resolved\n // against the pre-paste row (bounded mode never grows).\n const srcRows = valueRows.length;\n for (let rowIndex = target.row; rowIndex <= target.bounds.endRow; rowIndex++) {\n if (rowIndex >= currentRows.length) break;\n const sourceRow = valueRows[(rowIndex - target.row) % srcRows];\n const srcCols = sourceRow.length;\n if (srcCols === 0) continue;\n const evalRow = currentRows[rowIndex];\n fields.forEach((field, colOffset) =>\n addEdit(rowIndex, field, sourceRow[colOffset % srcCols], evalRow, sourceFields?.[colOffset % srcCols]),\n );\n }\n } else {\n const maxPasteRow = target.bounds ? target.bounds.endRow : Infinity;\n valueRows.forEach((rowData, rowOffset) => {\n const targetRowIndex = target.row + rowOffset;\n if (targetRowIndex > maxPasteRow) return;\n if (target.bounds && targetRowIndex >= currentRows.length) return; // bounded: don't grow\n if (!target.bounds && targetRowIndex >= rowCountAfter) rowCountAfter = targetRowIndex + 1;\n // Editability resolved against the pre-paste row (empty for grown rows).\n const evalRow = currentRows[targetRowIndex] ?? {};\n rowData.forEach((cellValue, colOffset) =>\n addEdit(targetRowIndex, fields[colOffset], cellValue, evalRow, sourceFields?.[colOffset]),\n );\n });\n }\n\n if (editsByRow.size === 0 && rowCountAfter === currentRows.length) {\n // Nothing accepted (e.g. every cell rejected) — still report the rejections.\n emitPasteRejected(grid, rejected);\n return;\n }\n\n // Grow the grid first for unbounded pastes that extend past existing data.\n // New rows start empty; their pasted values are applied in the write phase.\n if (rowCountAfter > currentRows.length) {\n const grown = [...currentRows];\n while (grown.length < rowCountAfter) {\n const emptyRow: Record<string, unknown> = {};\n allFields.forEach((f) => (emptyRow[f] = ''));\n grown.push(emptyRow);\n }\n grid.rows = grown;\n }\n\n const rowsNow = grid.rows as Record<string, unknown>[];\n\n // Route edits through updateRows so paste flows through the edit pipeline\n // (dirty tracking, validation, history, abortion). Rows without a resolvable\n // ID fall back to a direct in-place write.\n const updates: Array<{ id: string; changes: Record<string, unknown> }> = [];\n let directWrote = false;\n for (const [rowIndex, changes] of editsByRow) {\n const row = rowsNow[rowIndex];\n if (!row) continue;\n let id: string | undefined;\n try {\n id = grid.getRowId(row);\n } catch {\n id = undefined;\n }\n if (id == null) {\n // No stable ID → can't route through updateRow; write directly. Invalidate\n // the value-accessor cache per field (row identity is unchanged), matching\n // RowManager.updateRow — otherwise a `column.valueAccessor` display can go\n // stale after paste.\n for (const [field, value] of Object.entries(changes)) {\n writeCellField(row, field, value);\n invalidateAccessorCache(row as object, field);\n }\n directWrote = true;\n } else {\n updates.push({ id, changes });\n }\n }\n\n if (updates.length > 0) {\n grid.updateRows(updates, 'paste');\n } else if (directWrote && rowCountAfter === currentRows.length) {\n // Direct writes only, no structural grow above — trigger a render.\n grid.rows = [...rowsNow];\n }\n\n // Notify consumers of any cells a column's `onPaste` guard rejected.\n emitPasteRejected(grid, rejected);\n}\n\n/**\n * Deep-clone a structured cell value so tiled/multi-target pastes don't share a\n * reference. Primitives (and `null`) are returned as-is. Falls back to the\n * original value if it isn't structured-cloneable.\n * @internal\n */\nexport function cloneStructured(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n}\n\n// Module Augmentation - Register plugin name for type-safe getPluginByName()\ndeclare module '../../core/types' {\n interface DataGridEventMap {\n /** Fired after a successful copy operation. Provides the copied text, row count, and column count. @group Clipboard Events */\n copy: CopyDetail;\n /** Fired after a paste operation. Provides parsed rows, target cell, and column fields. @group Clipboard Events */\n paste: PasteDetail;\n /** Fired after a paste when one or more cells were rejected by a column's `onPaste` guard. @group Clipboard Events */\n 'paste-rejected': PasteRejectedDetail;\n }\n\n interface PluginNameMap {\n clipboard: import('./clipboard-plugin').ClipboardPlugin;\n }\n\n /** Clipboard contributes its own edit-origin tag so a `cell-commit` listener\n * can tell a paste from a user edit via `detail.source === 'paste'`. */\n interface UpdateSourceMap {\n /** A value written by a clipboard paste. @since 3.0.0 */\n paste: true;\n }\n\n interface BaseColumnConfig<TRow, TValue> {\n /**\n * Per-column paste guard / transform. Requires the ClipboardPlugin.\n *\n * Runs for each cell a paste would write into (after the editing plugin's\n * editability check), letting a consumer reject or rewrite pasted values\n * **per column** — finer-grained than the whole-operation\n * {@link ClipboardConfig.pasteHandler}.\n *\n * - `true` / omitted — accept pastes (default behavior).\n * - `false` — this column never accepts pastes; matching cells are skipped\n * (column alignment is preserved, like a non-editable cell).\n * - `(ctx) => …` — called per cell. Return `false` to reject just that cell,\n * `true` (or nothing) to accept as-is, or `{ value }` to write a\n * transformed value instead. Returning `{ value }` disambiguates a\n * transform from a boolean verdict, so boolean-valued columns stay safe.\n *\n * Synchronous only — the paste pipeline does not await. Rejected cells\n * (either form) are reported once per paste via the `paste-rejected` event\n * ({@link PasteRejectedDetail}), so a consumer can show a message.\n *\n * The callback context also carries `sourceField` — the column the value was\n * copied FROM (for a same-app paste; `undefined` for external pastes) — so a\n * column can reject cross-column / cross-type pastes (e.g. refuse a value\n * copied from a \"car\" column into a \"fruit\" column).\n *\n * @example\n * ```typescript\n * // Reject pastes into a locked column\n * { field: 'id', onPaste: false }\n *\n * // Reject invalid values, coerce the rest\n * {\n * field: 'price',\n * onPaste: ({ value }) => {\n * const n = Number(String(value).replace(/[^0-9.]/g, ''));\n * return Number.isFinite(n) ? { value: n } : false;\n * },\n * }\n * ```\n * @since 3.0.0\n */\n onPaste?: ColumnPasteGuard<TRow, TValue>;\n }\n}\n","/**\n * Clipboard Plugin (Class-based)\n *\n * Provides copy/paste functionality for tbw-grid.\n * Supports Ctrl+C/Cmd+C for copying and Ctrl+V/Cmd+V for pasting.\n *\n * **With Selection plugin:** Copies selected cells/rows/range\n * **Without Selection plugin:** Copies entire grid\n */\n\nimport { resolveCellValue } from '../../core/internal/value-accessor';\nimport {\n BaseGridPlugin,\n type GridElement,\n type PluginDependency,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { formatValueAsText, resolveColumns, resolveRows } from '../shared/data-collection';\nimport { buildClipboardHtml, parseClipboardHtmlPayload } from './clipboard-payload';\nimport { copyToClipboard } from './copy';\nimport { parseClipboardText, readFromClipboard } from './paste';\nimport {\n cloneStructured,\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/paste functionality with full keyboard shortcut support\n * (Ctrl/Cmd+C, Ctrl/Cmd+V). Handles single cells, multi-cell selections, and integrates\n * seamlessly with Excel and other spreadsheet applications via tab-delimited output.\n *\n * > **Optional Dependency:** Works best with SelectionPlugin for copying/pasting selected\n * > cells. Without SelectionPlugin, copies the entire grid and pastes at row 0, column 0.\n *\n * ## Installation\n *\n * ```ts\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * ```\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+C` / `Cmd+C` | Copy selected cells |\n * | `Ctrl+V` / `Cmd+V` | Paste into selected cells |\n *\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 * With `fillSelection: true`, pasting a smaller source into a larger bounded\n * selection tiles the source to fill the whole selection (e.g. one cell fills\n * all selected cells; a 1×2 source fills as `val1, val2, val1, val2`).\n *\n * @example Basic Usage with Excel Compatibility\n * ```ts\n * import '@toolbox-web/grid';\n * import { ClipboardPlugin } from '@toolbox-web/grid/plugins/clipboard';\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [\n * new SelectionPlugin({ mode: 'range' }),\n * new ClipboardPlugin({\n * includeHeaders: true,\n * delimiter: '\\t', // Tab for Excel\n * }),\n * ],\n * };\n * ```\n *\n * @example Custom Paste Handler\n * ```ts\n * new ClipboardPlugin({\n * pasteHandler: (grid, target, data) => {\n * // Validate or transform data before applying\n * console.log('Pasting', data.length, 'rows');\n * return defaultPasteHandler(grid, target, data);\n * },\n * })\n * ```\n *\n * @see {@link ClipboardConfig} for all configuration options\n * @see SelectionPlugin for enhanced copy/paste with selection\n *\n * @internal Extends BaseGridPlugin\n * @since 0.1.1\n */\nexport class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {\n /**\n * Plugin manifest — declares queries for inter-plugin communication.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [{ type: 'clipboard:copy', description: 'Triggers a copy operation and returns the copied text' }],\n };\n\n /**\n * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.\n *\n * Without SelectionPlugin: copies entire grid, pastes at row 0 col 0.\n * With SelectionPlugin: copies/pastes based on selection.\n */\n /** @internal */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'selection', required: false, reason: 'Enables copy/paste of selected cells instead of entire grid' },\n ];\n\n /** @internal */\n readonly name = 'clipboard';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ClipboardConfig> {\n return {\n includeHeaders: false,\n delimiter: '\\t',\n newline: '\\n',\n quoteStrings: false,\n };\n }\n\n // #region Internal State\n /** The last copied text (for reference/debugging) */\n private lastCopied: { text: string; timestamp: number } | null = null;\n /**\n * Raw (structured) values for the last copy, so a same-grid paste round-trips\n * object cells losslessly instead of degrading to the copied display text.\n * `text` is the exact clipboard text; a paste whose text matches restores\n * `rawRows` (data rows only, aligned with the copied columns). Cleared on\n * detach; a non-matching external paste simply ignores it.\n */\n #internalClipboard: { text: string; rawRows: unknown[][]; fields: string[] } | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Listen for native paste events to get clipboard data synchronously\n // This is more reliable than the async Clipboard API in iframe contexts\n grid.addEventListener('paste', (e) => this.#handleNativePaste(e), {\n signal: this.disconnectSignal,\n });\n }\n\n /** @internal */\n override detach(): void {\n this.lastCopied = null;\n this.#internalClipboard = null;\n }\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'clipboard:copy') {\n this.copy();\n return true;\n }\n return undefined;\n }\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isCopy = (event.ctrlKey || event.metaKey) && event.key === 'c';\n\n if (isCopy) {\n // Prevent the browser's default copy action so it doesn't overwrite\n // our clipboard write with whatever text is selected in the DOM.\n event.preventDefault();\n this.#handleCopy(event.target as HTMLElement);\n return true;\n }\n\n // For paste, we do NOT return true - let the native paste event fire\n // so we can access clipboardData synchronously in #handleNativePaste\n return false;\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Handle copy operation from keyboard shortcut.\n *\n * For keyboard-triggered copies, respects the current selection or\n * falls back to the focused cell from the DOM.\n */\n #handleCopy(target: HTMLElement): void {\n const selection = this.#getSelection();\n\n // Selection plugin exists but has no ranges → resolve the single active cell.\n // Range mode CLEARS `ranges` on plain keyboard navigation (arrow/Tab without\n // Shift), keeping the focused cell only as the selection `anchor`, and DOM\n // focus is NOT on a cell element after keyboard nav — so prefer the anchor\n // (a visible-column index) and only fall back to the focused DOM cell for\n // the mouse-focus / no-anchor edge. Without the anchor path, keyboard-nav\n // copy silently no-ops.\n if (selection && selection.ranges.length === 0) {\n let row: number | undefined;\n let field: string | undefined;\n if (selection.anchor) {\n row = selection.anchor.row;\n field = this.visibleColumns[selection.anchor.col]?.field;\n } else {\n const focused = this.#getFocusedCellFromDOM(target);\n if (focused) {\n row = focused.row;\n field = this.columns[focused.col]?.field;\n }\n }\n if (row == null || field == null) return;\n this.copy({ rowIndices: [row], columns: [field] });\n return;\n }\n\n // Delegate to the public copy() method (selection or full grid)\n this.copy();\n }\n\n /**\n * Handle native paste event (preferred method - works in iframes).\n * Uses synchronous clipboardData from the native paste event.\n *\n * Flow:\n * 1. Parse clipboard text\n * 2. Build target/fields info from selection\n * 3. Emit 'paste' event (for listeners)\n * 4. Call paste handler (if configured) to apply data to grid\n *\n * Selection behavior:\n * - Single cell: paste starts at cell, expands freely\n * - Range/row: paste is clipped to fit within selection bounds\n * - No selection: paste starts at row 0, col 0\n */\n #handleNativePaste(event: ClipboardEvent): void {\n // If the paste target is an editable form control or contenteditable element\n // (e.g. an active cell editor injected by EditingPlugin, a filter input, a\n // header search box), let the browser deliver the paste to that control\n // natively. Without this guard `event.preventDefault()` below would swallow\n // the user's keystroke and the editor input would never receive the text.\n if (this.#isEditablePasteTarget(event.target)) return;\n\n const text = event.clipboardData?.getData('text/plain');\n if (!text) return;\n\n // Prevent default to avoid pasting into contenteditable elements\n event.preventDefault();\n\n const parsed = parseClipboardText(text, this.config);\n\n // Get target cell from selection via query\n const selection = this.#getSelection();\n const ranges = selection?.ranges ?? [];\n const firstRange = ranges[0];\n\n // Aggregate the bounding box across ALL selected ranges. A multi-cell\n // selection is frequently expressed as several single-cell ranges (clicking\n // or dragging cell-by-cell), so inspecting `ranges[0]` alone would treat it\n // as a single cell and skip fill/clip — pasting into only the first cell.\n // min/max also normalizes reversed (bottom-up / right-to-left) drags.\n let selMinRow = Infinity;\n let selMinCol = Infinity;\n let selMaxRow = -Infinity;\n let selMaxCol = -Infinity;\n for (const r of ranges) {\n selMinRow = Math.min(selMinRow, r.from.row, r.to.row);\n selMaxRow = Math.max(selMaxRow, r.from.row, r.to.row);\n selMinCol = Math.min(selMinCol, r.from.col, r.to.col);\n selMaxCol = Math.max(selMaxCol, r.from.col, r.to.col);\n }\n\n // Determine target cell (top-left of the whole selection). Range mode\n // CLEARS `ranges` on plain keyboard navigation (arrow/Tab without Shift),\n // keeping the focused cell only as the selection `anchor`. So when there are\n // no ranges, fall back to the anchor before defaulting to (0,0) — otherwise\n // \"copy, arrow to another cell, paste\" always lands on cell (0,0) instead of\n // the active cell. Mirrors the focused-cell fallback in #handleCopy.\n const anchor = selection?.anchor ?? null;\n const targetRow = firstRange ? selMinRow : (anchor?.row ?? 0);\n const targetCol = firstRange ? selMinCol : (anchor?.col ?? 0);\n\n // Multi-cell when the selection spans more than one cell in total, whether\n // it's one large range or many single-cell ranges.\n const axis = selectionAxis(selection);\n const isMultiCell =\n !!firstRange && (axis === 'range' || axis === 'row') && (selMinRow !== selMaxRow || selMinCol !== selMaxCol);\n\n const bounds = isMultiCell ? { endRow: selMaxRow, endCol: selMaxCol } : null;\n // Selection range indices are visible-column indices (from data-col)\n const maxCol = bounds?.endCol ?? this.visibleColumns.length - 1;\n\n // Drop a copied header row so a round-trip paste writes only values into\n // cells (never the header label). Strips when this grid is configured to\n // include headers AND every cell of the first parsed row is one of this\n // grid's own column labels — independent of which column is pasted INTO, so\n // cross-column pastes (e.g. \"Source terminal\" → \"Terminal route\") strip too.\n // External pastes (first row ≠ labels) are left intact.\n this.#dropCopiedHeaderRow(parsed);\n\n // Same-grid round-trip: when the pasted text is exactly what THIS grid last\n // copied, restore the raw structured values (lossless object cells) aligned\n // with the header-stripped text rows — this path preserves exact value types\n // (e.g. Date) since it never serializes. For a cross-grid / cross-window\n // paste the in-memory buffer misses, so fall back to the structured payload\n // embedded in the clipboard's text/html. External pastes have neither and\n // use the parsed text.\n let rawRows: unknown[][] | undefined;\n let sourceFields: string[] | undefined;\n if (\n this.#internalClipboard &&\n this.#internalClipboard.text === text &&\n this.#internalClipboard.rawRows.length === parsed.length\n ) {\n rawRows = this.#internalClipboard.rawRows;\n sourceFields = this.#internalClipboard.fields;\n } else {\n const payload = parseClipboardHtmlPayload(event.clipboardData?.getData('text/html'));\n if (payload && payload.rows.length === parsed.length) {\n rawRows = payload.rows;\n sourceFields = payload.fields;\n }\n }\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 // Fill-selection tiling only applies to a bounded (multi-cell) selection.\n const fillSelection = this.config.fillSelection === true && bounds !== null;\n\n // Build field list for paste width (constrained by bounds if set). When\n // filling the selection, extend fields across the full selection width so\n // the source can be tiled to fill every selected column; otherwise cap at\n // the clipboard's own width.\n const fields: string[] = [];\n const pasteWidth = parsed[0]?.length ?? 0;\n const fieldWidth = fillSelection ? maxCol - targetCol + 1 : pasteWidth;\n for (let i = 0; i < fieldWidth && 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, fillSelection, rawRows, sourceFields };\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 * Drop a header row that this grid itself copied, so a round-trip paste\n * never lands a header label in a data cell.\n *\n * A row copied with `includeHeaders` consists entirely of this grid's own\n * column labels (`header || field`). Detect that by matching every cell of the\n * first parsed row against the full set of column labels — independent of\n * which column the user pastes INTO. This is essential for **cross-column**\n * paste (e.g. copying \"Source terminal\" and pasting into \"Terminal route\"):\n * the copied header carries the SOURCE column's label, which does not equal\n * the target column's label but is still one of this grid's labels. Matching\n * the label set fixes cross-column paste while leaving external pastes (whose\n * first row is data, not labels) untouched.\n *\n * Guarded to avoid eating a legitimate first data row:\n * 1. The grid is configured with `includeHeaders` (it copies headers), and\n * 2. there is more than one row (never strip the only row), and\n * 3. every cell of the first row equals some column's label.\n */\n #dropCopiedHeaderRow(parsed: string[][]): void {\n if (!this.config.includeHeaders) return;\n // Never strip away the only row — that would make paste a no-op.\n if (parsed.length <= 1) return;\n\n const headerRow = parsed[0];\n if (headerRow.length === 0) return;\n\n const labels = this.#columnLabels();\n for (const cell of headerRow) {\n // A cell that isn't a known column label → this is real data, keep the row.\n if (!labels.has(cell)) return;\n }\n\n parsed.shift();\n }\n\n /**\n * Set of this grid's column labels (`header || field`), matching how\n * {@link buildClipboardText} serializes the copied header row. Used to detect\n * a header row this grid copied, regardless of paste position.\n */\n #columnLabels(): Set<string> {\n const labels = new Set<string>();\n for (const col of this.columns) {\n const label = col.header || col.field;\n if (label) labels.add(label);\n }\n return labels;\n }\n\n /**\n * True when the paste event originated from a focusable form control or\n * contenteditable element — i.e. somewhere the user expects the browser's\n * native paste behavior (typing into an editor input). Lets EditingPlugin\n * editors, filter inputs, and other text fields receive paste normally\n * instead of having ClipboardPlugin swallow the event.\n */\n #isEditablePasteTarget(target: EventTarget | null): boolean {\n if (!(target instanceof Element)) return false;\n if (target.closest('input, textarea, select, [contenteditable=\"\"], [contenteditable=\"true\"]')) {\n return true;\n }\n return false;\n }\n\n /**\n * Get the current selection via Query System.\n * Returns undefined if no selection plugin is loaded or nothing is selected.\n */\n #getSelection(): SelectionQueryResult | undefined {\n const responses = this.grid?.query<SelectionQueryResult>('getSelection');\n return responses?.[0];\n }\n\n /**\n * Resolve columns and rows to include based on options and/or current selection.\n *\n * Priority for columns:\n * 1. `options.columns` (explicit field list)\n * 2. Selection union column bounds across ALL ranges (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 union row bounds across ALL ranges\n * 3. All rows\n *\n * `contains(rowOffset, colOffset)` (when non-null) reports whether a cell of\n * the resolved grid lies inside at least one selected range — callers use it\n * to blank the gaps between disjoint ranges, matching Excel's rectangular\n * multi-range copy.\n */\n #resolveData(options?: CopyOptions): {\n columns: ColumnConfig[];\n rows: Record<string, unknown>[];\n contains: ((rowOffset: number, colOffset: number) => boolean) | null;\n } {\n const selection = this.#getSelection();\n const ranges = selection?.ranges ?? [];\n const isRowAxis = selectionAxis(selection) === 'row';\n\n // Union bounding box across ALL ranges. A multi-range selection (CTRL+drag\n // repeatedly) must copy every range, not just the last one drawn; min/max\n // also normalizes reversed (bottom-up / right-to-left) drags.\n let minRow = Infinity;\n let maxRow = -Infinity;\n let minCol = Infinity;\n let maxCol = -Infinity;\n for (const r of ranges) {\n minRow = Math.min(minRow, r.from.row, r.to.row);\n maxRow = Math.max(maxRow, r.from.row, r.to.row);\n minCol = Math.min(minCol, r.from.col, r.to.col);\n maxCol = Math.max(maxCol, r.from.col, r.to.col);\n }\n\n // --- Columns ---\n let columns: ColumnConfig[];\n // Absolute visible-column index per resolved column (null when the columns\n // did not come from the selection). `resolveColumns` may drop utility /\n // hidden columns from the slice, so offsets can't be derived arithmetically.\n let colIndices: number[] | null = null;\n if (options?.columns) {\n // Caller specified exact fields\n columns = resolveColumns(this.columns, options.columns);\n } else if (ranges.length && !isRowAxis) {\n // Range/cell selection: restrict to selection column bounds\n // Selection indices are visible-column indices (from data-col)\n columns = resolveColumns(this.visibleColumns.slice(minCol, maxCol + 1));\n colIndices = columns.map((col) => this.visibleColumns.indexOf(col));\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 let rowIndices: number[] | null = null;\n if (options?.rowIndices) {\n // Caller specified exact row indices\n rows = resolveRows(this.rows as Record<string, unknown>[], options.rowIndices);\n } else if (ranges.length) {\n // Selection range: extract the union row span. Row mode selects WHOLE\n // rows and gets no column mask, so gaps between disjoint row ranges\n // (Ctrl+click rows 0, 5, 9) must be dropped outright rather than copied.\n const dropUnselectedRows = isRowAxis;\n const rowIsSelected = (r: number) =>\n ranges.some((g) => r >= Math.min(g.from.row, g.to.row) && r <= Math.max(g.from.row, g.to.row));\n rows = [];\n rowIndices = [];\n for (let r = minRow; r <= maxRow; r++) {\n const row = this.rows[r] as Record<string, unknown> | undefined;\n if (!row) continue;\n if (dropUnselectedRows && !rowIsSelected(r)) continue;\n rows.push(row);\n rowIndices.push(r);\n }\n } else {\n // No selection: all rows\n rows = this.rows as Record<string, unknown>[];\n }\n\n // Masking is only meaningful when BOTH axes came from the selection —\n // explicit `options.columns` / `options.rowIndices` (e.g. `copyRows()`)\n // would otherwise blank everything.\n const rowAbs = rowIndices;\n const colAbs = colIndices;\n const contains =\n rowAbs && colAbs\n ? (rowOffset: number, colOffset: number): boolean => {\n const row = rowAbs[rowOffset];\n const col = colAbs[colOffset];\n return ranges.some(\n (r) =>\n row >= Math.min(r.from.row, r.to.row) &&\n row <= Math.max(r.from.row, r.to.row) &&\n col >= Math.min(r.from.col, r.to.col) &&\n col <= Math.max(r.from.col, r.to.col),\n );\n }\n : null;\n\n return { columns, rows, contains };\n }\n\n /**\n * Build delimited text from resolved columns and rows.\n *\n * When no `processCell` callback is configured, uses \"copy what you see\" logic:\n * 1. Column `format` function (includes typeDefaults merged at config time)\n * 2. DOM cell textContent for columns with custom renderers (visible rows only)\n * 3. Raw value via `formatValueAsText` as final fallback\n */\n #buildText(\n columns: ColumnConfig[],\n rows: Record<string, unknown>[],\n options?: CopyOptions,\n contains?: ((rowOffset: number, colOffset: number) => boolean) | null,\n ): string {\n return this.#joinDisplayGrid(this.#buildDisplayGrid(columns, rows, options, contains), options);\n }\n\n /**\n * Build the 2D grid of DISPLAY strings for the given columns/rows (the same\n * WYSIWYG text used for `text/plain` and the `text/html` table). Header is\n * included only when configured.\n *\n * `contains` blanks cells that sit inside the selection's union bounding box\n * but outside every individual range, so a multi-range copy stays rectangular.\n */\n #buildDisplayGrid(\n columns: ColumnConfig[],\n rows: Record<string, unknown>[],\n options?: CopyOptions,\n contains?: ((rowOffset: number, colOffset: number) => boolean) | null,\n ): { header: string[] | null; rows: string[][] } {\n const includeHeaders = options?.includeHeaders ?? this.config.includeHeaders ?? false;\n const processCell = options?.processCell ?? this.config.processCell;\n const header = includeHeaders ? columns.map((c) => c.header || c.field) : null;\n const dataRows = rows.map((row, rowOffset) =>\n columns.map((col, colOffset) => {\n if (contains && !contains(rowOffset, colOffset)) return '';\n const value = resolveCellValue(row, col);\n if (processCell) return processCell(value, col.field, row);\n return this.#formatCellAsDisplayed(col, value, row);\n }),\n );\n return { header, rows: dataRows };\n }\n\n /** Join a display grid into delimited text (header row first when present). */\n #joinDisplayGrid(display: { header: string[] | null; rows: string[][] }, options?: CopyOptions): string {\n const delimiter = options?.delimiter ?? this.config.delimiter ?? '\\t';\n const newline = options?.newline ?? this.config.newline ?? '\\n';\n const lines: string[] = [];\n if (display.header) lines.push(display.header.join(delimiter));\n for (const cells of display.rows) lines.push(cells.join(delimiter));\n return lines.join(newline);\n }\n\n /**\n * Format a cell value the way the grid displays it.\n *\n * Priority:\n * 1. Column `format` function (includes typeDefaults applied at config merge time)\n * 2. DOM textContent for columns with a custom renderer (virtualized rows only)\n * 3. Raw value via `formatValueAsText`\n */\n #formatCellAsDisplayed(col: ColumnConfig, value: unknown, row: Record<string, unknown>): string {\n // 1. Column format function (covers col.format and typeDefaults)\n if (col.format) {\n try {\n const formatted = col.format(value, row);\n return formatted == null ? '' : String(formatted);\n } catch {\n // Format failed — fall through to next strategy\n }\n }\n\n // 2. DOM textContent for columns with custom renderers\n if (col.renderer || col.viewRenderer) {\n const text = this.#readCellTextFromDOM(col.field, row);\n if (text != null) return text;\n }\n\n // 3. Fallback to raw value formatting\n return formatValueAsText(value);\n }\n\n /**\n * Try to read a cell's displayed text from the DOM.\n *\n * Only works for rows currently rendered in the virtualized viewport.\n * Returns `null` if the row is not in the DOM (caller should fall back).\n */\n #readCellTextFromDOM(field: string, row: Record<string, unknown>): string | null {\n const host = this.gridElement;\n if (!host) return null;\n\n // Find the row index in the grid's current row array\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex === -1) return null;\n\n // Query the rendered cell by row index and field name\n const cell = host.querySelector<HTMLElement>(`.cell[data-row=\"${rowIndex}\"][data-field=\"${field}\"]`);\n if (!cell) return null;\n\n return cell.textContent?.trim() ?? null;\n }\n\n /**\n * Get focused cell coordinates from DOM.\n * Used as fallback when SelectionPlugin has no selection.\n */\n #getFocusedCellFromDOM(target: HTMLElement): { row: number; col: number } | null {\n // Cells carry `data-field` + `data-row` (see `data-field-cache` was never a\n // real attribute). Body cells have `data-row`; header cells don't, so the\n // `data-row` guard below excludes headers.\n const cell = target.closest('.cell[data-field]') as HTMLElement | null;\n if (!cell) return null;\n\n const field = cell.dataset.field;\n const rowIndexStr = cell.dataset.row;\n if (!field || !rowIndexStr) return null;\n\n const row = parseInt(rowIndexStr, 10);\n if (isNaN(row)) return null;\n\n const col = this.columns.findIndex((c) => c.field === field);\n if (col === -1) return null;\n\n return { row, col };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the text representation of the current selection (or specified data)\n * without writing to the system clipboard.\n *\n * Useful for previewing what would be copied, or for feeding the text into\n * a custom UI (e.g., a \"copy with column picker\" dialog).\n *\n * @param options - Control which columns/rows to include\n * @returns Delimited text, or empty string if nothing to copy\n *\n * @example Get text for specific columns\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * const text = clipboard.getSelectionAsText({\n * columns: ['name', 'email'],\n * includeHeaders: true,\n * });\n * console.log(text);\n * // \"Name\\tEmail\\nAlice\\talice@example.com\\n...\"\n * ```\n */\n getSelectionAsText(options?: CopyOptions): string {\n const { columns, rows, contains } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) return '';\n return this.#buildText(columns, rows, options, contains);\n }\n\n /**\n * Copy data to the system clipboard.\n *\n * Without options, copies the current selection (or entire grid if no selection).\n * With options, copies exactly the specified columns and/or rows — ideal for\n * \"copy with column picker\" workflows where the user selects rows first,\n * then chooses which columns to include via a dialog.\n *\n * @param options - Control which columns/rows to include\n * @returns The copied text\n *\n * @example Copy current selection (default)\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * await clipboard.copy();\n * ```\n *\n * @example Copy specific columns from specific rows\n * ```ts\n * // User selected rows in the grid, then picked columns in a dialog\n * const selectedRowIndices = [0, 3, 7];\n * const chosenColumns = ['name', 'department', 'salary'];\n * await clipboard.copy({\n * rowIndices: selectedRowIndices,\n * columns: chosenColumns,\n * includeHeaders: true,\n * });\n * ```\n */\n async copy(options?: CopyOptions): Promise<string> {\n const { columns, rows, contains } = this.#resolveData(options);\n if (columns.length === 0 || rows.length === 0) {\n return '';\n }\n\n const display = this.#buildDisplayGrid(columns, rows, options, contains);\n const text = this.#joinDisplayGrid(display, options);\n // Snapshot the RAW cell values (same column order as the text) for a\n // structured round-trip. Cloned so later row mutations don't change it.\n // Masked gaps between disjoint ranges stay blank here too, so a same-app\n // paste can't resurrect values the user never selected.\n const rawRows = rows.map((row, rowOffset) =>\n columns.map((col, colOffset) =>\n contains && !contains(rowOffset, colOffset) ? '' : cloneStructured(resolveCellValue(row, col)),\n ),\n );\n const fields = columns.map((col) => col.field);\n // Write BOTH text/plain (WYSIWYG for external targets) and text/html (a\n // table that also embeds the structured payload) so a same-app paste — even\n // cross-grid or cross-window — restores object cells losslessly.\n await copyToClipboard(text, buildClipboardHtml(display.header, display.rows, { v: 1, fields, rows: rawRows }));\n this.lastCopied = { text, timestamp: Date.now() };\n this.#internalClipboard = { text, rawRows, fields };\n this.emit<CopyDetail>('copy', {\n text,\n rowCount: rows.length,\n columnCount: columns.length,\n });\n return text;\n }\n\n /**\n * Copy specific rows by index to clipboard.\n *\n * Convenience wrapper around {@link copy} for row-based workflows.\n * Supports non-contiguous row indices (e.g., `[0, 3, 7]`).\n *\n * @param indices - Array of row indices to copy\n * @param options - Additional copy options (columns, headers, etc.)\n * @returns The copied text\n *\n * @example\n * ```ts\n * const clipboard = grid.getPluginByName('clipboard');\n * // Copy only rows 0 and 5, including just name and email columns\n * await clipboard.copyRows([0, 5], { columns: ['name', 'email'] });\n * ```\n */\n async copyRows(indices: number[], options?: Omit<CopyOptions, 'rowIndices'>): Promise<string> {\n if (indices.length === 0) return '';\n return this.copy({ ...options, rowIndices: indices });\n }\n\n /**\n * Read and parse clipboard content.\n * @returns Parsed 2D array of cell values, or null if clipboard is empty\n */\n async paste(): Promise<string[][] | null> {\n const text = await readFromClipboard();\n if (!text) return null;\n return parseClipboardText(text, this.config);\n }\n\n /**\n * Get the last copied text and timestamp.\n * @returns The last copied info or null\n */\n getLastCopied(): { text: string; timestamp: number } | null {\n return this.lastCopied;\n }\n // #endregion\n}\n\n// #region Internal Types\n\n/**\n * Range representation for clipboard operations.\n */\ninterface CellRange {\n from: { row: number; col: number };\n to: { row: number; col: number };\n}\n\n/**\n * Selection result returned by the Query System.\n * Matches the SelectionResult type from SelectionPlugin.\n */\ninterface SelectionQueryResult {\n mode: string | string[];\n activeAxis?: string;\n ranges: CellRange[];\n anchor: { row: number; col: number } | null;\n}\n\n/**\n * Axis that owns the current selection. `mode` may be an array (e.g.\n * `['range', 'column']`), so prefer `activeAxis` and fall back to a string `mode`.\n */\nfunction selectionAxis(sel: SelectionQueryResult | undefined): string | undefined {\n return sel?.activeAxis ?? (typeof sel?.mode === 'string' ? sel.mode : undefined);\n}\n// #endregion\n\n// Re-export types\nexport type { ClipboardConfig, CopyDetail, CopyOptions, PasteDetail } from './types';\n"],"mappings":"AA0BA,IAAM,iBAAgB,IAAI,QAO1B,SAAS,EAAY,GACnB,MAAe,cAAR,GAA+B,gBAAR,GAAiC,cAAR,CACzD,CAOA,IAAM,iBAAiB,IAAI,IAU3B,SAAgB,EAAe,GAC7B,IAA2B,IAAvB,EAAM,QAAQ,KAAa,OAAO,KACtC,IAAI,EAAW,EAAe,IAAI,GAKlC,YAJiB,IAAb,IACF,EAAW,OAAO,OAAO,EAAM,MAAM,MACrC,EAAe,IAAI,EAAO,IAErB,CACT,CAyDA,SAAgB,EAAc,EAAc,GAC1C,GAAW,MAAP,EAAa,OACjB,MAAM,EAAO,EAAe,GACtB,EAAI,EACV,OAAa,OAAT,EAAsB,EAAY,QAAS,EAAY,EAAE,GACzD,OAAO,UAAU,eAAe,KAAK,EAAG,GAAe,EAAE,GAtD/D,SAA0B,EAAc,GACtC,IAAI,EAAM,EACV,IAAK,IAAI,EAAI,EAAG,EAAI,EAAK,OAAQ,IAAK,CACpC,GAAW,MAAP,GAA8B,iBAAR,EAAkB,OAC5C,MAAM,EAAM,EAAK,GACjB,GAAI,EAAY,GAAM,OACtB,EAAM,EAAI,EACZ,CACA,OAA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