@toolbox-web/grid 3.7.1 → 3.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -3
- package/all.js +1 -1
- package/all.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/lib/core/types.d.ts +62 -7
- package/lib/features/registry.js +1 -1
- package/lib/plugins/clipboard/index.js +1 -1
- package/lib/plugins/column-virtualization/index.js +1 -1
- package/lib/plugins/context-menu/index.js +1 -1
- package/lib/plugins/editing/index.js +1 -1
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/editing/types.d.ts +0 -54
- package/lib/plugins/export/index.js +1 -1
- package/lib/plugins/filtering/index.js +1 -1
- package/lib/plugins/grouping-columns/index.js +1 -1
- package/lib/plugins/grouping-rows/index.js +1 -1
- package/lib/plugins/master-detail/index.js +1 -1
- package/lib/plugins/multi-sort/index.js +1 -1
- package/lib/plugins/pinned-columns/index.js +1 -1
- package/lib/plugins/pinned-rows/index.js +1 -1
- package/lib/plugins/pivot/index.js +1 -1
- package/lib/plugins/print/index.js +1 -1
- package/lib/plugins/reorder-columns/index.js +1 -1
- package/lib/plugins/responsive/index.js +1 -1
- package/lib/plugins/row-drag-drop/index.js +1 -1
- package/lib/plugins/selection/index.js +1 -1
- package/lib/plugins/server-side/index.js +1 -1
- package/lib/plugins/shell/index.js +1 -1
- package/lib/plugins/sticky-rows/index.js +1 -1
- package/lib/plugins/tooltip/index.js +1 -1
- package/lib/plugins/tree/index.js +1 -1
- package/lib/plugins/undo-redo/index.js +1 -1
- package/lib/plugins/visibility/index.js +1 -1
- package/package.json +1 -1
- package/umd/grid.all.umd.js +1 -1
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +1 -1
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/editing.umd.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../libs/grid/src/lib/core/constants.ts","../../../../../../libs/grid/src/lib/core/defaults.ts","../../../../../../libs/grid/src/lib/core/internal/aria.ts","../../../../../../libs/grid/src/lib/core/internal/utils.ts","../../../../../../libs/grid/src/lib/core/internal/value-accessor.ts","../../../../../../libs/grid/src/lib/core/internal/virtualization.ts","../../../../../../libs/grid/src/lib/core/internal/keyboard.ts","../../../../../../libs/grid/src/lib/core/internal/sanitize.ts","../../../../../../libs/grid/src/lib/core/internal/diagnostics.ts","../../../../../../libs/grid/src/lib/core/plugin/base-plugin.ts","../../../../../../libs/grid/src/lib/plugins/editing/editing.css?inline","../../../../../../libs/grid/src/lib/plugins/editing/editors.ts","../../../../../../libs/grid/src/lib/plugins/editing/internal/cell-validation.ts","../../../../../../libs/grid/src/lib/plugins/editing/internal/dirty-tracking.ts","../../../../../../libs/grid/src/lib/plugins/editing/internal/dirty-tracking-manager.ts","../../../../../../libs/grid/src/lib/plugins/editing/internal/helpers.ts","../../../../../../libs/grid/src/lib/plugins/editing/internal/editor-injection.ts","../../../../../../libs/grid/src/lib/plugins/editing/editing-plugin.ts"],"sourcesContent":["/**\n * Grid DOM Constants\n *\n * Centralized constants for CSS classes, data attributes, and selectors\n * used throughout the grid. Use these instead of magic strings.\n *\n * Note: Some constants here are used by plugins but defined in core because:\n * 1. The core CSS needs to style these elements (e.g., sticky positioning)\n * 2. Multiple plugins may share the same class names\n *\n * Plugins can define their own additional constants and export them.\n * See each plugin's index.ts for plugin-specific exports.\n */\n\n/**\n * CSS selector for focusable editor elements within a cell.\n * Used by EditingPlugin, UndoRedoPlugin, and keyboard navigation. Defined here\n * (a leaf module) rather than in `rows.ts` so `keyboard.ts` can consume it\n * without creating a rows ↔ keyboard import cycle.\n */\nexport const FOCUSABLE_EDITOR_SELECTOR =\n 'input,select,textarea,[contenteditable=\"true\"],[contenteditable=\"\"],[tabindex]:not([tabindex=\"-1\"])';\n\n// #region CSS Classes\n\n/**\n * CSS class names used in the grid's DOM.\n * Use these when adding/removing classes or querying elements.\n *\n * Classes are organized by:\n * - Core: Used by the grid core for structure and basic functionality\n * - Shared: Used by multiple features/plugins, styled by core CSS\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridClasses = {\n // ─── Core Structure ───────────────────────────────────────────────\n ROOT: 'tbw-grid-root',\n HEADER: 'header',\n HEADER_ROW: 'header-row',\n HEADER_CELL: 'header-cell',\n\n // Body structure\n ROWS_VIEWPORT: 'rows-viewport',\n ROWS_SPACER: 'rows-spacer',\n ROWS_CONTAINER: 'rows',\n\n // Row elements\n DATA_ROW: 'data-grid-row',\n GROUP_ROW: 'group-row',\n\n // Cell elements\n DATA_CELL: 'cell',\n\n // ─── Core States ──────────────────────────────────────────────────\n SELECTED: 'selected',\n FOCUSED: 'focused',\n EDITING: 'editing',\n EXPANDED: 'expanded',\n COLLAPSED: 'collapsed',\n DRAGGING: 'dragging',\n RESIZING: 'resizing',\n\n // Sorting (core feature)\n SORTABLE: 'sortable',\n SORTED_ASC: 'sorted-asc',\n SORTED_DESC: 'sorted-desc',\n\n // Visibility\n HIDDEN: 'hidden',\n\n // ─── Shared Classes (used by plugins, styled by core CSS) ────────\n // These are defined here because core CSS provides the base styling.\n // Plugins apply these classes; core CSS defines how they look.\n\n // Sticky positioning (PinnedColumnsPlugin applies, core CSS styles)\n STICKY_LEFT: 'sticky-left',\n STICKY_RIGHT: 'sticky-right',\n\n // Pinned rows (PinnedRowsPlugin applies, core CSS styles)\n PINNED_TOP: 'pinned-top',\n PINNED_BOTTOM: 'pinned-bottom',\n\n // Tree structure (TreePlugin applies, core CSS styles)\n TREE_TOGGLE: 'tree-toggle',\n TREE_INDENT: 'tree-indent',\n\n // Grouping (GroupingRowsPlugin applies, core CSS styles)\n GROUP_TOGGLE: 'group-toggle',\n GROUP_LABEL: 'group-label',\n GROUP_COUNT: 'group-count',\n\n // Selection (SelectionPlugin applies, core CSS styles)\n RANGE_SELECTION: 'range-selection',\n SELECTION_OVERLAY: 'selection-overlay',\n} as const;\n\n// #endregion\n\n// #region Data Attributes\n\n/**\n * Data attribute names used on grid elements.\n * Use these when getting/setting data attributes.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridDataAttrs = {\n // ─── Core Attributes ──────────────────────────────────────────────\n FIELD: 'data-field',\n\n /**\n * Marks a `title` the grid itself put on a cell to reveal ellipsised text\n * (WCAG SC 1.4.12). Anything that sets its own `title` on a cell must clear\n * this, or the grid will later mistake that title for its own and replace it.\n *\n * @since 3.6.0\n */\n TRUNCATED: 'data-tbw-truncated',\n\n // ─── Shared Attributes (used by plugins) ──────────────────────────\n GROUP_KEY: 'data-group-key', // GroupingRowsPlugin\n} as const;\n\n// #endregion\n\n// #region Selectors\n\n/**\n * Common CSS selectors for querying grid elements.\n * Built from the class constants for consistency.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridSelectors = {\n ROOT: `.${GridClasses.ROOT}`,\n HEADER: `.${GridClasses.HEADER}`,\n HEADER_ROW: `.${GridClasses.HEADER_ROW}`,\n HEADER_CELL: `.${GridClasses.HEADER_CELL}`,\n ROWS_VIEWPORT: `.${GridClasses.ROWS_VIEWPORT}`,\n ROWS_CONTAINER: `.${GridClasses.ROWS_CONTAINER}`,\n DATA_ROW: `.${GridClasses.DATA_ROW}`,\n DATA_CELL: `.${GridClasses.DATA_CELL}`,\n GROUP_ROW: `.${GridClasses.GROUP_ROW}`,\n\n // By data attribute\n CELL_BY_FIELD: (field: string) => `.${GridClasses.DATA_CELL}[${GridDataAttrs.FIELD}=\"${field}\"]`,\n\n // State selectors\n SELECTED_ROWS: `.${GridClasses.DATA_ROW}.${GridClasses.SELECTED}`,\n EDITING_CELL: `.${GridClasses.DATA_CELL}.${GridClasses.EDITING}`,\n} as const;\n\n// #endregion\n\n// #region CSS Custom Properties\n\n/**\n * CSS custom property names for theming.\n * Use these when programmatically setting styles.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridCSSVars = {\n // Colors\n COLOR_BG: '--tbw-color-bg',\n COLOR_FG: '--tbw-color-fg',\n COLOR_FG_MUTED: '--tbw-color-fg-muted',\n COLOR_BORDER: '--tbw-color-border',\n COLOR_ACCENT: '--tbw-color-accent',\n COLOR_HEADER_BG: '--tbw-color-header-bg',\n COLOR_HEADER_FG: '--tbw-color-header-fg',\n COLOR_SELECTION: '--tbw-color-selection',\n COLOR_ROW_HOVER: '--tbw-color-row-hover',\n COLOR_ROW_ALT: '--tbw-color-row-alt',\n\n // Sizing\n ROW_HEIGHT: '--tbw-row-height',\n HEADER_HEIGHT: '--tbw-header-height',\n CELL_PADDING: '--tbw-cell-padding',\n\n // Typography\n FONT_FAMILY: '--tbw-font-family',\n FONT_SIZE: '--tbw-font-size',\n\n // Borders\n BORDER_RADIUS: '--tbw-border-radius',\n FOCUS_OUTLINE: '--tbw-focus-outline',\n} as const;\n\n// #endregion\n\n// Type helpers\n\n/**\n * Union of all CSS class names used in the grid's DOM.\n * Use `GridClasses` to access individual values by key.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport type GridClassName = (typeof GridClasses)[keyof typeof GridClasses];\n\n/**\n * Union of all `data-*` attribute names used on grid elements.\n * Use `GridDataAttrs` to access individual values by key.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport type GridDataAttr = (typeof GridDataAttrs)[keyof typeof GridDataAttrs];\n\n/**\n * Union of all CSS custom property names (`--tbw-*`) available for theming.\n * Use `GridCSSVars` to access individual values by key.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport type GridCSSVar = (typeof GridCSSVars)[keyof typeof GridCSSVars];\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 * ARIA Accessibility Helpers\n *\n * Pure functions for managing ARIA attributes on grid elements.\n * Implements caching to avoid redundant DOM writes during scroll.\n *\n * @module internal/aria\n */\n\nimport { DEFAULT_A11Y_MESSAGES } from '../defaults';\nimport type { A11yMessages, GridConfig } from '../types';\n\n// #region Types\n\n/**\n * State for caching ARIA attributes to avoid redundant DOM writes.\n */\nexport interface AriaState {\n /** Last set row count */\n rowCount: number;\n /** Last set column count */\n colCount: number;\n /** Last set aria-label */\n ariaLabel: string | undefined;\n /** Last set aria-labelledby */\n ariaLabelledBy: string | undefined;\n /** Last set aria-describedby */\n ariaDescribedBy: string | undefined;\n /** Last set aria-roledescription */\n ariaRoleDescription: string | undefined;\n /** Last source row count announced via `dataLoaded`; used to suppress duplicate announcements */\n lastAnnouncedSourceCount: number;\n}\n\n/**\n * Create initial ARIA state.\n */\nexport function createAriaState(): AriaState {\n return {\n rowCount: -1,\n colCount: -1,\n ariaLabel: undefined,\n ariaLabelledBy: undefined,\n ariaDescribedBy: undefined,\n ariaRoleDescription: undefined,\n lastAnnouncedSourceCount: -1,\n };\n}\n\n// #endregion\n\n// #region Count Updates\n\n/**\n * Update ARIA row and column counts on grid elements.\n * Uses caching to avoid redundant DOM writes on every scroll frame.\n *\n * @param state - ARIA state for caching\n * @param rowsBodyEl - Element to set aria-rowcount/aria-colcount on\n * @param bodyEl - Element to set role=\"rowgroup\" on\n * @param rowCount - Current row count\n * @param colCount - Current column count\n * @returns true if anything was updated\n */\nexport function updateAriaCounts(\n state: AriaState,\n rowsBodyEl: HTMLElement | null,\n bodyEl: HTMLElement | null,\n rowCount: number,\n colCount: number,\n): boolean {\n // Skip if nothing changed (hot path optimization for scroll)\n if (rowCount === state.rowCount && colCount === state.colCount) {\n return false;\n }\n\n const prevRowCount = state.rowCount;\n state.rowCount = rowCount;\n state.colCount = colCount;\n\n // Update ARIA counts on inner grid element\n if (rowsBodyEl) {\n rowsBodyEl.setAttribute('aria-rowcount', String(rowCount));\n rowsBodyEl.setAttribute('aria-colcount', String(colCount));\n }\n\n // Set role=\"rowgroup\" on .rows only when there are rows (ARIA compliance)\n if (rowCount !== prevRowCount && bodyEl) {\n if (rowCount > 0) {\n bodyEl.setAttribute('role', 'rowgroup');\n } else {\n bodyEl.removeAttribute('role');\n }\n }\n\n return true;\n}\n\n// #endregion\n\n// #region Label Updates\n\n/**\n * Determine the effective aria-label for the grid.\n * Priority: explicit config > shell title > nothing\n *\n * The shell title is read from `config.shell.header.title`. The shell plugin\n * folds any light-DOM `<tbw-grid-header title>` into that field via its\n * `processConfig` hook (extraction #370), so core needs no plugin state here.\n *\n * @param config - Grid configuration (the merged effective config)\n * @returns The aria-label to use, or undefined\n */\nexport function getEffectiveAriaLabel<T>(config: GridConfig<T> | undefined): string | undefined {\n const explicitLabel = config?.gridAriaLabel;\n if (explicitLabel) return explicitLabel;\n\n return config?.shell?.header?.title ?? undefined;\n}\n\n/**\n * Update ARIA label and describedby attributes on the grid container.\n * Uses caching to avoid redundant DOM writes.\n *\n * @param state - ARIA state for caching\n * @param rowsBodyEl - Element to set aria-label/aria-describedby on\n * @param config - Grid configuration (the merged effective config)\n * @returns true if anything was updated\n */\nexport function updateAriaLabels<T>(\n state: AriaState,\n rowsBodyEl: HTMLElement | null,\n config: GridConfig<T> | undefined,\n): boolean {\n if (!rowsBodyEl) return false;\n\n let updated = false;\n\n // aria-labelledby wins per WAI-ARIA accessible-name precedence — when set,\n // `aria-label` is suppressed even if explicitly configured to avoid two\n // competing names being computed by AT.\n const ariaLabelledBy = config?.gridAriaLabelledBy;\n const effectiveLabel = ariaLabelledBy ? undefined : getEffectiveAriaLabel(config);\n\n // Update aria-labelledby only if changed\n if (ariaLabelledBy !== state.ariaLabelledBy) {\n state.ariaLabelledBy = ariaLabelledBy;\n if (ariaLabelledBy) {\n rowsBodyEl.setAttribute('aria-labelledby', ariaLabelledBy);\n } else {\n rowsBodyEl.removeAttribute('aria-labelledby');\n }\n updated = true;\n }\n\n // Update aria-label only if changed\n if (effectiveLabel !== state.ariaLabel) {\n state.ariaLabel = effectiveLabel;\n if (effectiveLabel) {\n rowsBodyEl.setAttribute('aria-label', effectiveLabel);\n } else {\n rowsBodyEl.removeAttribute('aria-label');\n }\n updated = true;\n }\n\n // Update aria-describedby only if changed\n const ariaDescribedBy = config?.gridAriaDescribedBy;\n if (ariaDescribedBy !== state.ariaDescribedBy) {\n state.ariaDescribedBy = ariaDescribedBy;\n if (ariaDescribedBy) {\n rowsBodyEl.setAttribute('aria-describedby', ariaDescribedBy);\n } else {\n rowsBodyEl.removeAttribute('aria-describedby');\n }\n updated = true;\n }\n\n // Update aria-roledescription only if changed. Apps can override the\n // announced role name (e.g. localized \"Tabell\" instead of generic \"grid\").\n const ariaRoleDescription = config?.gridAriaRoleDescription;\n if (ariaRoleDescription !== state.ariaRoleDescription) {\n state.ariaRoleDescription = ariaRoleDescription;\n if (ariaRoleDescription) {\n rowsBodyEl.setAttribute('aria-roledescription', ariaRoleDescription);\n } else {\n rowsBodyEl.removeAttribute('aria-roledescription');\n }\n updated = true;\n }\n\n return updated;\n}\n\n// #endregion\n\n// #region Live Announcements\n\n/**\n * Announce a message to screen readers via the grid's aria-live region.\n * Clears then sets text to ensure repeated messages are re-announced.\n *\n * Respects `effectiveConfig.a11y.announcements` — if set to `false`,\n * the announcement is silently skipped.\n *\n * @param gridEl - The grid host element (or any ancestor containing `.tbw-sr-only`)\n * @param message - The message to announce\n */\nexport function announce(gridEl: HTMLElement, message: string): void {\n // Check if announcements are disabled via config.\n // gridEl is always a DataGridElement at runtime — use property access safely.\n if (!gridEl) return;\n const config =\n 'effectiveConfig' in gridEl\n ? (gridEl as HTMLElement & { effectiveConfig?: GridConfig }).effectiveConfig\n : undefined;\n if (config?.a11y?.announcements === false) return;\n\n const el = gridEl.querySelector?.('.tbw-sr-only');\n if (!el) return;\n // Clear first so identical consecutive messages are still announced\n el.textContent = '';\n // `requestAnimationFrame` can be undefined if a debounced announcement fires\n // after the DOM/host environment is torn down (notably in unit tests). Fall\n // back to a direct assignment so `announce` never throws out of band.\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => {\n el.textContent = message;\n });\n } else {\n el.textContent = message;\n }\n}\n\n/**\n * Get an announcement message, preferring custom overrides from config.\n * Falls back to default English messages when no override is provided.\n *\n * @param gridEl - The grid host element\n * @param key - The message key from A11yMessages\n * @param args - Arguments to pass to the message function\n */\nexport function getA11yMessage<K extends keyof A11yMessages>(\n gridEl: HTMLElement,\n key: K,\n ...args: Parameters<A11yMessages[K]>\n): string {\n const config =\n gridEl && 'effectiveConfig' in gridEl\n ? (gridEl as HTMLElement & { effectiveConfig?: GridConfig }).effectiveConfig\n : undefined;\n const customFn = config?.a11y?.messages?.[key] as ((...a: Parameters<A11yMessages[K]>) => string) | undefined;\n if (customFn) return customFn(...args);\n return (DEFAULT_A11Y_MESSAGES[key] as (...a: Parameters<A11yMessages[K]>) => string)(...args);\n}\n\n/**\n * Announce a `dataLoaded` message — but only when the source row count has\n * actually changed since the last announcement. This prevents announcement\n * spam from internal `data-change` emits triggered by sort/filter/edit, which\n * have their own dedicated announcements.\n *\n * @param gridEl - The grid host element\n * @param state - ARIA state (tracks last announced count)\n * @param sourceRowCount - Current source row count\n */\nexport function announceDataLoaded(gridEl: HTMLElement, state: AriaState, sourceRowCount: number): void {\n if (sourceRowCount === state.lastAnnouncedSourceCount) return;\n const previousAnnouncedSourceCount = state.lastAnnouncedSourceCount;\n state.lastAnnouncedSourceCount = sourceRowCount;\n // Skip only the initial sentinel → 0 transition (empty grid mount). A later\n // transition to 0 (e.g. data cleared / reloaded to an empty result set) should\n // still announce so screen-reader users hear that the grid is now empty.\n if (sourceRowCount === 0 && previousAnnouncedSourceCount < 0) return;\n announce(gridEl, getA11yMessage(gridEl, 'dataLoaded', sourceRowCount));\n}\n\n// #endregion\n","// #region Environment Helpers\n\n/**\n * Check if we're running in a development environment.\n * Returns true for localhost or when NODE_ENV !== 'production'.\n * Used to show warnings only in development.\n */\nexport function isDevelopment(): boolean {\n // Check for localhost (browser environment)\n if (typeof window !== 'undefined' && window.location) {\n const hostname = window.location.hostname;\n if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1') {\n return true;\n }\n }\n // Check for NODE_ENV (build-time or SSR)\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n return true;\n }\n return false;\n}\n\n// #endregion\n\n// #region Cell Rendering Helpers\n\n/**\n * Generate accessible HTML for a boolean cell.\n * Uses role=\"checkbox\" with proper aria attributes.\n */\nexport function booleanCellHTML(value: boolean): string {\n return `<span role=\"checkbox\" aria-checked=\"${value}\" aria-label=\"${value}\">${value ? '🗹' : '☐'}</span>`;\n}\n\n/**\n * Format a date value for display.\n * Handles Date objects, timestamps, and date strings.\n * Returns empty string for invalid dates.\n */\nexport function formatDateValue(value: unknown): string {\n if (value == null || value === '') return '';\n if (value instanceof Date) {\n return isNaN(value.getTime()) ? '' : value.toLocaleDateString();\n }\n if (typeof value === 'number' || typeof value === 'string') {\n const d = new Date(value);\n return isNaN(d.getTime()) ? '' : d.toLocaleDateString();\n }\n return '';\n}\n\n/**\n * Get the row index from a cell element's data-row attribute.\n * Falls back to calculating from parent row's DOM position if data-row is missing.\n * Returns -1 if no valid row index is found.\n */\nexport function getRowIndexFromCell(cell: Element | null): number {\n if (!cell) return -1;\n const attr = cell.getAttribute('data-row');\n if (attr) return parseInt(attr, 10);\n\n // Fallback: find the parent .data-grid-row and calculate index from siblings\n const rowEl = cell.closest('.data-grid-row');\n if (!rowEl) return -1;\n\n const parent = rowEl.parentElement;\n if (!parent) return -1;\n\n // Get all data-grid-row siblings and find this row's index\n const rows = parent.querySelectorAll(':scope > .data-grid-row');\n for (let i = 0; i < rows.length; i++) {\n if (rows[i] === rowEl) return i;\n }\n return -1;\n}\n\n/**\n * Get the column index from a cell element's data-col attribute.\n * Returns -1 if no valid column index is found.\n */\nexport function getColIndexFromCell(cell: Element | null): number {\n if (!cell) return -1;\n const attr = cell.getAttribute('data-col');\n return attr ? parseInt(attr, 10) : -1;\n}\n\n/**\n * Clear all cell-focus styling from a root element.\n * Used when changing focus or when selection plugin takes over focus management.\n */\nexport function clearCellFocus(root: Element | null): void {\n if (!root) return;\n root.querySelectorAll('.cell-focus').forEach((el) => el.classList.remove('cell-focus'));\n}\n// #endregion\n\n// #region RTL Helpers\n\n/** Text direction */\nexport type TextDirection = 'ltr' | 'rtl';\n\n/**\n * Get the text direction for an element.\n * Reads from the computed style, which respects the `dir` attribute on the element\n * or any ancestor, as well as CSS `direction` property.\n *\n * @param element - The element to check direction for\n * @returns 'ltr' or 'rtl'\n *\n * @example\n * ```typescript\n * // Detect grid's direction\n * const dir = getDirection(gridElement);\n * if (dir === 'rtl') {\n * // Handle RTL layout\n * }\n * ```\n */\nexport function getDirection(element: Element): TextDirection {\n // Try computed style first (works in real browsers)\n try {\n const computedDir = getComputedStyle(element).direction;\n if (computedDir === 'rtl') return 'rtl';\n } catch {\n // getComputedStyle may fail in some test environments\n }\n\n // Fallback: check dir attribute on element or ancestors\n // This handles test environments where getComputedStyle may not reflect dir attribute\n try {\n const dirAttr = element.closest?.('[dir]')?.getAttribute('dir');\n if (dirAttr === 'rtl') return 'rtl';\n } catch {\n // closest may not be available on mock elements\n }\n\n return 'ltr';\n}\n\n/**\n * Check if an element is in RTL mode.\n *\n * @param element - The element to check\n * @returns true if the element's text direction is right-to-left\n */\nexport function isRTL(element: Element): boolean {\n return getDirection(element) === 'rtl';\n}\n\n/**\n * Resolve a logical inline position to a physical position based on text direction.\n *\n * - `'start'` → `'left'` in LTR, `'right'` in RTL\n * - `'end'` → `'right'` in LTR, `'left'` in RTL\n * - `'left'` / `'right'` → unchanged (physical values)\n *\n * @param position - Logical or physical position\n * @param direction - Text direction ('ltr' or 'rtl')\n * @returns Physical position ('left' or 'right')\n *\n * @example\n * ```typescript\n * resolveInlinePosition('start', 'ltr'); // 'left'\n * resolveInlinePosition('start', 'rtl'); // 'right'\n * resolveInlinePosition('left', 'rtl'); // 'left' (unchanged)\n * ```\n */\nexport function resolveInlinePosition(\n position: 'left' | 'right' | 'start' | 'end',\n direction: TextDirection,\n): 'left' | 'right' {\n if (position === 'left' || position === 'right') {\n return position;\n }\n if (direction === 'rtl') {\n return position === 'start' ? 'right' : 'left';\n }\n return position === 'start' ? 'left' : 'right';\n}\n// #endregion\n","/**\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 * Row Virtualization Module\n *\n * Provides all virtualization-related functionality for the grid:\n *\n * 1. **Position Cache** (index-based): Maps row index → {offset, height, measured}\n * - Rebuilt when row count changes (expand/collapse, filter)\n * - Used for scroll position → row index lookups (binary search)\n *\n * 2. **Height Cache** (identity-based): Maps row identity → height\n * - Persists across expand/collapse\n * - Uses rowId string keys when available, WeakMap otherwise\n * - Synthetic rows use __rowCacheKey for stable identity\n *\n * 3. **Virtual Window**: Computes which rows to render based on scroll position\n *\n * 4. **Row Measurement**: Measures rendered row heights from DOM\n */\n\n// #region Types\n\n/**\n * Position entry for a single row in the position cache.\n * @category Plugin Development\n */\nexport interface RowPosition {\n /** Cumulative offset from top in pixels */\n offset: number;\n /** Row height in pixels */\n height: number;\n /** Whether this is a measured value (true) or estimate (false) */\n measured: boolean;\n}\n\n/**\n * Height cache that persists row heights across position cache rebuilds.\n * Uses dual storage: Map for string keys (rowId, __rowCacheKey) and WeakMap for object refs.\n * @category Plugin Development\n */\nexport interface HeightCache {\n /** Heights keyed by string (for synthetic rows with __rowCacheKey or rowId-keyed rows) */\n byKey: Map<string, number>;\n /** Heights keyed by object reference (for data rows without rowId) */\n byRef: WeakMap<object, number>;\n}\n\n/**\n * Configuration for the position cache.\n */\nexport interface PositionCacheConfig<T = unknown> {\n /** Function to get row ID (if configured) */\n rowId?: (row: T) => string | number;\n}\n\n// #endregion\n\n// #region Height Cache Operations\n\n/**\n * Create a new empty height cache.\n */\nexport function createHeightCache(): HeightCache {\n return {\n byKey: new Map(),\n byRef: new WeakMap(),\n };\n}\n\n/**\n * Get the cache key for a row.\n * Returns string for synthetic rows (__rowCacheKey) or rowId-keyed rows,\n * or the row object itself for WeakMap lookup.\n */\nexport function getRowCacheKey<T>(row: T, rowId?: (row: T) => string | number): string | T {\n if (!row || typeof row !== 'object') return row;\n\n // 1. Synthetic rows: plugins MUST add __rowCacheKey\n if ('__rowCacheKey' in row) {\n return (row as { __rowCacheKey: string }).__rowCacheKey;\n }\n\n // 2. rowId property directly on the row (common pattern)\n if ('rowId' in row && (row as { rowId: string | number }).rowId != null) {\n return `id:${(row as { rowId: string | number }).rowId}`;\n }\n\n // 3. User-provided rowId function (if configured)\n if (rowId) {\n return `id:${rowId(row)}`;\n }\n\n // 4. Object identity (for WeakMap)\n return row;\n}\n\n/**\n * Get cached height for a row.\n * @returns Cached height or undefined if not cached\n */\nexport function getCachedHeight<T>(\n cache: HeightCache,\n row: T,\n rowId?: (row: T) => string | number,\n): number | undefined {\n const key = getRowCacheKey(row, rowId);\n\n if (typeof key === 'string') {\n return cache.byKey.get(key);\n }\n\n // Object key - use WeakMap\n if (key && typeof key === 'object') {\n return cache.byRef.get(key);\n }\n\n return undefined;\n}\n\n/**\n * Set cached height for a row.\n */\nexport function setCachedHeight<T>(\n cache: HeightCache,\n row: T,\n height: number,\n rowId?: (row: T) => string | number,\n): void {\n const key = getRowCacheKey(row, rowId);\n\n if (typeof key === 'string') {\n cache.byKey.set(key, height);\n } else if (key && typeof key === 'object') {\n cache.byRef.set(key, height);\n }\n}\n\n// #endregion\n\n// #region Position Cache Operations\n\n/**\n * Rebuild position cache preserving known heights from height cache.\n * Called when row count changes (expand/collapse, filter, data change).\n *\n * @param rows - Array of row data\n * @param heightCache - Height cache with persisted measurements\n * @param estimatedHeight - Estimated height for unmeasured rows\n * @param config - Position cache configuration\n * @param getPluginHeight - Optional function to get height from plugins\n * @returns New position cache\n */\nexport function rebuildPositionCache<T>(\n rows: T[],\n heightCache: HeightCache,\n estimatedHeight: number,\n config: PositionCacheConfig<T>,\n getPluginHeight?: (row: T, index: number) => number | undefined,\n): RowPosition[] {\n const cache: RowPosition[] = new Array(rows.length);\n let offset = 0;\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n\n // Height resolution order:\n // 1. Plugin's getRowHeight() (for synthetic rows with known heights)\n let height = getPluginHeight?.(row, i);\n let measured = height !== undefined;\n\n // 2. Cached height from previous measurements\n if (height === undefined) {\n height = getCachedHeight(heightCache, row, config.rowId);\n measured = height !== undefined;\n }\n\n // 3. Fall back to estimate\n if (height === undefined) {\n height = estimatedHeight;\n measured = false;\n }\n\n cache[i] = { offset, height, measured };\n offset += height;\n }\n\n return cache;\n}\n\n/**\n * Update a single row's height in the position cache.\n * Recalculates offsets for all subsequent rows.\n *\n * @param cache - Position cache to update\n * @param index - Row index to update\n * @param newHeight - New measured height\n */\nexport function updateRowHeight(cache: RowPosition[], index: number, newHeight: number): void {\n if (index < 0 || index >= cache.length) return;\n\n const entry = cache[index];\n const heightDiff = newHeight - entry.height;\n\n // Latch `measured` even when the height is unchanged, otherwise callers that enqueue on\n // `!measured` re-measure the same row on every render pass.\n entry.measured = true;\n\n if (heightDiff === 0) return;\n\n // Update this row\n entry.height = newHeight;\n\n // Recalculate offsets for all subsequent rows\n for (let i = index + 1; i < cache.length; i++) {\n cache[i].offset += heightDiff;\n }\n}\n\nexport interface RowHeightChange {\n /** Row index into the position cache. */\n index: number;\n /** Measured height in pixels. */\n height: number;\n}\n\n/**\n * Update multiple row heights while recalculating the affected cache suffix once.\n *\n * @param cache - Position cache to update (mutated in place)\n * @param changes - Height changes in any order; each row index should occur at most once\n */\nexport function updateRowHeights(cache: RowPosition[], changes: RowHeightChange[]): void {\n if (changes.length === 0 || cache.length === 0) return;\n\n // Callers usually collect in DOM order, which is already ascending — skip the copy then.\n let sortedChanges = changes;\n for (let i = 1; i < changes.length; i++) {\n if (changes[i].index < changes[i - 1].index) {\n sortedChanges = [...changes].sort((a, b) => a.index - b.index);\n break;\n }\n }\n\n let changeIndex = 0;\n while (changeIndex < sortedChanges.length && sortedChanges[changeIndex].index < 0) changeIndex++;\n if (changeIndex >= sortedChanges.length || sortedChanges[changeIndex].index >= cache.length) return;\n\n let cumulativeDiff = 0;\n const firstChangedIndex = sortedChanges[changeIndex].index;\n for (let index = firstChangedIndex; index < cache.length; index++) {\n const entry = cache[index];\n entry.offset += cumulativeDiff;\n\n while (changeIndex < sortedChanges.length && sortedChanges[changeIndex].index === index) {\n const height = sortedChanges[changeIndex].height;\n const heightDiff = height - entry.height;\n entry.measured = true;\n if (heightDiff !== 0) {\n entry.height = height;\n cumulativeDiff += heightDiff;\n }\n changeIndex++;\n }\n }\n}\n\n/**\n * Get total content height from position cache.\n *\n * @param cache - Position cache\n * @returns Total height in pixels\n */\nexport function getTotalHeight(cache: RowPosition[]): number {\n if (cache.length === 0) return 0;\n const last = cache[cache.length - 1];\n return last.offset + last.height;\n}\n\n// #endregion\n\n// #region Binary Search\n\n/**\n * Find the row index at a given scroll offset using binary search.\n * Returns the index of the row that contains the given pixel offset.\n *\n * @param cache - Position cache\n * @param targetOffset - Scroll offset in pixels\n * @returns Row index at that offset, or -1 if cache is empty\n */\nexport function getRowIndexAtOffset(cache: RowPosition[], targetOffset: number): number {\n if (cache.length === 0) return -1;\n if (targetOffset <= 0) return 0;\n\n let low = 0;\n let high = cache.length - 1;\n\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const entry = cache[mid];\n const entryEnd = entry.offset + entry.height;\n\n if (targetOffset < entry.offset) {\n high = mid - 1;\n } else if (targetOffset >= entryEnd) {\n low = mid + 1;\n } else {\n // targetOffset is within this row\n return mid;\n }\n }\n\n // Return the closest row (low will be just past the target)\n return Math.max(0, Math.min(low, cache.length - 1));\n}\n\n// #endregion\n\n// #region Statistics\n\n/**\n * Calculate the average measured height.\n * Used for estimating unmeasured rows.\n *\n * @param cache - Position cache\n * @param defaultHeight - Default height to use if no measurements\n * @returns Average measured height\n */\nexport function calculateAverageHeight(cache: RowPosition[], defaultHeight: number): number {\n let totalHeight = 0;\n let measuredCount = 0;\n\n for (const entry of cache) {\n if (entry.measured) {\n totalHeight += entry.height;\n measuredCount++;\n }\n }\n\n return measuredCount > 0 ? totalHeight / measuredCount : defaultHeight;\n}\n\n/**\n * Count how many rows have been measured.\n *\n * @param cache - Position cache\n * @returns Number of measured rows\n */\nexport function countMeasuredRows(cache: RowPosition[]): number {\n let count = 0;\n for (const entry of cache) {\n if (entry.measured) count++;\n }\n return count;\n}\n\n// #endregion\n// #region Row Measurement\n\n/**\n * Result of measuring rendered row heights.\n */\nexport interface RowMeasurementResult {\n /** Whether any heights changed */\n hasChanges: boolean;\n /** Updated measured row count */\n measuredCount: number;\n /** Updated average height */\n averageHeight: number;\n}\n\n/**\n * Context for measuring rendered rows.\n */\nexport interface RowMeasurementContext<T> {\n /** Position cache to update */\n positionCache: RowPosition[];\n /** Height cache for persistence */\n heightCache: HeightCache;\n /** Row data array */\n rows: T[];\n /** Default row height */\n defaultHeight: number;\n /** Start index of rendered window */\n start: number;\n /** End index of rendered window (exclusive) */\n end: number;\n /** Function to get plugin height for a row */\n getPluginHeight?: (row: T, index: number) => number | undefined;\n /** Function to get row ID for height cache keying */\n getRowId?: (row: T) => string | number;\n}\n\n/**\n * Measure rendered row heights from DOM elements and update caches.\n * Returns measurement statistics for updating virtualization state.\n *\n * @param context - Measurement context with all dependencies\n * @param rowElements - NodeList of rendered row elements\n * @returns Measurement result with flags and statistics\n */\nexport function measureRenderedRowHeights<T>(\n context: RowMeasurementContext<T>,\n rowElements: NodeListOf<Element>,\n): RowMeasurementResult {\n const { positionCache, heightCache, rows, start, end, getPluginHeight, getRowId } = context;\n\n let hasChanges = false;\n const heightChanges: RowHeightChange[] = [];\n\n rowElements.forEach((rowEl) => {\n const rowIndexStr = (rowEl as HTMLElement).dataset.rowIndex;\n if (!rowIndexStr) return;\n\n const rowIndex = parseInt(rowIndexStr, 10);\n if (rowIndex < start || rowIndex >= end || rowIndex >= rows.length) return;\n\n const row = rows[rowIndex];\n\n // Check if a plugin provides the height for this row\n const pluginHeight = getPluginHeight?.(row, rowIndex);\n\n if (pluginHeight !== undefined) {\n // Plugin provides height - use it for position cache\n const currentEntry = positionCache[rowIndex];\n if (!currentEntry.measured || Math.abs(currentEntry.height - pluginHeight) > 1) {\n heightChanges.push({ index: rowIndex, height: pluginHeight });\n hasChanges = true;\n }\n return; // Don't measure DOM for plugin-managed rows\n }\n\n // No plugin height - use DOM measurement\n const measuredHeight = (rowEl as HTMLElement).offsetHeight;\n\n if (measuredHeight > 0) {\n const currentEntry = positionCache[rowIndex];\n\n // Only update if height differs significantly (> 1px to avoid oscillation)\n if (!currentEntry.measured || Math.abs(currentEntry.height - measuredHeight) > 1) {\n heightChanges.push({ index: rowIndex, height: measuredHeight });\n setCachedHeight(heightCache, row, measuredHeight, getRowId);\n hasChanges = true;\n }\n }\n });\n\n updateRowHeights(positionCache, heightChanges);\n\n // Recompute stats\n const measuredCount = hasChanges ? countMeasuredRows(positionCache) : 0;\n const averageHeight = hasChanges ? calculateAverageHeight(positionCache, context.defaultHeight) : 0;\n\n return { hasChanges, measuredCount, averageHeight };\n}\n\n/**\n * Compute measurement statistics for a position cache, excluding plugin-managed rows.\n * Used after rebuilding position cache to get accurate averages for non-plugin rows.\n *\n * @param cache - Position cache\n * @param rows - Row data array\n * @param defaultHeight - Default height if no measurements\n * @param getPluginHeight - Function to check if plugin manages row height\n * @returns Object with measured count and average height\n */\nexport function computeAverageExcludingPluginRows<T>(\n cache: RowPosition[],\n rows: T[],\n defaultHeight: number,\n getPluginHeight?: (row: T, index: number) => number | undefined,\n): { measuredCount: number; averageHeight: number } {\n let measuredCount = 0;\n let totalMeasured = 0;\n\n for (let i = 0; i < cache.length; i++) {\n const entry = cache[i];\n if (entry.measured) {\n // Only include in average if plugin doesn't provide height for this row\n const pluginHeight = getPluginHeight?.(rows[i], i);\n if (pluginHeight === undefined) {\n totalMeasured += entry.height;\n measuredCount++;\n }\n }\n }\n\n return {\n measuredCount,\n averageHeight: measuredCount > 0 ? totalMeasured / measuredCount : defaultHeight,\n };\n}\n\n// #endregion\n\n// #region Scroll Mapping (max element-height cap)\n\n/**\n * Maximum spacer element height (px) before browsers cap the rendered height.\n *\n * Chromium's hard cap is `2^25 = 33,554,432` px; Firefox/Safari are similar or larger.\n * We pick `33,500,000` — ~54 KB of headroom under Chromium's cap so that floating-point\n * drift in the fractional mapping math (`scrollTop * rMax / sMax`) cannot push a computed\n * spacer position past the engine cap and silently truncate.\n *\n * For datasets where `totalRows * rowHeight` exceeds this value, the faux-vscroll\n * spacer would silently truncate, making the tail of the dataset unreachable via\n * the native scrollbar / `Ctrl+End`. The grid switches to fractional scroll mapping\n * above this threshold — see {@link computeScrollMapping}.\n *\n * @category Plugin Development\n * @since 2.13.0\n */\nexport const MAX_ELEMENT_HEIGHT_PX = 33_500_000;\n\n/**\n * Mapping between native `scrollTop` (clamped spacer space) and \"virtual\" scroll\n * position (raw row-content space). See {@link computeScrollMapping}.\n *\n * @category Plugin Development\n * @since 2.13.0\n */\nexport interface ScrollMapping {\n /** Raw row-content height in pixels (totalRows * rowHeight or sum of variable heights). */\n rawContentHeight: number;\n /** Effective spacer DOM height — `min(rawContentHeight, maxSpacerHeight)`. */\n spacerHeight: number;\n /** Viewport height used for computing scrollable extents. */\n viewportHeight: number;\n /** True when `rawContentHeight > maxSpacerHeight` — fractional mapping is active. */\n capped: boolean;\n}\n\n/**\n * Compute a mapping between the spacer's native scrollTop and the virtual\n * row-content scroll offset.\n *\n * For datasets within `maxSpacerHeight`, mapping is identity (no transform).\n * Above the cap, the spacer is clamped and `scrollTop` units no longer equal\n * row-content units — call {@link toVirtualScrollTop} / {@link fromVirtualScrollTop}\n * to translate between the two coordinate spaces.\n *\n * @category Plugin Development\n * @since 2.13.0\n */\nexport function computeScrollMapping(\n rawContentHeight: number,\n viewportHeight: number,\n maxSpacerHeight = MAX_ELEMENT_HEIGHT_PX,\n): ScrollMapping {\n const spacerHeight = Math.min(rawContentHeight, maxSpacerHeight);\n return {\n rawContentHeight,\n spacerHeight,\n viewportHeight,\n capped: rawContentHeight > maxSpacerHeight,\n };\n}\n\n/**\n * Translate a native `scrollTop` (spacer space) into a virtual scroll offset\n * in raw row-content space. Identity when the mapping is not capped.\n *\n * The result is clamped to `[0, rawContentHeight - viewportHeight]` so callers\n * never index past the dataset, even when the spacer's actual scrollable extent\n * slightly exceeds `spacerHeight - viewportHeight` (e.g. when a horizontal scrollbar\n * adds bottom padding to the faux spacer).\n *\n * @category Plugin Development\n * @since 2.13.0\n */\nexport function toVirtualScrollTop(scrollTop: number, mapping: ScrollMapping): number {\n if (!mapping.capped) return scrollTop;\n const sMax = mapping.spacerHeight - mapping.viewportHeight;\n const rMax = mapping.rawContentHeight - mapping.viewportHeight;\n if (sMax <= 0 || rMax <= 0) return scrollTop;\n const virtual = (scrollTop * rMax) / sMax;\n if (virtual < 0) return 0;\n if (virtual > rMax) return rMax;\n return virtual;\n}\n\n/**\n * Translate a virtual scroll offset (raw row-content space) into a native\n * `scrollTop` value (spacer space). Identity when the mapping is not capped.\n *\n * @category Plugin Development\n * @since 2.13.0\n */\nexport function fromVirtualScrollTop(virtualTop: number, mapping: ScrollMapping): number {\n if (!mapping.capped) return virtualTop;\n const sMax = mapping.spacerHeight - mapping.viewportHeight;\n const rMax = mapping.rawContentHeight - mapping.viewportHeight;\n if (sMax <= 0 || rMax <= 0) return virtualTop;\n return (virtualTop * sMax) / rMax;\n}\n\n/**\n * Identity scroll mapping (no cap applied). Useful as a default in places that\n * don't yet know the dataset extents. `viewportHeight` is `0` until the first\n * `calculateTotalSpacerHeight` call populates the real extents — safe because\n * `capped: false` short-circuits both translation helpers before they read it.\n *\n * @category Plugin Development\n * @since 2.13.0\n */\nexport function createIdentityScrollMapping(): ScrollMapping {\n return { rawContentHeight: 0, spacerHeight: 0, viewportHeight: 0, capped: false };\n}\n\n// #endregion\n\n// #region Scroll Transform\n\n/**\n * Sub-pixel `translateY` for the `.rows` element at a given native scroll position.\n *\n * Bypass mode (all rows rendered) tracks the raw scroll offset directly. Virtualized mode\n * offsets only the remainder past the window's first row, and rounds that start down to an\n * even index so DOM `nth-child(even)` zebra parity keeps matching data-row parity.\n *\n * @param v Virtual state (structural subset of `VirtualState`).\n * @param rawScrollTop Native `scrollTop` of the faux scrollbar (clamped spacer space).\n */\nexport function computeRowsTranslateY(\n v: {\n rowHeight: number;\n bypassThreshold: number;\n variableHeights: boolean;\n positionCache: RowPosition[] | null;\n scrollMapping: ScrollMapping;\n },\n totalRows: number,\n rawScrollTop: number,\n): number {\n if (totalRows <= v.bypassThreshold) return -rawScrollTop;\n\n const currentScrollTop = toVirtualScrollTop(rawScrollTop, v.scrollMapping);\n const cache = v.positionCache;\n let startRowOffset: number;\n\n if (v.variableHeights && cache && cache.length > 0) {\n let rawStart = getRowIndexAtOffset(cache, currentScrollTop);\n if (rawStart === -1) rawStart = 0;\n const evenAlignedStart = rawStart - (rawStart % 2);\n startRowOffset = cache[evenAlignedStart]?.offset ?? evenAlignedStart * v.rowHeight;\n } else {\n const rawStart = Math.floor(currentScrollTop / v.rowHeight);\n startRowOffset = (rawStart - (rawStart % 2)) * v.rowHeight;\n }\n\n return -(currentScrollTop - startRowOffset);\n}\n\n// #endregion\n\n// #region Fixed-Height Virtual Window\n\n/**\n * Result of computing a virtual window for fixed-height rows.\n * Used by plugins like FilteringPlugin for virtualized dropdowns.\n */\nexport interface VirtualWindow {\n /** First row index to render (inclusive) */\n start: number;\n /** Last row index to render (exclusive) */\n end: number;\n /** Pixel offset to apply to the rows container (translateY) */\n offsetY: number;\n /**\n * Effective spacer DOM height — use this for the scrollable spacer element.\n * Equal to `min(totalRows * rowHeight, maxSpacerHeight)`. Above the cap this\n * is clamped; use {@link VirtualWindow.rawContentHeight} for the un-clamped value.\n */\n totalHeight: number;\n /**\n * Raw, un-clamped row-content height (`totalRows * rowHeight`). Equal to\n * `totalHeight` when the dataset is below `maxSpacerHeight`.\n *\n * @since 2.13.0\n */\n rawContentHeight: number;\n}\n\n/** Parameters for computing the virtual window */\nexport interface VirtualWindowParams {\n /** Total number of rows */\n totalRows: number;\n /** Height of the viewport in pixels */\n viewportHeight: number;\n /** Current scroll top position */\n scrollTop: number;\n /** Height of each row in pixels */\n rowHeight: number;\n /** Number of extra rows to render above/below viewport */\n overscan: number;\n /**\n * Optional cap on the spacer's DOM height. When `totalRows * rowHeight` exceeds\n * this value, `scrollTop` is treated as a spacer-space position and translated\n * to virtual row-content space via fractional mapping. Defaults to {@link MAX_ELEMENT_HEIGHT_PX}.\n * Pass `Infinity` to disable.\n *\n * @since 2.13.0\n */\n maxSpacerHeight?: number;\n}\n\n/**\n * Compute the virtual row window based on scroll position and viewport.\n * Simple fixed-height implementation for plugins needing basic virtualization.\n *\n * For datasets where `totalRows * rowHeight > maxSpacerHeight`, scroll position\n * is mapped fractionally so the entire dataset stays reachable past the browser's\n * single-element height cap (Chromium ~33.5M px). See {@link computeScrollMapping}.\n *\n * @param params - Parameters for computing the window\n * @returns VirtualWindow with start/end indices and transforms\n */\nexport function computeVirtualWindow(params: VirtualWindowParams): VirtualWindow {\n const { totalRows, viewportHeight, scrollTop, rowHeight, overscan, maxSpacerHeight = MAX_ELEMENT_HEIGHT_PX } = params;\n\n const visibleRows = Math.ceil(viewportHeight / rowHeight);\n const rawContentHeight = totalRows * rowHeight;\n const mapping = computeScrollMapping(rawContentHeight, viewportHeight, maxSpacerHeight);\n const virtualScrollTop = toVirtualScrollTop(scrollTop, mapping);\n\n // Render overscan rows in each direction (total window = visible + 2*overscan)\n let start = Math.floor(virtualScrollTop / rowHeight) - overscan;\n if (start < 0) start = 0;\n\n let end = start + visibleRows + overscan * 2;\n if (end > totalRows) end = totalRows;\n\n // Ensure start is adjusted if we hit the end\n if (end === totalRows && start > 0) {\n start = Math.max(0, end - visibleRows - overscan * 2);\n }\n\n return {\n start,\n end,\n offsetY: start * rowHeight,\n totalHeight: mapping.spacerHeight,\n rawContentHeight,\n };\n}\n\n/**\n * Determine if virtualization should be bypassed for small datasets.\n * When there are very few items, the overhead of virtualization isn't worth it.\n *\n * @param totalRows - Total number of items\n * @param threshold - Bypass threshold (skip virtualization if totalRows <= threshold)\n * @returns True if virtualization should be bypassed\n */\nexport function shouldBypassVirtualization(totalRows: number, threshold: number): boolean {\n return totalRows <= threshold;\n}\n\n// #endregion\n","/**\n * Central keyboard handler attached to the host element. Manages navigation, paging,\n * and edit lifecycle triggers while respecting active form field interactions.\n */\nimport { FOCUSABLE_EDITOR_SELECTOR, GridClasses } from '../constants';\nimport type { GridHost } from '../types';\nimport { clearCellFocus, isRTL } from './utils';\nimport { readCellField } from './value-accessor';\nimport { fromVirtualScrollTop, toVirtualScrollTop } from './virtualization';\n\n/** Commit active row edit if the editing plugin provides this method. */\nfunction tryCommitEdit(grid: GridHost): void {\n if (typeof grid.commitActiveRowEdit === 'function') grid.commitActiveRowEdit();\n}\n\nfunction isFormField(el: HTMLElement | null): boolean {\n if (!el) return false;\n const tag = el.tagName;\n if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') return true;\n if (el.isContentEditable) return true;\n return false;\n}\n\n/** True while a row-scoped edit session is active. */\nfunction isRowEditing(grid: GridHost): boolean {\n return grid._activeEditRows !== undefined && grid._activeEditRows !== -1;\n}\n\n// #region Keyboard Handler\n/**\n * Guard chain deciding whether this keydown belongs to something other than\n * cell navigation and must be left alone.\n */\nfunction shouldIgnoreKeyDown(grid: GridHost, e: KeyboardEvent, target: HTMLElement | null): boolean {\n // Keyboard events whose target lives inside the grid host but OUTSIDE the\n // rows body (toolpanel inputs/buttons, shell-header controls, light-DOM\n // children of <tbw-grid>) own their own keyboard interactions. Treating\n // ArrowUp/ArrowDown/Enter on such a target as cell navigation steals the\n // user's actual interaction target on the very next render cycle.\n // Cells and the grid host itself remain valid navigation targets.\n if (target && target !== grid && !target.closest?.('.rows-body')) return true;\n\n if (isFormField(target)) {\n switch (e.key) {\n // Home/End and horizontal arrows navigate within the text input; Enter\n // and Escape are handled by the input's own handlers first.\n case 'Home':\n case 'End':\n case 'ArrowLeft':\n case 'ArrowRight':\n case 'Enter':\n case 'Escape':\n return true;\n case 'ArrowUp':\n case 'ArrowDown':\n // Number spinners own the vertical arrows; other fields fall through.\n if ((target as HTMLInputElement).tagName === 'INPUT' && (target as HTMLInputElement).type === 'number') {\n return true;\n }\n break;\n }\n }\n\n const colType = grid._visibleColumns[grid._focusCol]?.type;\n return isRowEditing(grid) && colType === 'select' && (e.key === 'ArrowDown' || e.key === 'ArrowUp');\n}\n\n/** Tab / Shift+Tab: advance one cell, wrapping to the next/previous row. */\nfunction navigateTab(grid: GridHost, e: KeyboardEvent, maxRow: number, maxCol: number): void {\n e.preventDefault();\n if (!e.shiftKey) {\n if (grid._focusCol < maxCol) {\n grid._focusCol += 1;\n return;\n }\n tryCommitEdit(grid);\n if (grid._focusRow < maxRow) {\n grid._focusRow += 1;\n grid._focusCol = 0;\n }\n return;\n }\n if (grid._focusCol > 0) {\n grid._focusCol -= 1;\n } else if (grid._focusRow > 0) {\n if (grid._activeEditRows === grid._focusRow) tryCommitEdit(grid);\n grid._focusRow -= 1;\n grid._focusCol = maxCol;\n }\n}\n\n/**\n * ArrowLeft/ArrowRight. `towardEnd` is the LOGICAL direction (ArrowRight); in\n * RTL the physical arrow maps to the opposite column index.\n */\nfunction navigateHorizontal(grid: GridHost, e: KeyboardEvent, maxCol: number, towardEnd: boolean): void {\n const forward = isRTL(grid) ? !towardEnd : towardEnd;\n grid._focusCol = forward ? Math.min(maxCol, grid._focusCol + 1) : Math.max(0, grid._focusCol - 1);\n e.preventDefault();\n}\n\n/** Home/End (plus Ctrl/Cmd variants which also jump to the first/last row). */\nfunction navigateRowEdge(grid: GridHost, e: KeyboardEvent, maxRow: number, maxCol: number, toEnd: boolean): void {\n if (e.ctrlKey || e.metaKey) {\n if (isRowEditing(grid)) tryCommitEdit(grid);\n grid._focusRow = toEnd ? maxRow : 0;\n }\n grid._focusCol = toEnd ? maxCol : 0;\n e.preventDefault();\n ensureCellVisible(grid, toEnd ? { forceScrollRight: true } : { forceScrollLeft: true });\n}\n\n/** Dispatch the unified `cell-activate` event. Returns true when cancelled. */\nfunction emitCellActivate(grid: GridHost, e: KeyboardEvent): boolean {\n const rowIndex = grid._focusRow;\n const colIndex = grid._focusCol;\n const column = grid._visibleColumns[colIndex];\n const row = grid._rows[rowIndex];\n const field = column?.field ?? '';\n const activateEvent = new CustomEvent('cell-activate', {\n cancelable: true,\n detail: {\n rowIndex,\n colIndex,\n column,\n field,\n value: field && row ? readCellField(row, field) : undefined,\n row,\n cellEl: grid.querySelector(`[data-row=\"${rowIndex}\"][data-col=\"${colIndex}\"]`) as HTMLElement | undefined,\n trigger: 'keyboard' as const,\n originalEvent: e,\n },\n });\n grid.dispatchEvent(activateEvent);\n return activateEvent.defaultPrevented;\n}\n\nexport function handleGridKeyDown(grid: GridHost, e: KeyboardEvent): void {\n // Dispatch to plugin system first - if any plugin handles it, stop here\n if (grid._dispatchKeyDown?.(e)) return;\n\n const path = e.composedPath?.() ?? [];\n const target = (path.length ? path[0] : e.target) as HTMLElement | null;\n if (shouldIgnoreKeyDown(grid, e, target)) return;\n\n const maxRow = grid._rows.length - 1;\n const maxCol = grid._visibleColumns.length - 1;\n\n switch (e.key) {\n case 'Tab':\n navigateTab(grid, e, maxRow, maxCol);\n break;\n case 'ArrowDown':\n if (isRowEditing(grid)) tryCommitEdit(grid);\n grid._focusRow = Math.min(maxRow, grid._focusRow + 1);\n e.preventDefault();\n break;\n case 'ArrowUp':\n if (isRowEditing(grid)) tryCommitEdit(grid);\n grid._focusRow = Math.max(0, grid._focusRow - 1);\n e.preventDefault();\n break;\n case 'ArrowRight':\n navigateHorizontal(grid, e, maxCol, true);\n break;\n case 'ArrowLeft':\n navigateHorizontal(grid, e, maxCol, false);\n break;\n case 'Home':\n navigateRowEdge(grid, e, maxRow, maxCol, false);\n return;\n case 'End':\n navigateRowEdge(grid, e, maxRow, maxCol, true);\n return;\n case 'PageDown':\n grid._focusRow = Math.min(maxRow, grid._focusRow + 20);\n e.preventDefault();\n break;\n case 'PageUp':\n grid._focusRow = Math.max(0, grid._focusRow - 20);\n e.preventDefault();\n break;\n // NOTE: Enter is normally handled by EditingPlugin. If no plugin handled\n // it, dispatch the unified cell-activate event for custom handling.\n case 'Enter':\n if (emitCellActivate(grid, e)) {\n e.preventDefault();\n return;\n }\n break;\n default:\n return;\n }\n ensureCellVisible(grid);\n}\n// #endregion\n\n// #region Cell Visibility\n/**\n * Options for ensureCellVisible to control scroll behavior.\n */\ninterface EnsureCellVisibleOptions {\n /** Force scroll to the leftmost position (for Home key) */\n forceScrollLeft?: boolean;\n /** Force scroll to the rightmost position (for End key) */\n forceScrollRight?: boolean;\n /** Force horizontal scroll even in edit mode (for Tab navigation) */\n forceHorizontalScroll?: boolean;\n}\n\n/**\n * Vertical: scroll the virtualized container so the focused row is in view.\n *\n * `y` is in raw row-content space (rowHeight × index). Above the browser height\n * cap (#326), `scrollEl.scrollTop` is in clamped spacer space — the two\n * coordinate systems are not interchangeable, so translate scrollTop into\n * virtual space for the comparison and back into native space when writing.\n * For sub-cap datasets the mapping is identity, so this is a no-op.\n *\n * Plugins that paint over the viewport (sticky rows) report the space they\n * obscure via `_getVerticalScrollOffsets`, so the row lands clear of the\n * overlay instead of underneath it — WCAG 2.2 SC 2.4.11 Focus Not Obscured.\n */\nfunction scrollFocusedRowIntoView(grid: GridHost): void {\n if (!grid._virtualization?.enabled) return;\n const { rowHeight, container, viewportEl, scrollMapping } = grid._virtualization;\n // container is the faux scrollbar element that handles actual scrolling;\n // viewportEl is the visible area element that has the correct height.\n const scrollEl = container as HTMLElement | undefined;\n const visibleHeight = viewportEl?.clientHeight ?? scrollEl?.clientHeight ?? 0;\n if (!scrollEl || visibleHeight <= 0) return;\n\n const offsets = grid._getVerticalScrollOffsets?.(grid._focusRow) ?? { top: 0, bottom: 0 };\n if (offsets.skipScroll) return;\n // A malformed or oversized report must never invert the visible band.\n const top = Math.max(0, offsets.top);\n const bottom = Math.max(0, offsets.bottom);\n const usableHeight = visibleHeight - top - bottom;\n if (usableHeight <= 0) return;\n\n const y = grid._focusRow * rowHeight;\n const virtualScrollTop = scrollMapping ? toVirtualScrollTop(scrollEl.scrollTop, scrollMapping) : scrollEl.scrollTop;\n if (y < virtualScrollTop + top) {\n const target = Math.max(0, y - top);\n scrollEl.scrollTop = scrollMapping ? fromVirtualScrollTop(target, scrollMapping) : target;\n } else if (y + rowHeight > virtualScrollTop + top + usableHeight) {\n const target = Math.max(0, y - usableHeight + rowHeight - top);\n scrollEl.scrollTop = scrollMapping ? fromVirtualScrollTop(target, scrollMapping) : target;\n }\n}\n\n/**\n * Resolve the rendered cell for the focused row/col, or `undefined` when the\n * focused row is outside the current virtual window.\n */\nfunction findFocusedCell(grid: GridHost): { rowEl: HTMLElement | null; cell: HTMLElement } | undefined {\n const rowIndex = grid._focusRow;\n const vStart = grid._virtualization.start ?? 0;\n const vEnd = grid._virtualization.end ?? grid._rows.length;\n if (rowIndex < vStart || rowIndex >= vEnd) return undefined;\n\n const rowEl = grid._bodyEl.querySelectorAll('.data-grid-row')[rowIndex - vStart] as HTMLElement | null;\n // Try exact column match first, then query by data-col, then fall back to the\n // first cell (full-width group rows).\n let cell = rowEl?.children[grid._focusCol] as HTMLElement | undefined;\n if (!cell || !cell.classList?.contains('cell')) {\n cell = (rowEl?.querySelector(`.cell[data-col=\"${grid._focusCol}\"]`) ?? rowEl?.querySelector('.cell[data-col]')) as\n HTMLElement | undefined;\n }\n return cell ? { rowEl: rowEl ?? null, cell } : undefined;\n}\n\n/** Horizontal: bring the focused cell into the `.tbw-scroll-area` viewport. */\nfunction scrollCellIntoViewHorizontally(\n grid: GridHost,\n rowEl: HTMLElement | null,\n cell: HTMLElement,\n options?: EnsureCellVisibleOptions,\n): void {\n const scrollArea = grid.querySelector('.tbw-scroll-area') as HTMLElement | null;\n if (!scrollArea) return;\n\n // Home/End always scroll to the edge.\n if (options?.forceScrollLeft) {\n scrollArea.scrollLeft = 0;\n return;\n }\n if (options?.forceScrollRight) {\n scrollArea.scrollLeft = scrollArea.scrollWidth - scrollArea.clientWidth;\n return;\n }\n\n // Plugins (e.g. pinned columns) report how much of the scroll area they\n // obscure, and whether the focused cell should skip scrolling entirely\n // (pinned cells are always visible).\n const offsets = grid._getHorizontalScrollOffsets?.(rowEl ?? undefined, cell) ?? { left: 0, right: 0 };\n if (offsets.skipScroll) return;\n\n const cellRect = cell.getBoundingClientRect();\n const scrollAreaRect = scrollArea.getBoundingClientRect();\n const cellLeft = cellRect.left - scrollAreaRect.left + scrollArea.scrollLeft;\n const cellRight = cellLeft + cellRect.width;\n const visibleLeft = scrollArea.scrollLeft + offsets.left;\n const visibleRight = scrollArea.scrollLeft + scrollArea.clientWidth - offsets.right;\n if (cellLeft < visibleLeft) {\n scrollArea.scrollLeft = cellLeft - offsets.left;\n } else if (cellRight > visibleRight) {\n scrollArea.scrollLeft = cellRight - scrollArea.clientWidth + offsets.right;\n }\n}\n\n/** Move real DOM focus to the editor, the cell, or the grid host. */\nfunction applyFocusTarget(grid: GridHost, cell: HTMLElement, isEditing: boolean): void {\n if (isEditing && cell.classList.contains(GridClasses.EDITING)) {\n // Editing cell: focus the editor input inside it\n const focusTarget = cell.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n if (focusTarget && document.activeElement !== focusTarget) {\n try {\n focusTarget.focus({ preventScroll: true });\n } catch {\n /* empty */\n }\n }\n return;\n }\n\n if (isEditing) {\n // Active edit row but this cell isn't the editing cell — focus it so Tab\n // navigation within the row can attach editors.\n if (cell.contains(document.activeElement)) return;\n if (!cell.hasAttribute('tabindex')) cell.setAttribute('tabindex', '-1');\n try {\n cell.focus({ preventScroll: true });\n } catch {\n /* empty */\n }\n return;\n }\n\n // NOT editing: keep focus on the grid element (tabindex=0) rather than\n // individual cells. In a virtualized grid, cells can be detached by\n // subsequent render cycles (e.g., SelectionPlugin's requestAfterRender\n // → RAF → row recycling). A detached focused cell causes activeElement\n // to revert to <body>, breaking keyboard navigation.\n // Visual focus is managed by the .cell-focus CSS class + data-has-focus.\n //\n // BUT: don't steal focus from a real focused descendant (toolpanel\n // input, shell-header button, registered overlay control). Cell focus\n // is virtual; if the user is actively typing in a non-cell input, we\n // must leave that input alone. We only reclaim focus when nothing\n // meaningful inside the grid currently holds it (active element is\n // outside grid, on the grid host itself, or on a bare cell).\n const active = document.activeElement;\n const meaningful =\n active instanceof HTMLElement &&\n active !== grid &&\n typeof grid.contains === 'function' &&\n grid.contains(active) &&\n !active.classList.contains('cell') &&\n !active.closest('.cell');\n if (!meaningful && active !== grid) {\n grid.focus({ preventScroll: true });\n }\n}\n\n/**\n * Scroll the viewport (virtualized or static) so the focused cell's row is visible\n * and apply visual focus styling / tabindex management.\n */\nexport function ensureCellVisible(grid: GridHost, options?: EnsureCellVisibleOptions): void {\n scrollFocusedRowIntoView(grid);\n\n const isEditing = isRowEditing(grid) || !!grid._isGridEditMode;\n // Skip refreshVirtualWindow when in edit mode to avoid wiping editors\n if (!isEditing) grid.refreshVirtualWindow(false);\n\n clearCellFocus(grid._bodyEl);\n // Clear previous aria-selected markers\n Array.from(grid._bodyEl.querySelectorAll('[aria-selected=\"true\"]')).forEach((el) => {\n el.setAttribute('aria-selected', 'false');\n });\n\n const focused = findFocusedCell(grid);\n if (!focused) return;\n const { rowEl, cell } = focused;\n\n cell.classList.add('cell-focus');\n cell.setAttribute('aria-selected', 'true');\n\n // Skip horizontal scrolling in edit mode to prevent scroll jumps when editors\n // are created — unless forceHorizontalScroll is set (Tab while editing).\n if (!isEditing || options?.forceHorizontalScroll) {\n scrollCellIntoViewHorizontally(grid, rowEl, cell, options);\n }\n\n applyFocusTarget(grid, cell, isEditing);\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, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\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 * 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","/**\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 * Editing Plugin Styles\n *\n * These styles are injected into the document when the EditingPlugin is loaded.\n * CSS custom properties use fallbacks to core grid variables for consistency.\n * Uses CSS nesting for scoping to tbw-grid elements.\n */\n\n@layer tbw-plugins {\n /* ============================================================================\n CSS Custom Properties for Editing\n ============================================================================\n These are defined here so they can be overridden by consumers.\n They reference core grid variables with sensible defaults.\n ============================================================================ */\n tbw-grid {\n /* Editing cell/row backgrounds */\n --tbw-editing-bg: var(--tbw-color-selection);\n --tbw-editing-row-bg: var(--tbw-editing-bg);\n\n /* Editing input styling */\n --tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));\n --tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);\n --tbw-font-size-editor: inherit;\n\n /* Row outline when editing */\n --tbw-editing-row-outline-color: var(--tbw-color-accent);\n --tbw-editing-row-outline-width: 1px;\n\n /* ============================================================================\n Row Editing State\n ============================================================================ */\n\n /* Highlight entire row when any cell is being edited (only in row mode, not grid mode) */\n &:not(.tbw-grid-mode) .data-grid-row:has(.editing) {\n background: var(--tbw-editing-row-bg);\n outline: var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);\n outline-offset: calc(-1 * var(--tbw-editing-row-outline-width));\n }\n\n /* ============================================================================\n Cell Editing State\n ============================================================================ */\n\n /* Cell in edit mode */\n .data-grid-row > .cell.editing {\n overflow: hidden;\n padding: 0;\n /* Override block to flex for editing inputs */\n display: flex;\n /* Match the non-editing cell height exactly. Non-editing height is:\n max(--tbw-row-height [border-box], line-height + padding + border [content-driven])\n Since editing cells have padding:0, min-height must compensate for both cases:\n - Content-driven: line-height (1lh) + original vertical padding + border\n - Min-height-driven: just var(--tbw-row-height) (border-box already includes padding+border) */\n min-height: max(\n var(--tbw-row-height),\n calc(1lh + 2 * var(--tbw-cell-padding-v, 0.25em) + var(--tbw-border-width, 1px))\n );\n align-items: center;\n justify-content: center;\n }\n\n /* Standard form inputs inside editing cells */\n .data-grid-row > .cell.editing input:not([type='checkbox']),\n .data-grid-row > .cell.editing select,\n .data-grid-row > .cell.editing textarea {\n width: 100%;\n height: 100%;\n flex: 1 1 auto;\n align-self: stretch;\n min-width: 0;\n border: var(--tbw-editing-border);\n padding: var(--tbw-padding-editing-input);\n font-size: var(--tbw-font-size-editor);\n }\n\n /* ============================================================================\n Editor Host\n ============================================================================ */\n\n /* Editor host wrapper uses display:contents to let editor fill cell */\n .tbw-editor-host {\n display: contents;\n }\n\n /* ============================================================================\n Changed Row Indicator\n ============================================================================ */\n\n /* Visual indicator for rows that have been modified */\n .data-grid-row.changed {\n /* Could add a left border or background tint here */\n }\n\n /* ============================================================================\n Invalid Cell Indicator\n ============================================================================ */\n\n /* Default invalid cell color - can be overridden by consumers */\n --tbw-invalid-bg: light-dark(#fef2f2, #450a0a);\n --tbw-invalid-border-color: light-dark(#ef4444, #f87171);\n\n /* Visual indicator for cells marked as invalid */\n .data-grid-row > .cell[data-invalid='true'] {\n background: var(--tbw-invalid-bg);\n outline: 1px solid var(--tbw-invalid-border-color);\n outline-offset: -1px;\n }\n }\n} /* End @layer tbw-plugins */\n","/**\n * Default Editors Module\n *\n * Provides built-in editor factories for different column types.\n * Each editor type has its own factory function for consistency and readability.\n *\n * IMPORTANT: Editor factories should NOT call focus() on elements - they are called\n * before the element is appended to the DOM. The calling code (beginBulkEdit,\n * inlineEnterEdit) is responsible for focusing the correct editor after insertion.\n */\n\nimport type { ColumnConfig, ColumnEditorContext } from '../../core/types';\nimport type { DateEditorParams, NumberEditorParams, SelectEditorParams, TextEditorParams } from './types';\n\n// ============================================================================\n// Type Aliases\n// ============================================================================\n\n/** Option shape used by select editor (matches column.options) */\ntype ColumnOption = { label: string; value: unknown };\n\n/** Column with any row type (used for editor factories) */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyColumn = ColumnConfig<any>;\n\n// ============================================================================\n// Utilities\n// ============================================================================\n\n/** Resolve column.options (handles both array and function forms) */\nfunction resolveOptions(column: AnyColumn): ColumnOption[] {\n const raw = column.options;\n if (!raw) return [];\n return typeof raw === 'function' ? raw() : raw;\n}\n\n/** Format a Date as YYYY-MM-DD string */\nfunction toISODate(date: Date): string {\n const y = date.getFullYear();\n const m = String(date.getMonth() + 1).padStart(2, '0');\n const d = String(date.getDate()).padStart(2, '0');\n return `${y}-${m}-${d}`;\n}\n\n// ============================================================================\n// Editor Factories\n// ============================================================================\n\n/** Creates a number input editor */\nfunction createNumberEditor(column: AnyColumn): (ctx: ColumnEditorContext) => HTMLElement {\n return (ctx) => {\n const params = column.editorParams as NumberEditorParams | undefined;\n const input = document.createElement('input');\n input.type = 'number';\n input.value = ctx.value != null ? String(ctx.value) : '';\n\n if (params?.min !== undefined) input.min = String(params.min);\n if (params?.max !== undefined) input.max = String(params.max);\n if (params?.step !== undefined) input.step = String(params.step);\n if (params?.placeholder) input.placeholder = params.placeholder;\n\n const commit = () => {\n if (input.value === '') {\n if (column.nullable) {\n ctx.commit(null);\n } else {\n // Non-nullable: fall back to min value or 0\n ctx.commit(params?.min ?? 0);\n }\n } else {\n ctx.commit(Number(input.value));\n }\n };\n input.addEventListener('blur', commit);\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Enter') commit();\n if (e.key === 'Escape') ctx.cancel();\n });\n\n return input;\n };\n}\n\n/** Creates a checkbox editor for boolean values */\nfunction createBooleanEditor(): (ctx: ColumnEditorContext) => HTMLElement {\n return (ctx) => {\n const input = document.createElement('input');\n input.type = 'checkbox';\n input.checked = !!ctx.value;\n input.addEventListener('change', () => ctx.commit(input.checked));\n return input;\n };\n}\n\n/** Creates a date input editor */\nfunction createDateEditor(column: AnyColumn): (ctx: ColumnEditorContext) => HTMLElement {\n return (ctx) => {\n const params = column.editorParams as DateEditorParams | undefined;\n const input = document.createElement('input');\n input.type = 'date';\n\n // Set initial value - handle both Date objects and string dates\n if (ctx.value instanceof Date) {\n input.valueAsDate = ctx.value;\n } else if (typeof ctx.value === 'string' && ctx.value) {\n // String date like \"2019-10-09\" - set directly as value\n input.value = ctx.value.split('T')[0]; // Handle ISO strings too\n }\n if (params?.min) input.min = params.min;\n if (params?.max) input.max = params.max;\n if (params?.placeholder) input.placeholder = params.placeholder;\n\n // Commit function preserves original type (string vs Date)\n const commit = () => {\n if (!input.value) {\n if (column.nullable) {\n ctx.commit(null);\n } else {\n // Non-nullable: use configured default or today\n const fallback = params?.default;\n if (typeof ctx.value === 'string' || typeof fallback === 'string') {\n // String mode: use default string or today as YYYY-MM-DD\n ctx.commit(typeof fallback === 'string' ? fallback : toISODate(fallback ?? new Date()));\n } else {\n // Date object mode\n ctx.commit(fallback instanceof Date ? fallback : new Date());\n }\n }\n return;\n }\n if (typeof ctx.value === 'string') {\n // Original was string, return string in YYYY-MM-DD format\n ctx.commit(input.value);\n } else {\n ctx.commit(input.valueAsDate);\n }\n };\n\n input.addEventListener('change', commit);\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') ctx.cancel();\n });\n\n return input;\n };\n}\n\n/** Sentinel value used internally to identify the nullable \"(Blank)\" option */\nconst NULLABLE_BLANK_VALUE = '__tbw_null__';\n\n/** Creates a select dropdown editor */\nfunction createSelectEditor(column: AnyColumn): (ctx: ColumnEditorContext) => HTMLElement {\n return (ctx) => {\n const params = column.editorParams as SelectEditorParams | undefined;\n const select = document.createElement('select');\n if (column.multi) select.multiple = true;\n\n // Add blank option: nullable columns always get one, otherwise respect includeEmpty\n const showBlank = column.nullable || params?.includeEmpty;\n if (showBlank) {\n const emptyOpt = document.createElement('option');\n emptyOpt.value = column.nullable ? NULLABLE_BLANK_VALUE : '';\n emptyOpt.textContent = column.nullable ? (params?.emptyLabel ?? '(Blank)') : (params?.emptyLabel ?? '');\n if (ctx.value == null) emptyOpt.selected = true;\n select.appendChild(emptyOpt);\n }\n\n // Populate options from column.options\n const options = resolveOptions(column);\n options.forEach((opt) => {\n const o = document.createElement('option');\n o.value = String(opt.value);\n o.textContent = opt.label;\n if (column.multi && Array.isArray(ctx.value) && ctx.value.includes(opt.value)) {\n o.selected = true;\n } else if (!column.multi && ctx.value === opt.value) {\n o.selected = true;\n }\n select.appendChild(o);\n });\n\n const commit = () => {\n if (column.multi) {\n const values = Array.from(select.selectedOptions).map((o) => o.value);\n ctx.commit(values);\n } else if (column.nullable && select.value === NULLABLE_BLANK_VALUE) {\n ctx.commit(null);\n } else {\n ctx.commit(select.value);\n }\n };\n\n select.addEventListener('change', commit);\n select.addEventListener('blur', commit);\n select.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') ctx.cancel();\n });\n\n return select;\n };\n}\n\n/** Creates a text input editor (default) */\nfunction createTextEditor(column: AnyColumn): (ctx: ColumnEditorContext) => HTMLElement {\n return (ctx) => {\n const params = column.editorParams as TextEditorParams | undefined;\n const input = document.createElement('input');\n input.type = 'text';\n input.value = ctx.value != null ? String(ctx.value) : '';\n\n if (params?.maxLength !== undefined) input.maxLength = params.maxLength;\n if (params?.pattern) input.pattern = params.pattern;\n if (params?.placeholder) input.placeholder = params.placeholder;\n\n // Commit function preserves original type when possible\n const commit = () => {\n const inputVal = input.value;\n\n // Empty input handling\n if (inputVal === '') {\n if (column.nullable) {\n ctx.commit(null);\n } else {\n // Non-nullable: commit empty string so the field is never null\n ctx.commit('');\n }\n return;\n }\n\n // Preserve values with characters that <input> can't represent (newlines, etc.).\n // If stripping those characters produces the same string, the user didn't change anything.\n if (typeof ctx.value === 'string' && inputVal === ctx.value.replace(/[\\n\\r]/g, '')) {\n return;\n }\n // Preserve numeric type for custom column types (e.g., currency)\n if (typeof ctx.value === 'number') {\n ctx.commit(Number(inputVal));\n } else {\n ctx.commit(inputVal);\n }\n };\n\n input.addEventListener('blur', commit);\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Enter') commit();\n if (e.key === 'Escape') ctx.cancel();\n });\n\n return input;\n };\n}\n\n// ============================================================================\n// Main Entry Point\n// ============================================================================\n\n/**\n * Returns a default editor factory function for the given column type.\n * Each editor handles commit on blur/Enter, and cancel on Escape.\n *\n * Note: Focus is NOT called here - the calling code handles focusing after DOM insertion.\n * @since 0.4.0\n */\nexport function defaultEditorFor(column: AnyColumn): (ctx: ColumnEditorContext) => HTMLElement | string {\n switch (column.type) {\n case 'number':\n return createNumberEditor(column);\n case 'boolean':\n return createBooleanEditor();\n case 'date':\n return createDateEditor(column);\n case 'select':\n return createSelectEditor(column);\n default:\n return createTextEditor(column);\n }\n}\n\n// ============================================================================\n// Utility Export (used by EditingPlugin)\n// ============================================================================\n\n/**\n * Resolve a numeric editor value. Empty input falls back to `null` for nullable\n * columns, otherwise to the configured `min` (or `0`).\n */\nfunction readNumericValue(raw: string, column?: AnyColumn): unknown {\n if (raw === '') {\n if (column?.nullable) return null;\n const params = column?.editorParams as NumberEditorParams | undefined;\n return params?.min ?? 0;\n }\n return Number(raw);\n}\n\n/**\n * Resolve a `<input type=\"date\">` value, preserving the original value's type\n * (string dates stay `YYYY-MM-DD` strings, Date objects stay `Date`).\n */\nfunction readDateValue(input: HTMLInputElement, column?: AnyColumn, originalValue?: unknown): unknown {\n if (!input.value) {\n if (column?.nullable) return null;\n // Non-nullable: preserve original or fall back to today\n if (typeof originalValue === 'string') return originalValue || new Date().toISOString().slice(0, 10);\n return (originalValue as Date) ?? new Date();\n }\n // Preserve original type: if original was a string, return string (YYYY-MM-DD format)\n if (typeof originalValue === 'string') {\n return input.value; // input.value is already in YYYY-MM-DD format\n }\n return input.valueAsDate;\n}\n\n/**\n * Resolve a plain text `<input>` value, preserving numeric originals and values\n * containing characters `<input>` cannot represent.\n */\nfunction readTextInputValue(input: HTMLInputElement, column?: AnyColumn, originalValue?: unknown): unknown {\n // For text inputs, check if original value was a number to preserve type\n if (typeof originalValue === 'number') return readNumericValue(input.value, column);\n // Nullable text: empty → null; non-nullable: empty → ''\n if (input.value === '' && (originalValue === null || originalValue === undefined)) {\n return column?.nullable ? null : '';\n }\n // Preserve values with characters <input> can't represent (newlines, etc.)\n if (typeof originalValue === 'string' && input.value === originalValue.replace(/[\\n\\r]/g, '')) {\n return originalValue;\n }\n return input.value;\n}\n\n/**\n * Resolve a `<textarea>` / `<select>` value using the column type or the\n * original value's type.\n */\nfunction readTextControlValue(\n input: HTMLTextAreaElement | HTMLSelectElement,\n column?: AnyColumn,\n originalValue?: unknown,\n): unknown {\n // Check column type OR original value type — preserves numeric type for\n // custom column types (e.g., currency).\n if (input.value !== '' && (column?.type === 'number' || typeof originalValue === 'number')) {\n return Number(input.value);\n }\n // Nullable: empty → null; non-nullable: empty → ''\n if ((originalValue === null || originalValue === undefined) && input.value === '') {\n return column?.nullable ? null : '';\n }\n return input.value;\n}\n\n/**\n * Get the typed value from an input element based on its type, column config, and original value.\n * Preserves the type of the original value (e.g., numeric currency values stay as numbers,\n * string dates stay as strings, null/undefined for empty fields).\n */\nexport function getInputValue(\n input: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n column?: AnyColumn,\n originalValue?: unknown,\n): unknown {\n if (!(input instanceof HTMLInputElement)) return readTextControlValue(input, column, originalValue);\n switch (input.type) {\n case 'checkbox':\n return input.checked;\n case 'number':\n return readNumericValue(input.value, column);\n case 'date':\n return readDateValue(input, column, originalValue);\n default:\n return readTextInputValue(input, column, originalValue);\n }\n}\n","/**\n * Cell Validation Manager\n *\n * Manages invalid-cell state for the Editing Plugin.\n * Extracted from EditingPlugin to reduce the main plugin file size.\n *\n * The manager owns the `Map<rowId, Map<field, message>>` state and exposes\n * read/write methods. DOM synchronization is handled via an injected callback.\n *\n * @internal\n */\n\n/** Callback to sync the data-invalid attribute on a cell element in the DOM. */\nexport type SyncInvalidAttributeFn = (rowId: string, field: string, invalid: boolean) => void;\n\n/**\n * Manages validation state for grid cells.\n *\n * Tracks which cells are marked invalid and their validation messages.\n * The DOM side-effect (adding/removing `data-invalid` attribute) is delegated\n * to the `syncAttribute` callback provided at construction time.\n */\nexport class CellValidationManager {\n /** Invalid cell tracking: Map<rowId, Map<field, message>> */\n readonly #cells = new Map<string, Map<string, string>>();\n\n /** Callback to sync DOM attributes when validation state changes */\n readonly #syncAttribute: SyncInvalidAttributeFn;\n\n constructor(syncAttribute: SyncInvalidAttributeFn) {\n this.#syncAttribute = syncAttribute;\n }\n\n // #region Write Operations\n\n /**\n * Mark a cell as invalid with an optional validation message.\n *\n * @param rowId - The row ID (from getRowId)\n * @param field - The field name\n * @param message - Optional validation message (for tooltips or display)\n */\n setInvalid(rowId: string, field: string, message = ''): void {\n let rowInvalids = this.#cells.get(rowId);\n if (!rowInvalids) {\n rowInvalids = new Map();\n this.#cells.set(rowId, rowInvalids);\n }\n rowInvalids.set(field, message);\n this.#syncAttribute(rowId, field, true);\n }\n\n /**\n * Clear the invalid state for a specific cell.\n *\n * @param rowId - The row ID (from getRowId)\n * @param field - The field name\n */\n clearInvalid(rowId: string, field: string): void {\n const rowInvalids = this.#cells.get(rowId);\n if (rowInvalids) {\n rowInvalids.delete(field);\n if (rowInvalids.size === 0) {\n this.#cells.delete(rowId);\n }\n }\n this.#syncAttribute(rowId, field, false);\n }\n\n /**\n * Clear all invalid cells for a specific row.\n *\n * @param rowId - The row ID (from getRowId)\n */\n clearRowInvalid(rowId: string): void {\n const rowInvalids = this.#cells.get(rowId);\n if (rowInvalids) {\n const fields = Array.from(rowInvalids.keys());\n this.#cells.delete(rowId);\n fields.forEach((field) => this.#syncAttribute(rowId, field, false));\n }\n }\n\n /**\n * Clear all invalid cell states across all rows.\n */\n clearAllInvalid(): void {\n const entries = Array.from(this.#cells.entries());\n this.#cells.clear();\n entries.forEach(([rowId, fields]) => {\n fields.forEach((_, field) => this.#syncAttribute(rowId, field, false));\n });\n }\n\n // #endregion\n\n // #region Read Operations\n\n /**\n * Check if a specific cell is marked as invalid.\n *\n * @param rowId - The row ID (from getRowId)\n * @param field - The field name\n * @returns True if the cell is marked as invalid\n */\n isCellInvalid(rowId: string, field: string): boolean {\n return this.#cells.get(rowId)?.has(field) ?? false;\n }\n\n /**\n * Get the validation message for an invalid cell.\n *\n * @param rowId - The row ID (from getRowId)\n * @param field - The field name\n * @returns The validation message, or undefined if cell is valid\n */\n getInvalidMessage(rowId: string, field: string): string | undefined {\n return this.#cells.get(rowId)?.get(field);\n }\n\n /**\n * Check if a row has any invalid cells.\n *\n * @param rowId - The row ID (from getRowId)\n * @returns True if the row has at least one invalid cell\n */\n hasInvalidCells(rowId: string): boolean {\n const rowInvalids = this.#cells.get(rowId);\n return rowInvalids ? rowInvalids.size > 0 : false;\n }\n\n /**\n * Get all invalid fields for a row.\n *\n * @param rowId - The row ID (from getRowId)\n * @returns Map of field names to validation messages\n */\n getInvalidFields(rowId: string): Map<string, string> {\n return new Map(this.#cells.get(rowId) ?? []);\n }\n\n // #endregion\n}\n","/**\n * Pure functions for dirty tracking baseline management.\n *\n * Extracted from EditingPlugin to keep the plugin under the 2,000 line target.\n * All functions are stateless — the caller owns the baseline `Map`.\n *\n * @internal\n */\n\nimport { readCellField } from '../../../core/internal/value-accessor';\n\n// #region Types\n\n/**\n * Detail for `dirty-change` custom events.\n * @since 1.23.0\n */\nexport interface DirtyChangeDetail<T = unknown> {\n /** Row ID (from getRowId) */\n rowId: string;\n /** Current row data */\n row: T;\n /** Baseline (original) row data, or undefined for newly inserted rows */\n original: T | undefined;\n /**\n * Transition type:\n * - `'modified'` — row differs from baseline\n * - `'new'` — row was inserted via `insertRow()` and has no baseline\n * - `'reverted'` — row was reverted to baseline via `revertRow()`\n * - `'pristine'` — row was explicitly marked pristine via `markAsPristine()`\n */\n type: 'modified' | 'new' | 'reverted' | 'pristine';\n}\n\n/**\n * Result of getDirtyRows(): each entry has the row ID, original (baseline),\n * and current data.\n * @since 1.23.0\n */\nexport interface DirtyRowEntry<T = unknown> {\n id: string;\n /** The original (baseline) row data, or `undefined` for newly inserted rows. */\n original: T | undefined;\n current: T;\n}\n\n/**\n * Detail for `baselines-captured` custom events.\n *\n * Emitted after the render pipeline completes when new baseline snapshots\n * were captured during `processRows`.\n * @since 1.23.0\n */\nexport interface BaselinesCapturedDetail {\n /** Total number of tracked baselines (not just newly captured). */\n count: number;\n}\n\n// #endregion\n\n// #region Baseline Capture\n\n/**\n * Capture baselines for rows not already tracked (first-write-wins).\n *\n * Uses `structuredClone` for deep copy so nested objects cannot be mutated\n * through shared references.\n *\n * @param baselines - Map of rowId → deep-cloned baseline row data\n * @param rows - Rows to snapshot\n * @param getRowId - Function to resolve row ID (may throw; exceptions are swallowed)\n */\nexport function captureBaselines<T>(\n baselines: Map<string, T>,\n rows: readonly T[],\n getRowId: (row: T) => string | undefined,\n): void {\n for (const row of rows) {\n try {\n const id = getRowId(row);\n if (id != null && !baselines.has(id)) {\n baselines.set(id, structuredClone(row));\n }\n } catch {\n // Row has no resolvable ID — skip\n }\n }\n}\n\n// #endregion\n\n// #region Dirty Detection\n\n/**\n * Check whether a row's current data differs from its baseline.\n *\n * Uses deep property comparison so that `structuredClone`'d baselines\n * with nested objects/arrays/Dates compare correctly.\n */\nexport function isRowDirty<T>(baselines: Map<string, T>, rowId: string, currentRow: T): boolean {\n const baseline = baselines.get(rowId);\n if (!baseline) return false; // No baseline → row is \"new\" or untracked\n return !deepEqual(baseline, currentRow);\n}\n\n/**\n * Check whether a single cell (field) differs from its baseline value.\n *\n * Returns `false` when no baseline exists for the row.\n */\nexport function isCellDirty<T>(baselines: Map<string, T>, rowId: string, currentRow: T, field: string): boolean {\n const baseline = baselines.get(rowId);\n if (!baseline) return false;\n const baselineValue = readCellField(baseline, field);\n const currentValue = readCellField(currentRow, field);\n return !deepEqual(baselineValue, currentValue);\n}\n\n/**\n * Deep comparison of two values. Handles primitives, plain objects, arrays,\n * and Dates — the value types produced by `structuredClone` on row data.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a == null || b == null) return false;\n if (typeof a !== typeof b) return false;\n\n // Date comparison\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n\n // Array comparison\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n\n // Object comparison\n if (typeof a === 'object') {\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const keysA = Object.keys(aObj);\n const keysB = Object.keys(bObj);\n if (keysA.length !== keysB.length) return false;\n for (const key of keysA) {\n if (!deepEqual(aObj[key], bObj[key])) return false;\n }\n return true;\n }\n\n return false;\n}\n\n// #endregion\n\n// #region State Transitions\n\n/**\n * Mark a row as pristine: re-snapshot baseline from current data.\n *\n * After calling this, `isRowDirty` returns `false` for the row (until it\n * is edited again).\n */\nexport function markPristine<T>(baselines: Map<string, T>, rowId: string, currentRow: T): void {\n baselines.set(rowId, structuredClone(currentRow));\n}\n\n/**\n * Get the original (baseline) row data as a deep clone.\n *\n * Returns `undefined` if no baseline exists (e.g. newly inserted row).\n */\nexport function getOriginalRow<T>(baselines: Map<string, T>, rowId: string): T | undefined {\n const baseline = baselines.get(rowId);\n return baseline ? structuredClone(baseline) : undefined;\n}\n\n/**\n * Revert a row to its baseline values by mutating the current row in-place.\n *\n * Returns `true` if a baseline existed and the row was reverted, `false` otherwise.\n */\nexport function revertToBaseline<T>(baselines: Map<string, T>, rowId: string, currentRow: T): boolean {\n const baseline = baselines.get(rowId);\n if (!baseline) return false;\n const baselineObj = baseline as Record<string, unknown>;\n const currentObj = currentRow as Record<string, unknown>;\n for (const key of Object.keys(baselineObj)) {\n currentObj[key] = baselineObj[key];\n }\n return true;\n}\n\n// #endregion\n","/**\n * Stateful manager for dirty tracking in the EditingPlugin.\n *\n * Owns all dirty-tracking-related state (baselines, changed/new/committed sets)\n * and exposes high-level methods that coordinate pure functions from\n * `dirty-tracking.ts`.\n *\n * The EditingPlugin delegates all dirty tracking operations to this manager,\n * keeping the plugin class focused on orchestration (row resolution, event\n * emission, render scheduling).\n *\n * @internal\n */\n\nimport { writeCellField } from '../../../core/internal/value-accessor';\nimport {\n captureBaselines,\n getOriginalRow,\n isCellDirty,\n isRowDirty,\n markPristine,\n revertToBaseline,\n type DirtyRowEntry,\n} from './dirty-tracking';\n\n// #region Types\n\n/**\n * Callback that resolves a row object by its ID.\n * Returns `undefined` when the row is not found.\n */\nexport type RowResolver<T> = (rowId: string) => T | undefined;\n\n// #endregion\n\n// #region DirtyTrackingManager\n\nexport class DirtyTrackingManager<T> {\n // --- Owned state ---\n\n /** Baseline snapshots: rowId → deep-cloned original row data (first-write-wins) */\n readonly baselines = new Map<string, T>();\n\n /** Whether new baselines were captured during the current processRows cycle */\n private baselinesWereCaptured = false;\n\n /** Row IDs inserted via `insertRow()` (no baseline available) */\n readonly newRowIds = new Set<string>();\n\n /** Row IDs that have been modified (edit committed) */\n readonly changedRowIds = new Set<string>();\n\n /** Row IDs whose edit session was committed (gates `tbw-row-dirty` CSS class) */\n readonly committedDirtyRowIds = new Set<string>();\n\n // --- Lifecycle ---\n\n /** Reset all dirty tracking state (called from detach / resetChangedRows). */\n clear(): void {\n this.changedRowIds.clear();\n this.committedDirtyRowIds.clear();\n this.baselines.clear();\n this.newRowIds.clear();\n this.baselinesWereCaptured = false;\n }\n\n // --- Baseline capture (called from processRows) ---\n\n /**\n * Capture baselines for rows not already tracked (first-write-wins).\n * Sets the `baselinesWereCaptured` flag when new rows are snapshotted.\n */\n capture(rows: readonly T[], getRowId: (r: T) => string | undefined): void {\n const sizeBefore = this.baselines.size;\n captureBaselines(this.baselines, rows, getRowId);\n if (this.baselines.size > sizeBefore) {\n this.baselinesWereCaptured = true;\n }\n }\n\n /**\n * Drain the baselines-captured flag (called from afterRender).\n * Returns `null` when no new captures occurred, or the baseline count.\n */\n drainCapturedFlag(): number | null {\n if (!this.baselinesWereCaptured) return null;\n this.baselinesWereCaptured = false;\n return this.baselines.size;\n }\n\n // --- Row dirty queries ---\n\n /** Check if a specific row differs from its baseline. */\n isRowDirty(rowId: string, row: T): boolean {\n return isRowDirty(this.baselines, rowId, row);\n }\n\n /** Check if ANY row is dirty (requires row resolver for baseline iteration). */\n hasAnyDirty(resolveRow: RowResolver<T>): boolean {\n if (this.newRowIds.size > 0) return true;\n for (const [rowId] of this.baselines) {\n const row = resolveRow(rowId);\n if (row && isRowDirty(this.baselines, rowId, row)) return true;\n }\n return false;\n }\n\n // --- Cell dirty queries ---\n\n /** Check if a single cell differs from its baseline value. */\n isCellDirty(rowId: string, row: T, field: string): boolean {\n return isCellDirty(this.baselines, rowId, row, field);\n }\n\n // --- Render-time helpers ---\n\n /**\n * Get the dirty-state tuple needed by afterRowRender to toggle CSS classes.\n *\n * `isCommittedDirty` requires BOTH committed status AND actual data divergence\n * from baseline (handles undo: after CTRL+Z, row is no longer visually dirty).\n */\n getRowDirtyState(rowId: string, row: T): { isNew: boolean; isCommittedDirty: boolean; hasBaseline: boolean } {\n const isNew = this.newRowIds.has(rowId);\n const isCommittedDirty = !isNew && this.committedDirtyRowIds.has(rowId) && isRowDirty(this.baselines, rowId, row);\n return { isNew, isCommittedDirty, hasBaseline: this.baselines.has(rowId) };\n }\n\n // --- Mark operations ---\n\n /** Re-snapshot baseline from current data and remove from all sets. */\n markPristine(rowId: string, row: T): void {\n markPristine(this.baselines, rowId, row);\n this.newRowIds.delete(rowId);\n this.changedRowIds.delete(rowId);\n this.committedDirtyRowIds.delete(rowId);\n }\n\n /**\n * Update a single field's baseline to an externally-synced value.\n *\n * Used for `source: 'sync'` (declarative host data replacement): the incoming\n * value becomes the new pristine truth for that cell without touching other\n * fields' baselines or the row's dirty membership sets. No-op when the row has\n * no captured baseline (an untracked row is not dirty anyway).\n */\n rebaselineCell(rowId: string, field: string, value: unknown): void {\n const baseline = this.baselines.get(rowId);\n if (baseline) writeCellField(baseline, field, value);\n }\n\n /** Mark a row as newly inserted (no baseline). */\n markNew(rowId: string): void {\n this.newRowIds.add(rowId);\n this.committedDirtyRowIds.add(rowId);\n }\n\n /** Mark a row as dirty (external mutation). */\n markDirty(rowId: string): void {\n this.changedRowIds.add(rowId);\n this.committedDirtyRowIds.add(rowId);\n }\n\n /** Re-snapshot all baselines and clear all tracking sets. */\n markAllPristine(resolveRow: RowResolver<T>): void {\n for (const [rowId] of this.baselines) {\n const row = resolveRow(rowId);\n if (row) markPristine(this.baselines, rowId, row);\n }\n this.newRowIds.clear();\n this.changedRowIds.clear();\n this.committedDirtyRowIds.clear();\n }\n\n // --- Original row access ---\n\n /** Get deep-cloned baseline (undefined for new/untracked rows). */\n getOriginalRow(rowId: string): T | undefined {\n return getOriginalRow<T>(this.baselines, rowId);\n }\n\n /** Lightweight check whether a baseline exists (no cloning). */\n hasBaseline(rowId: string): boolean {\n return this.baselines.has(rowId);\n }\n\n // --- Aggregate queries ---\n\n /** Get all dirty rows with original + current data. Requires a row resolver. */\n getDirtyRows(resolveRow: RowResolver<T>): DirtyRowEntry<T>[] {\n const result: DirtyRowEntry<T>[] = [];\n for (const [rowId, baseline] of this.baselines) {\n const row = resolveRow(rowId);\n if (row && isRowDirty(this.baselines, rowId, row)) {\n result.push({ id: rowId, original: structuredClone(baseline), current: row });\n }\n }\n for (const newId of this.newRowIds) {\n const row = resolveRow(newId);\n if (row) {\n result.push({ id: newId, original: undefined, current: row });\n }\n }\n return result;\n }\n\n /** Get IDs of all dirty rows. Requires a row resolver. */\n getDirtyRowIds(resolveRow: RowResolver<T>): string[] {\n const ids: string[] = [];\n for (const [rowId] of this.baselines) {\n const row = resolveRow(rowId);\n if (row && isRowDirty(this.baselines, rowId, row)) ids.push(rowId);\n }\n for (const newId of this.newRowIds) ids.push(newId);\n return ids;\n }\n\n // --- Revert operations ---\n\n /**\n * Revert a row to its baseline values (mutates row in-place).\n * Returns `true` when baseline existed and row was reverted.\n */\n revertRow(rowId: string, row: T): boolean {\n const reverted = revertToBaseline(this.baselines, rowId, row);\n if (reverted) {\n this.changedRowIds.delete(rowId);\n this.committedDirtyRowIds.delete(rowId);\n }\n return reverted;\n }\n\n /** Revert all rows to baseline values. Requires a row resolver. */\n revertAll(resolveRow: RowResolver<T>): void {\n for (const [rowId] of this.baselines) {\n const row = resolveRow(rowId);\n if (row) revertToBaseline(this.baselines, rowId, row);\n }\n this.changedRowIds.clear();\n this.committedDirtyRowIds.clear();\n }\n\n // --- Changed row queries ---\n\n /** Resolve changed row IDs to row objects. */\n getChangedRows(resolveRow: RowResolver<T>): T[] {\n const rows: T[] = [];\n for (const id of this.changedRowIds) {\n const row = resolveRow(id);\n if (row) rows.push(row);\n }\n return rows;\n }\n\n /** Get a copy of changed row IDs. */\n getChangedRowIds(): string[] {\n return Array.from(this.changedRowIds);\n }\n\n /** Check if a row has been marked as changed. */\n isRowChanged(rowId: string): boolean {\n return this.changedRowIds.has(rowId);\n }\n}\n\n// #endregion\n","/**\n * Pure helper functions for the Editing Plugin.\n *\n * Extracted from EditingPlugin to reduce the main plugin file size.\n * All functions are stateless — they have no `this` access.\n *\n * @internal\n */\n\nimport type {\n ColumnConfig,\n ColumnEditorSpec,\n ColumnInternal,\n InternalGrid,\n RowElementInternal,\n} from '../../../core/types';\nimport { getInputValue } from '../editors';\nimport type { EditingConfig } from '../types';\n\n// #region Constants\n\n/**\n * CSS selector for focusable editor elements inside a cell.\n * Duplicated from core/internal/rows to avoid cross-boundary imports\n * that Vite externalises to `@toolbox-web/grid` during plugin bundling.\n *\n * @internal\n */\nexport const FOCUSABLE_EDITOR_SELECTOR =\n 'input,select,textarea,[contenteditable=\"true\"],[contenteditable=\"\"],[tabindex]:not([tabindex=\"-1\"])';\n\n/**\n * Returns the closest ancestor (or `target` itself) that matches\n * {@link FOCUSABLE_EDITOR_SELECTOR}, or `null` if none exists.\n *\n * Always prefer this over `target.matches(FOCUSABLE_EDITOR_SELECTOR)` —\n * non-focusable editor descendants (e.g. `<option>` inside an open\n * native `<select>` popup; spans inside `contenteditable`) need to be\n * recognised as \"inside the editor\" but do not themselves match the\n * selector.\n *\n * @internal\n */\nexport function getEditorAncestor(target: EventTarget | null | undefined): Element | null {\n const el = target as Element | null | undefined;\n return el?.closest?.(FOCUSABLE_EDITOR_SELECTOR) ?? null;\n}\n\n// #endregion\n\n// #region Editor Resolution\n\n/**\n * Resolves the editor for a column using the priority chain:\n * 1. Column-level (`column.editor`)\n * 2. Light DOM template (`__editorTemplate` → returns 'template')\n * 3. Grid-level (`gridConfig.typeDefaults[column.type]`)\n * 4. App-level (framework adapter's `getTypeDefault`)\n * 5. Returns undefined (caller uses built-in defaultEditorFor)\n */\nexport function resolveEditor<TRow>(\n grid: InternalGrid<TRow>,\n col: ColumnInternal<TRow>,\n): ColumnEditorSpec<TRow, unknown> | 'template' | undefined {\n // 1. Column-level editor (highest priority)\n if (col.editor) return col.editor;\n\n // 2. Light DOM template\n const tplHolder = col.__editorTemplate;\n if (tplHolder) return 'template';\n\n // No type specified - no type defaults to check\n if (!col.type) return undefined;\n\n // 3. Grid-level typeDefaults (access via effectiveConfig)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const gridTypeDefaults = (grid as any).effectiveConfig?.typeDefaults;\n if (gridTypeDefaults?.[col.type]?.editor) {\n return gridTypeDefaults[col.type].editor as ColumnEditorSpec<TRow, unknown>;\n }\n\n // 4. App-level registry (via framework adapter)\n const adapter = grid.__frameworkAdapter;\n if (adapter?.getTypeDefault) {\n const appDefault = adapter.getTypeDefault<TRow>(col.type, grid._hostElement);\n if (appDefault?.editor) {\n return appDefault.editor as ColumnEditorSpec<TRow, unknown>;\n }\n }\n\n // 5. No custom editor - caller uses built-in defaultEditorFor\n return undefined;\n}\n\n// #endregion\n\n// #region Property Key Safety\n\n/**\n * Returns true if the given property key is safe to use on a plain object.\n */\nexport function isSafePropertyKey(key: unknown): key is string {\n if (typeof key !== 'string') return false;\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') return false;\n return true;\n}\n\n// #endregion\n\n// #region Row Element State\n\n/**\n * Increment the editing cell count on a row element.\n */\nexport function incrementEditingCount(rowEl: RowElementInternal): void {\n const count = (rowEl.__editingCellCount ?? 0) + 1;\n rowEl.__editingCellCount = count;\n rowEl.setAttribute('data-has-editing', '');\n}\n\n/**\n * Clear all editing state from a row element.\n */\nexport function clearEditingState(rowEl: RowElementInternal): void {\n rowEl.__editingCellCount = 0;\n rowEl.removeAttribute('data-has-editing');\n}\n\n// #endregion\n\n// #region No-op Helpers\n\n/**\n * No-op updateRow function for rows without IDs.\n * Extracted to a named function to satisfy eslint no-empty-function.\n */\nexport function noopUpdateRow(_changes: unknown): void {\n // Row has no ID - cannot update\n}\n\n// #endregion\n\n// #region Editor Input Wiring\n\n/**\n * Auto-wire commit/cancel lifecycle for input elements in string-returned editors.\n */\nexport function wireEditorInputs(\n editorHost: HTMLElement,\n column: ColumnConfig<unknown>,\n commit: (value: unknown) => void,\n originalValue?: unknown,\n): void {\n const input = editorHost.querySelector('input,textarea,select') as\n | HTMLInputElement\n | HTMLTextAreaElement\n | HTMLSelectElement\n | null;\n if (!input) return;\n\n input.addEventListener('blur', () => {\n commit(getInputValue(input, column, originalValue));\n });\n\n if (input instanceof HTMLInputElement && input.type === 'checkbox') {\n input.addEventListener('change', () => commit(input.checked));\n } else if (input instanceof HTMLSelectElement) {\n input.addEventListener('change', () => commit(getInputValue(input, column, originalValue)));\n }\n}\n\n// #endregion\n\n// #region Edit Guard\n\n/**\n * Returns `true` when the configured `onBeforeEditClose` callback vetoes\n * the close (i.e. returns `false`). Use as a one-liner guard:\n *\n * ```ts\n * if (shouldPreventEditClose(config, e)) return;\n * ```\n */\nexport function shouldPreventEditClose(config: EditingConfig, event: MouseEvent | KeyboardEvent): boolean {\n return config.onBeforeEditClose?.(event) === false;\n}\n\n// #endregion\n\n// #region ARIA Overlay Detection\n\n/**\n * Returns `true` when `target` is inside an overlay panel that is currently\n * \"owned\" by an open combobox/listbox/menu inside `scopeEl`.\n *\n * Detection uses the WAI-ARIA pattern: a control with\n * `aria-expanded=\"true\"` and `aria-controls=\"<id>\"` declares ownership of\n * the panel with that id. Used by the editing plugin as a generic fallback\n * so portal-rendered overlays from libraries like Downshift, Material UI,\n * or Headless UI are recognised as part of the active editor without the\n * consumer having to call `registerExternalFocusContainer` (#251).\n *\n * Cheap: only walks elements with `aria-expanded=\"true\"` inside the\n * editor scope (typically zero or one).\n *\n * @internal\n */\nexport function isInsideOpenAriaOverlay(target: Node | null | undefined, scopeEl: HTMLElement): boolean {\n if (!target) return false;\n const triggers = scopeEl.querySelectorAll<HTMLElement>('[aria-expanded=\"true\"][aria-controls]');\n for (let i = 0; i < triggers.length; i++) {\n const id = triggers[i].getAttribute('aria-controls');\n if (!id) continue;\n const panel = scopeEl.ownerDocument?.getElementById(id);\n if (panel && panel.contains(target as Node)) return true;\n }\n return false;\n}\n\n// #endregion\n\n// #region Row Comparison\n\n/**\n * Shallow-compare a snapshot against the current row to detect changes.\n * Returns `true` if any own-property value differs between the two objects.\n */\nexport function hasRowChanged<T>(snapshot: T | undefined, current: T): boolean {\n if (!snapshot) return false;\n const snapshotObj = snapshot as Record<string, unknown>;\n const currentObj = current as Record<string, unknown>;\n const allKeys = new Set([...Object.keys(snapshotObj), ...Object.keys(currentObj)]);\n for (const key of allKeys) {\n if (snapshotObj[key] !== currentObj[key]) return true;\n }\n return false;\n}\n\n// #endregion\n","/**\n * Editor injection logic for the Editing Plugin.\n *\n * Extracted from EditingPlugin to reduce the main file size.\n * Contains the DOM-heavy editor creation and template rendering,\n * while the plugin retains state management and event emission.\n *\n * @internal\n */\n\nimport { EDITOR_MOUNT_ERROR, warnDiagnostic } from '../../../core/internal/diagnostics';\nimport { readCellField, writeCellField } from '../../../core/internal/value-accessor';\nimport type {\n ColumnConfig,\n ColumnEditorContext,\n ColumnInternal,\n GridHost,\n RowElementInternal,\n} from '../../../core/types';\nimport { defaultEditorFor, getInputValue } from '../editors';\nimport type { EditingConfig } from '../types';\nimport {\n FOCUSABLE_EDITOR_SELECTOR,\n getEditorAncestor,\n incrementEditingCount,\n isSafePropertyKey,\n noopUpdateRow,\n resolveEditor,\n shouldPreventEditClose,\n wireEditorInputs,\n} from './helpers';\n\n// #region Types\n\n/**\n * Dependencies injected by the EditingPlugin so the extraction\n * can call back into plugin-owned state and methods.\n */\nexport interface EditorInjectionDeps<T> {\n /** Internal grid reference (also serves as HTMLElement). */\n grid: GridHost<T>;\n /** Whether the grid is in always-editing \"grid\" mode. */\n isGridMode: boolean;\n /** Plugin configuration. */\n config: EditingConfig;\n /** Set of cells currently in edit mode (\"rowIndex:colIndex\"). */\n editingCells: Set<string>;\n /** Value-change callbacks keyed by \"rowIndex:field\". */\n editorValueCallbacks: Map<string, (newValue: unknown) => void>;\n /** Returns `true` when an edit session is active (#activeEditRow !== -1). */\n isEditSessionActive: () => boolean;\n /** Commit a single cell value change. */\n commitCellValue: (rowIndex: number, column: ColumnConfig<T>, newValue: unknown, rowData: T) => void;\n /** Exit editing for a row (commit or revert). */\n exitRowEdit: (rowIndex: number, revert: boolean) => void;\n}\n\n// #endregion\n\n// #region Editor Injection\n\n/**\n * Inject an editor into a cell element.\n *\n * Handles the full editor lifecycle: creates the editor host, resolves\n * the editor spec (template / custom-element / factory / component),\n * wires commit/cancel callbacks, and registers value-change listeners.\n */\nexport function injectEditor<T>(\n deps: EditorInjectionDeps<T>,\n rowData: T,\n rowIndex: number,\n column: ColumnConfig<T>,\n colIndex: number,\n cell: HTMLElement,\n skipFocus: boolean,\n parentRowEl?: HTMLElement,\n): void {\n if (!column.editable) return;\n if (cell.classList.contains('editing')) return;\n\n const { grid, isGridMode, config, editingCells, editorValueCallbacks } = deps;\n\n // Get row ID for updateRow helper (may not exist)\n let rowId: string | undefined;\n try {\n rowId = grid.getRowId?.(rowData);\n } catch {\n // Row has no ID\n }\n\n // Create updateRow helper for cascade updates (noop if row has no ID)\n const updateRow: (changes: Partial<T>) => void = rowId\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (changes) => (grid as any).updateRow(rowId!, changes as Record<string, unknown>, 'cascade')\n : noopUpdateRow;\n\n const originalValue = isSafePropertyKey(column.field) ? readCellField(rowData, column.field) : undefined;\n\n cell.classList.add('editing');\n editingCells.add(`${rowIndex}:${colIndex}`);\n\n // Use explicit parentRowEl when cell is in a DocumentFragment (not yet in DOM),\n // otherwise fall back to cell.parentElement for cells already attached to a row.\n const rowEl = (parentRowEl ?? cell.parentElement) as RowElementInternal | null;\n if (rowEl) incrementEditingCount(rowEl);\n\n let editFinalized = false;\n const commit = (newValue: unknown) => {\n // In grid mode, always allow commits (we're always editing)\n // In row mode, only allow commits if we're in an active edit session\n if (editFinalized || (!isGridMode && !deps.isEditSessionActive())) return;\n // Resolve row and index fresh at commit time.\n // With a row ID we use _getRowEntry for O(1) lookup — this is resilient\n // against _rows being replaced (e.g. Angular directive effect).\n // Without a row ID we fall back to the captured rowData reference.\n // Using _rows[rowIndex] without an ID is unsafe: the index may be stale\n // after _rows replacement, which would commit to the WRONG row.\n const entry = rowId ? grid._getRowEntry(rowId) : undefined;\n const currentRowData = (entry?.row ?? rowData) as T;\n const currentIndex = entry?.index ?? rowIndex;\n deps.commitCellValue(currentIndex, column, newValue, currentRowData);\n };\n const cancel = () => {\n editFinalized = true;\n if (isSafePropertyKey(column.field)) {\n // Same ID-first / captured-rowData fallback as commit — see comment above.\n const entry = rowId ? grid._getRowEntry(rowId) : undefined;\n const currentRowData = (entry?.row ?? rowData) as T;\n writeCellField(currentRowData, column.field, originalValue);\n }\n };\n\n const editorHost = document.createElement('div');\n editorHost.className = 'tbw-editor-host';\n // Let the framework adapter (React/Vue/Angular) tear down any renderer\n // it mounted into this cell BEFORE we wipe the DOM. The `cell.innerHTML`\n // assignment below removes adapter-managed nodes synchronously without\n // notifying the framework — which leaves React's fiber tree pointing at\n // orphan DOM and throws `removeChild` on the next user-triggered commit\n // (issue #250). Calling `releaseCell` here unmounts cleanly while the\n // adapter's container is still attached to its remembered children.\n // Guard with `firstElementChild` so default-rendered cells (no\n // adapter-managed nodes) skip the no-op call — matches the wipe-guard\n // pattern in `core/internal/rows.ts`.\n if (cell.firstElementChild) grid.__frameworkAdapter?.releaseCell?.(cell);\n cell.innerHTML = '';\n cell.appendChild(editorHost);\n\n // Keydown handler for Enter/Escape\n editorHost.addEventListener('keydown', (e: KeyboardEvent) => {\n // Respect editor-level preventDefault: portal-based pickers (combobox,\n // autocomplete, calendar) call preventDefault on Enter to confirm an\n // option without exiting the row. Bubbling reaches editorHost with\n // defaultPrevented=true; honor that and skip the row-exit logic (#250).\n if (e.defaultPrevented) return;\n // ARIA-expanded fallback (#251): when the focused control declares\n // an open overlay via aria-expanded=\"true\" + aria-controls, defer\n // Enter to the overlay so combobox confirmation does not close the\n // row edit. Covers libraries like Downshift / Headless UI / MUI\n // Autocomplete that do not call preventDefault on confirm.\n // Only short-circuit Enter — Escape and other keys must still flow\n // through the normal handlers (Escape closes the overlay first via\n // its own listener, then dispatches up to cancel-edit if unhandled).\n if (e.key === 'Enter') {\n const ariaTarget = e.target as HTMLElement | null;\n if (\n ariaTarget &&\n ariaTarget.getAttribute?.('aria-expanded') === 'true' &&\n ariaTarget.hasAttribute?.('aria-controls')\n ) {\n return;\n }\n }\n if (e.key === 'Enter') {\n // Native <select> open-popup guard — applies in BOTH grid and row mode.\n // When Enter's target is a *descendant* of the editor (most notably an\n // <option> inside an open native <select> popup), do nothing: let the\n // browser commit the highlighted option and close the popup, which fires\n // `change` on the editor (committing via the change listener wired below).\n // Calling preventDefault / stopPropagation / exitRowEdit here would\n // destroy the open popup and discard the selection. A subsequent Enter\n // (popup closed → target IS the editor) then exits the row as usual.\n // Row mode previously lacked this guard, so keyboard selection in custom\n // <select> editors closed the row instead of picking the value (#427).\n const enterTarget = e.target as Element | null;\n const enterEditorAncestor = getEditorAncestor(enterTarget);\n if (enterEditorAncestor && enterEditorAncestor !== enterTarget) {\n return;\n }\n // In grid mode, Enter just commits without exiting\n if (isGridMode) {\n // Target IS the editor itself (SELECT with no popup open, or\n // INPUT/TEXTAREA): commit the current value. preventDefault\n // suppresses the browser opening the SELECT popup on Enter.\n // We deliberately do NOT stopPropagation — the event must\n // bubble so EditingPlugin can blur the editor and return\n // focus to the grid for cell navigation.\n e.preventDefault();\n const input = editorHost.querySelector('input,textarea,select') as\n HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null;\n if (input) {\n commit(getInputValue(input, column as ColumnConfig<unknown>, originalValue));\n }\n return;\n }\n if (shouldPreventEditClose(config, e)) return;\n e.stopPropagation();\n e.preventDefault();\n editFinalized = true;\n deps.exitRowEdit(rowIndex, false);\n }\n if (e.key === 'Escape') {\n // In grid mode, Escape doesn't exit edit mode\n if (isGridMode) {\n e.stopPropagation();\n e.preventDefault();\n return;\n }\n if (shouldPreventEditClose(config, e)) return;\n e.stopPropagation();\n e.preventDefault();\n cancel();\n deps.exitRowEdit(rowIndex, true);\n }\n });\n\n const colInternal = column as ColumnInternal<T>;\n const tplHolder = colInternal.__editorTemplate;\n // Resolve editor using priority chain: column → template → typeDefaults → adapter → built-in\n const editorSpec = resolveEditor(grid, colInternal) ?? defaultEditorFor(column);\n const value = originalValue;\n\n // Value-change callback registration.\n // Editors call onValueChange(cb) to receive pushes when the underlying row\n // is mutated externally (e.g., via updateRow from another cell's commit).\n // Multiple callbacks can be registered (user + auto-wire).\n const callbackKey = `${rowIndex}:${column.field}`;\n const callbacks: Array<(newValue: unknown) => void> = [];\n editorValueCallbacks.set(callbackKey, (newVal) => {\n for (const cb of callbacks) cb(newVal);\n });\n const onValueChange = (cb: (newValue: unknown) => void) => {\n callbacks.push(cb);\n };\n\n if (editorSpec === 'template' && tplHolder) {\n renderTemplateEditor(deps, editorHost, colInternal, rowData, originalValue, commit, cancel, skipFocus, rowIndex);\n // Auto-update built-in template editors when value changes externally.\n // Skip non-primitive values (arrays, objects) — framework adapters manage\n // those via the cell-cancel event. String() on arrays produces comma-separated junk.\n onValueChange((newVal) => {\n if (newVal != null && typeof newVal === 'object') return;\n const input = editorHost.querySelector<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(\n 'input,textarea,select',\n );\n if (input) {\n if (input instanceof HTMLInputElement && input.type === 'checkbox') {\n input.checked = !!newVal;\n } else {\n input.value = String(newVal ?? '');\n }\n }\n });\n } else if (typeof editorSpec === 'string') {\n const el = document.createElement(editorSpec) as HTMLElement & { value?: unknown };\n el.value = value;\n el.addEventListener('change', () => commit(el.value));\n // Auto-update custom element editors when value changes externally\n onValueChange((newVal) => {\n el.value = newVal;\n });\n editorHost.appendChild(el);\n if (!skipFocus) {\n queueMicrotask(() => {\n const focusable = editorHost.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n focusable?.focus({ preventScroll: true });\n });\n }\n } else if (typeof editorSpec === 'function') {\n const ctx: ColumnEditorContext<T> = {\n row: rowData,\n rowId: rowId ?? '',\n value,\n field: column.field,\n column,\n commit,\n cancel,\n updateRow,\n onValueChange,\n grid: deps.grid as ColumnEditorContext<T>['grid'],\n };\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const produced = (editorSpec as any)(ctx);\n if (typeof produced === 'string') {\n // NOT sanitized on purpose: sanitizeHTML strips `input`/`select`/\n // `textarea`/`button`, which is exactly what an editor is made of. The\n // string comes from an author-supplied editor factory (code, not row\n // data) — row values reach the DOM through the compiled-template path\n // below, which escapes interpolated values.\n // eslint-disable-next-line no-restricted-syntax\n editorHost.innerHTML = produced;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wireEditorInputs(editorHost, column as any, commit, originalValue);\n // Auto-update wired inputs when value changes externally\n onValueChange((newVal) => {\n const input = editorHost.querySelector<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(\n 'input,textarea,select',\n );\n if (input) {\n if (input instanceof HTMLInputElement && input.type === 'checkbox') {\n input.checked = !!newVal;\n } else {\n input.value = String(newVal ?? '');\n }\n }\n });\n } else if (produced instanceof Node) {\n editorHost.appendChild(produced);\n const isSimpleInput =\n produced instanceof HTMLInputElement ||\n produced instanceof HTMLSelectElement ||\n produced instanceof HTMLTextAreaElement;\n if (!isSimpleInput) {\n cell.setAttribute('data-editor-managed', '');\n } else {\n // Auto-update simple inputs returned by factory functions\n onValueChange((newVal) => {\n if (produced instanceof HTMLInputElement && produced.type === 'checkbox') {\n produced.checked = !!newVal;\n } else {\n (produced as HTMLInputElement).value = String(newVal ?? '');\n }\n });\n }\n } else if (!produced && editorHost.hasChildNodes()) {\n // Factory returned void but mounted content into the editor host\n // (e.g. Angular/React/Vue adapter component editor). Mark the cell\n // as externally managed so the native commit loop in #exitRowEdit\n // does not read raw input values from framework editor DOM.\n cell.setAttribute('data-editor-managed', '');\n }\n if (!skipFocus) {\n queueMicrotask(() => {\n const focusable = editorHost.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n focusable?.focus({ preventScroll: true });\n });\n }\n } else if (editorSpec && typeof editorSpec === 'object') {\n const placeholder = document.createElement('div');\n placeholder.setAttribute('data-external-editor', '');\n placeholder.setAttribute('data-field', column.field);\n editorHost.appendChild(placeholder);\n cell.setAttribute('data-editor-managed', '');\n const context: ColumnEditorContext<T> = {\n row: rowData,\n rowId: rowId ?? '',\n value,\n field: column.field,\n column,\n commit,\n cancel,\n updateRow,\n onValueChange,\n grid: deps.grid as ColumnEditorContext<T>['grid'],\n };\n if (editorSpec.mount) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n editorSpec.mount({ placeholder, context: context as any, spec: editorSpec });\n } catch (e) {\n warnDiagnostic(\n EDITOR_MOUNT_ERROR,\n `External editor mount error for column '${column.field}': ${e}`,\n deps.grid.id,\n );\n }\n } else {\n grid.dispatchEvent(\n new CustomEvent('mount-external-editor', { detail: { placeholder, spec: editorSpec, context } }),\n );\n }\n }\n\n nameEditorFromHeader(editorHost, column);\n}\n\n/**\n * Give the editor an accessible name taken from its column header.\n *\n * A screen reader announces the header when focus lands on a *gridcell*, but an\n * `<input>` inside that cell is a control in its own right and needs its own\n * name (SC 4.1.2 / SC 3.3.2) — otherwise it is announced as a bare \"edit text\".\n * Deferred a microtask so editors that mount asynchronously are covered, and\n * skipped entirely whenever the control already has a name of any kind.\n */\nfunction nameEditorFromHeader<T>(editorHost: HTMLElement, column: ColumnConfig<T>): void {\n const label = typeof column.header === 'string' ? column.header : column.field;\n if (!label) return;\n\n queueMicrotask(() => {\n const control = editorHost.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n if (!control) return;\n const named =\n control.hasAttribute('aria-label') ||\n control.hasAttribute('aria-labelledby') ||\n control.hasAttribute('title') ||\n (control.id && editorHost.querySelector(`label[for=\"${CSS.escape(control.id)}\"]`)) ||\n control.closest('label');\n if (!named) control.setAttribute('aria-label', label);\n });\n}\n\n// #endregion\n\n// #region Template Editor\n\n/**\n * Render a template-based editor inside an editor host element.\n */\nfunction renderTemplateEditor<T>(\n deps: Pick<EditorInjectionDeps<T>, 'config' | 'exitRowEdit'>,\n editorHost: HTMLElement,\n column: ColumnInternal<T>,\n rowData: T,\n originalValue: unknown,\n commit: (value: unknown) => void,\n cancel: () => void,\n skipFocus: boolean,\n rowIndex: number,\n): void {\n const tplHolder = column.__editorTemplate;\n if (!tplHolder) return;\n\n const clone = tplHolder.cloneNode(true) as HTMLElement;\n const compiledEditor = column.__compiledEditor;\n\n if (compiledEditor) {\n // NOT sanitized: editor markup is author light-DOM (`<template editor>`) and\n // contains form controls the sanitizer would strip. Row data interpolated\n // via `{{ }}` is HTML-escaped by the compiled template itself.\n // eslint-disable-next-line no-restricted-syntax\n clone.innerHTML = compiledEditor({\n row: rowData,\n value: originalValue,\n field: column.field,\n column,\n commit,\n cancel,\n });\n } else {\n clone.querySelectorAll<HTMLElement>('*').forEach((node) => {\n if (node.childNodes.length === 1 && node.firstChild?.nodeType === Node.TEXT_NODE) {\n node.textContent =\n node.textContent\n ?.replace(/{{\\s*value\\s*}}/g, originalValue == null ? '' : String(originalValue))\n .replace(/{{\\s*row\\.([a-zA-Z0-9_]+)\\s*}}/g, (_m, g: string) => {\n if (!isSafePropertyKey(g)) return '';\n const v = (rowData as Record<string, unknown>)[g];\n return v == null ? '' : String(v);\n }) || '';\n }\n });\n }\n\n const input = clone.querySelector<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(\n 'input,textarea,select',\n );\n if (input) {\n if (input instanceof HTMLInputElement && input.type === 'checkbox') {\n input.checked = !!originalValue;\n } else {\n input.value = String(originalValue ?? '');\n }\n\n let editFinalized = false;\n input.addEventListener('blur', () => {\n if (editFinalized) return;\n commit(getInputValue(input, column, originalValue));\n });\n input.addEventListener('keydown', (evt) => {\n const e = evt as KeyboardEvent;\n if (e.key === 'Enter') {\n if (shouldPreventEditClose(deps.config, e)) return;\n e.stopPropagation();\n e.preventDefault();\n editFinalized = true;\n commit(getInputValue(input, column, originalValue));\n deps.exitRowEdit(rowIndex, false);\n }\n if (e.key === 'Escape') {\n if (shouldPreventEditClose(deps.config, e)) return;\n e.stopPropagation();\n e.preventDefault();\n cancel();\n deps.exitRowEdit(rowIndex, true);\n }\n });\n if (input instanceof HTMLInputElement && input.type === 'checkbox') {\n input.addEventListener('change', () => commit(input.checked));\n }\n if (!skipFocus) {\n setTimeout(() => input.focus({ preventScroll: true }), 0);\n }\n }\n editorHost.appendChild(clone);\n}\n\n// #endregion\n","/**\n * Editing Plugin\n *\n * Provides complete editing functionality for tbw-grid.\n * This plugin is FULLY SELF-CONTAINED - the grid has ZERO editing knowledge.\n *\n * The plugin:\n * - Owns all editing state (active cell, snapshots, changed rows)\n * - Uses event distribution (onCellClick, onKeyDown) to handle edit lifecycle\n * - Uses afterRender() hook to inject editors into cells\n * - Uses processColumns() to augment columns with editing metadata\n * - Emits its own events (cell-commit, row-commit, changed-rows-reset)\n *\n * Without this plugin, the grid cannot edit. With this plugin, editing\n * is fully functional without any core changes.\n */\n\nimport { GridDataAttrs } from '../../core/constants';\nimport { announce, getA11yMessage } from '../../core/internal/aria';\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { compileTemplate } from '../../core/internal/sanitize';\nimport { invalidateAccessorCache, readCellField, writeCellField } from '../../core/internal/value-accessor';\nimport type {\n AfterCellRenderContext,\n AfterRowRenderContext,\n PluginManifest,\n PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport { BaseGridPlugin, type CellClickEvent, type GridElement } from '../../core/plugin/base-plugin';\nimport type { CellEditablePredicate, CommitCellValueContext } from '../../core/plugin/types';\nimport type {\n ColumnConfig,\n ColumnInternal,\n GridHost,\n InternalGrid,\n RowElementInternal,\n TypeDefault,\n UpdateSource,\n} from '../../core/types';\nimport styles from './editing.css?inline';\nimport { getInputValue } from './editors';\nimport { CellValidationManager } from './internal/cell-validation';\nimport { type BaselinesCapturedDetail, type DirtyChangeDetail, type DirtyRowEntry } from './internal/dirty-tracking';\nimport { DirtyTrackingManager } from './internal/dirty-tracking-manager';\nimport { type EditorInjectionDeps, injectEditor as injectEditorImpl } from './internal/editor-injection';\nimport {\n clearEditingState,\n FOCUSABLE_EDITOR_SELECTOR,\n getEditorAncestor,\n hasRowChanged,\n isInsideOpenAriaOverlay,\n isSafePropertyKey,\n noopUpdateRow,\n shouldPreventEditClose,\n} from './internal/helpers';\nimport type {\n BeforeEditCloseDetail,\n CellCancelDetail,\n CellCommitDetail,\n ChangedRowsResetDetail,\n EditCloseDetail,\n EditingConfig,\n EditOpenDetail,\n RowCommitDetail,\n} from './types';\n\n// ============================================================================\n// EditingPlugin\n// ============================================================================\n\n/**\n * Editing Plugin for tbw-grid\n *\n * Enables inline cell editing in the grid. Provides built-in editors for common data types\n * and supports custom editor functions for specialized input scenarios.\n *\n * ## Why Opt-In?\n *\n * Editing is delivered as a plugin rather than built into the core grid:\n *\n * - **Smaller bundle** — Apps that only display data don't pay for editing code\n * - **Clear intent** — Explicit plugin registration makes editing capability obvious\n * - **Runtime validation** — Using `editable: true` without the plugin throws a helpful error\n *\n * ## Installation\n *\n * ```ts\n * import { EditingPlugin } from '@toolbox-web/grid/plugins/editing';\n * ```\n *\n * ## Edit Triggers\n *\n * Configure how editing is triggered with the `editOn` option:\n *\n * | Value | Behavior |\n * |-------|----------|\n * | `'click'` | Single click enters edit mode (default) |\n * | `'dblclick'` | Double-click enters edit mode |\n *\n * ## Keyboard Shortcuts\n *\n * | Key | Action |\n * |-----|--------|\n * | `Enter` | Commit edit and move down |\n * | `Tab` | Commit edit and move right |\n * | `Escape` | Cancel edit, restore original value |\n * | `Arrow Keys` | Navigate between cells (when not editing) |\n *\n * @example Basic editing with double-click trigger\n * ```ts\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', editable: true },\n * { field: 'price', type: 'number', editable: true },\n * { field: 'active', type: 'boolean', editable: true },\n * ],\n * plugins: [new EditingPlugin({ editOn: 'dblclick' })],\n * };\n *\n * grid.on('cell-commit', ({ field, oldValue, newValue }) => {\n * console.log(`${field}: ${oldValue} → ${newValue}`);\n * });\n * ```\n *\n * @example Custom editor function\n * ```ts\n * columns: [\n * {\n * field: 'status',\n * editable: true,\n * editor: (ctx) => {\n * const select = document.createElement('select');\n * ['pending', 'active', 'completed'].forEach(opt => {\n * const option = document.createElement('option');\n * option.value = opt;\n * option.textContent = opt;\n * option.selected = ctx.value === opt;\n * select.appendChild(option);\n * });\n * select.addEventListener('change', () => ctx.commit(select.value));\n * return select;\n * },\n * },\n * ]\n * ```\n *\n * @see {@link EditingConfig} for configuration options\n * @see `ColumnEditorContext` for custom editor context\n * @see {@link EditingConfig} for interactive examples in the docs site\n * @since 0.4.0\n */\nexport class EditingPlugin<T = unknown> extends BaseGridPlugin<EditingConfig> {\n /**\n * Plugin manifest - declares owned properties for configuration validation.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n ownedProperties: [\n {\n property: 'editable',\n level: 'column',\n description: 'the \"editable\" column property',\n isUsed: (v) => v === true || typeof v === 'function',\n },\n {\n property: 'editor',\n level: 'column',\n description: 'the \"editor\" column property',\n },\n {\n property: 'editorParams',\n level: 'column',\n description: 'the \"editorParams\" column property',\n },\n {\n property: 'nullable',\n level: 'column',\n description: 'the \"nullable\" column property (allows null values)',\n },\n ],\n events: [\n {\n type: 'cell-edit-committed',\n description: 'Emitted when a cell edit is committed (for plugin-to-plugin coordination)',\n },\n ],\n queries: [\n {\n type: 'isEditing',\n description: 'Returns whether any cell is currently being edited',\n },\n {\n type: 'getCellEditableResolver',\n description:\n 'Returns a predicate (field, row) => boolean resolving per-cell editability (rowEditable gate + column.editable true/false/function), for consumers like clipboard paste',\n },\n {\n type: 'commitCellValue',\n description:\n 'Commits a single cell value coming from a core row mutation (updateRow/updateRows), running the full edit pipeline: cancelable cell-commit (validation/abortion), dirty tracking, history, and cascade. Returns true (applied), false (vetoed), or undefined (not handled).',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'editing';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<EditingConfig> {\n return {\n mode: 'row',\n editOn: 'click',\n };\n }\n\n /**\n * Whether the grid is in 'grid' mode (all cells always editable).\n */\n get #isGridMode(): boolean {\n return this.config.mode === 'grid';\n }\n\n /**\n * Resolve whether a given cell is editable.\n *\n * Resolution order:\n * 1. `gridConfig.rowEditable(row)` — row-level gate (if provided). Returns `false` → not editable.\n * 2. `column.editable` — `true`, `false`, or `(row) => boolean`.\n *\n * @returns `true` when the cell should be editable, `false` otherwise.\n */\n #isCellEditable(column: ColumnConfig<T>, row: T): boolean {\n // Row-level gate\n const rowEditable = this.#internalGrid.effectiveConfig?.rowEditable;\n if (rowEditable && !rowEditable(row as any)) return false;\n\n // Column-level check\n const { editable } = column;\n if (typeof editable === 'function') return editable(row);\n return editable === true;\n }\n\n /**\n * Check whether a column has ANY editability configured (static `true` or a\n * function). This is used for quick checks where no specific row is available\n * (e.g. \"does this row have any potentially-editable columns?\").\n */\n #hasEditableConfig(column: ColumnConfig<T>): boolean {\n return column.editable === true || typeof column.editable === 'function';\n }\n\n // #region Editing State (fully owned by plugin)\n\n /** Currently active edit row index, or -1 if not editing */\n #activeEditRow = -1;\n\n /** Row ID of the currently active edit row (stable across _rows replacement) */\n #activeEditRowId: string | undefined;\n\n /** Reference to the row object at edit-open time. Used as fallback in\n * #exitRowEdit when no row ID is available (prevents stale-index access). */\n #activeEditRowRef: T | undefined;\n\n /** Currently active edit column index, or -1 if not editing */\n #activeEditCol = -1;\n\n /** Snapshots of row data before editing started */\n #rowEditSnapshots = new Map<number, T>();\n\n /** Set of cells currently in edit mode: \"rowIndex:colIndex\" */\n #editingCells = new Set<string>();\n\n /**\n * Light-DOM elements whose declarative attributes have already been read.\n * The `editable` attribute (and `<tbw-grid-column-editor>` template) supply\n * the INITIAL state only — seeding once guarantees a later runtime/config\n * change to a falsy value is not re-applied on the next `processColumns`\n * pass (issue #272). Reset in `detach()` so a re-attached instance re-seeds.\n */\n #seededFromAttr = new WeakSet<HTMLElement>();\n\n /**\n * Value-change callbacks for active editors.\n * Keyed by \"rowIndex:field\" → callback that pushes updated values to the editor.\n * Populated during #injectEditor, cleaned up when editors are removed.\n */\n #editorValueCallbacks = new Map<string, (newValue: unknown) => void>();\n\n /** Flag to restore focus after next render (used when exiting edit mode) */\n #pendingFocusRestore = false;\n\n /** Row index pending animation after render, or -1 if none */\n #pendingRowAnimation = -1;\n\n /**\n * Cell validation manager — handles invalid-cell state tracking and DOM sync.\n * Initialized lazily in `attach()` since the sync callback needs grid access.\n */\n #validation!: CellValidationManager;\n\n /**\n * In grid mode, tracks whether an input field is currently focused.\n * When true: arrow keys work within input (edit mode).\n * When false: arrow keys navigate between cells (navigation mode).\n * Escape switches to navigation mode, Enter switches to edit mode.\n */\n #gridModeInputFocused = false;\n\n /**\n * In grid mode, when true, prevents inputs from auto-focusing.\n * This is set when Escape is pressed (navigation mode) and cleared\n * when Enter is pressed or user explicitly clicks an input.\n */\n #gridModeEditLocked = false;\n\n /**\n * When true, only a single cell is being edited (triggered by F2 or `beginCellEdit`).\n * Tab and Arrow keys commit and close the editor instead of navigating to adjacent cells.\n */\n #singleCellEdit = false;\n\n /**\n * In grid mode, snapshot of the focused cell's value when the editor first\n * receives focus. Used to revert on Escape (cell-level cancel).\n */\n #gridModeCellSnapshot: { rowIndex: number; colIndex: number; field: string; value: unknown } | null = null;\n\n // --- Dirty Tracking State (delegated to DirtyTrackingManager) ---\n\n /** Manages all dirty tracking state: baselines, changed/new/committed sets. */\n readonly #dirty = new DirtyTrackingManager<T>();\n\n /**\n * Cells currently mid-`cell-commit`, keyed `` `${rowId ?? rowIndex}\\0${field}` ``.\n * A `cell-commit` listener commonly cascades by calling `updateRow`, which\n * routes back through this commit pipeline synchronously. When such a nested\n * update targets a cell already in this set, `#commitCellValue` returns early\n * (the outer commit owns the single apply + `cell-edit-committed`), preventing\n * the infinite `updateRow → cell-commit → updateRow` recursion WITHOUT any\n * consumer-side re-entrancy guard and WITHOUT duplicating history or bypassing\n * a pending `preventDefault()`.\n */\n readonly #committingCells = new Set<string>();\n\n // --- Editor Injection Deps (cached for #injectEditor delegation) ---\n\n /** Dependency bag created once in `attach()` and reused by every `#injectEditor` call. */\n #editorDeps!: EditorInjectionDeps<T>;\n\n /**\n * Narrows the grid to its row type `T`. `GridElement` is intentionally\n * non-generic, so this accessor re-applies the plugin's own `T`.\n */\n get #internalGrid(): GridHost<T> {\n return this.grid;\n }\n\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n const signal = this.disconnectSignal;\n const internalGrid = this.#internalGrid;\n\n // Initialize cell validation manager with DOM sync callback\n this.#validation = new CellValidationManager((rowId, field, invalid) => {\n this.#syncInvalidCellAttribute(rowId, field, invalid);\n });\n\n // Initialize editor injection deps (cached for all #injectEditor calls)\n this.#editorDeps = {\n grid: internalGrid,\n isGridMode: this.#isGridMode,\n config: this.config,\n editingCells: this.#editingCells,\n editorValueCallbacks: this.#editorValueCallbacks,\n isEditSessionActive: () => this.#activeEditRow !== -1,\n commitCellValue: (ri, col, val, row) => this.#commitCellValue(ri, col, val, row),\n exitRowEdit: (ri, revert) => this.#exitRowEdit(ri, revert),\n };\n\n // Inject editing state and methods onto grid for backward compatibility\n this.#syncGridEditState();\n\n // Inject changedRows getter\n Object.defineProperty(grid, 'changedRows', {\n get: () => this.changedRows,\n configurable: true,\n });\n\n // Inject changedRowIds getter (new ID-based API)\n Object.defineProperty(grid, 'changedRowIds', {\n get: () => this.changedRowIds,\n configurable: true,\n });\n\n // Inject raw Set for O(1) lookup in the render hot path\n Object.defineProperty(grid, '_changedRowIdSet', {\n get: () => this.#dirty.changedRowIds,\n configurable: true,\n });\n\n // Inject resetChangedRows method\n (grid as any).resetChangedRows = (silent?: boolean) => this.resetChangedRows(silent);\n\n this.#attachRowModeListeners(signal, internalGrid);\n\n // In grid mode, request a full render to trigger afterCellRender hooks\n if (this.#isGridMode) {\n internalGrid._isGridEditMode = true;\n this.gridElement.classList.add('tbw-grid-mode');\n this.requestRender();\n this.#attachGridModeListeners(signal, internalGrid);\n }\n }\n\n /**\n * Row-mode editing wiring: document-level Escape/click-outside exit, the optional\n * focus trap, external `cell-change` push-down into open editors, and undo/redo\n * dirty re-evaluation. Registered unconditionally — each handler self-guards on\n * `#isGridMode` / its own config flag.\n */\n #attachRowModeListeners(signal: AbortSignal, internalGrid: GridHost<T>): void {\n // Document-level Escape to cancel editing (only in 'row' mode)\n document.addEventListener(\n 'keydown',\n (e: KeyboardEvent) => {\n // In grid mode, Escape doesn't exit edit mode\n if (this.#isGridMode) return;\n if (e.key === 'Escape' && this.#activeEditRow !== -1) {\n if (shouldPreventEditClose(this.config, e)) return;\n this.#exitRowEdit(this.#activeEditRow, true);\n }\n },\n { capture: true, signal },\n );\n\n // Click outside to commit editing (only in 'row' mode)\n // Use queueMicrotask to allow pending change events to fire first.\n // This is important for Angular/React editors where the (change) event\n // fires after mousedown but before mouseup/click.\n document.addEventListener(\n 'mousedown',\n (e: MouseEvent) => {\n // In grid mode, clicking outside doesn't exit edit mode\n if (this.#isGridMode) return;\n if (this.#activeEditRow === -1) return;\n const rowEl = internalGrid.findRenderedRowElement?.(this.#activeEditRow);\n if (!rowEl) return;\n const path = (e.composedPath && e.composedPath()) || [];\n if (path.includes(rowEl)) return;\n\n // Check if click is inside a registered external focus container\n // (e.g., overlays, datepickers, dropdowns at <body> level).\n // Only check targets OUTSIDE the grid — clicks on other rows inside\n // the grid should still commit the active edit row.\n const target = e.target as Node | null;\n if (target && !this.gridElement.contains(target) && this.grid.containsFocus?.(target)) {\n return;\n }\n\n // ARIA-expanded fallback (#251): when the click target lives inside\n // an overlay declared by an open combobox/listbox in the active edit\n // row (aria-expanded=\"true\" + aria-controls=<id>), treat it as part\n // of the editor. Covers Downshift / Headless UI / MUI Autocomplete\n // panels that opt out of registerExternalFocusContainer.\n if (target && !this.gridElement.contains(target)) {\n const rowEl = internalGrid.findRenderedRowElement?.(this.#activeEditRow);\n if (rowEl && isInsideOpenAriaOverlay(target, rowEl)) return;\n }\n\n if (shouldPreventEditClose(this.config, e)) return;\n\n // Delay exit to allow pending change/commit events to fire\n queueMicrotask(() => {\n if (this.#activeEditRow !== -1) {\n this.#exitRowEdit(this.#activeEditRow, false);\n }\n });\n },\n { signal },\n );\n\n // Focus trap: when enabled, prevent focus from leaving the grid\n // while a row is being edited. If focus moves outside the grid\n // (and its registered external containers), reclaim it.\n if (this.config.focusTrap) {\n this.gridElement.addEventListener(\n 'focusout',\n (e: FocusEvent) => {\n // Only trap in row mode when actively editing\n if (this.#isGridMode) return;\n if (this.#activeEditRow === -1) return;\n\n const related = e.relatedTarget as Node | null;\n // If focus is going to an external container, that's fine\n if (related && this.grid.containsFocus?.(related)) return;\n // If focus is going to another element inside the grid, allow it\n if (related && this.gridElement.contains(related)) return;\n\n // Focus left the grid entirely — reclaim it\n queueMicrotask(() => {\n // Re-check in case editing was committed in the meantime\n if (this.#activeEditRow === -1) return;\n this.#focusCurrentCellEditor();\n });\n },\n { signal },\n );\n }\n\n // Listen for external row mutations to push updated values to active editors.\n // When field A commits and sets field B via updateRow(), field B's editor\n // (if open) must reflect the new value.\n this.gridElement.addEventListener(\n 'cell-change',\n (e: Event) => {\n const detail = (e as CustomEvent).detail as {\n rowIndex: number;\n field: string;\n newValue: unknown;\n source: string;\n };\n // Only push updates from cascade/api sources — not from the editor's own commit\n if (detail.source === 'user') return;\n const key = `${detail.rowIndex}:${detail.field}`;\n const cb = this.#editorValueCallbacks.get(key);\n if (cb) cb(detail.newValue);\n },\n { signal },\n );\n\n // --- Dirty tracking: listen for undo/redo events to re-evaluate dirty state ---\n if (this.config.dirtyTracking) {\n const handleUndoRedo = (e: Event) => {\n const detail = (e as CustomEvent).detail as { action?: { rowIndex: number; field: string } };\n const action = detail?.action;\n if (!action) return;\n const row = this.rows[action.rowIndex] as T | undefined;\n if (!row) return;\n const rowId = this.#safeGetRowId(row);\n if (!rowId) return;\n const dirty = this.#dirty.isRowDirty(rowId, row);\n this.#emitDirtyChange(rowId, row, dirty ? 'modified' : 'pristine');\n };\n this.gridElement.addEventListener('undo', handleUndoRedo, { signal });\n this.gridElement.addEventListener('redo', handleUndoRedo, { signal });\n\n // Listen for row-inserted events to auto-mark new rows for dirty tracking\n this.on('row-inserted', (detail: { row: T; index: number }) => {\n const rowId = this.#safeGetRowId(detail.row);\n if (rowId != null) {\n this.markAsNew(String(rowId));\n }\n });\n }\n }\n\n /**\n * Grid-mode (\"spreadsheet\") editing wiring: focus/blur tracking that distinguishes\n * navigation mode from edit mode, Escape-to-navigation, and click-to-unlock.\n * Only registered when `editing.mode === 'grid'`.\n */\n #attachGridModeListeners(signal: AbortSignal, internalGrid: GridHost<T>): void {\n // Track focus/blur on inputs to maintain navigation vs edit mode state\n this.gridElement.addEventListener(\n 'focusin',\n (e: FocusEvent) => {\n const target = e.target as HTMLElement;\n // Ignore focus on the grid element itself — it has tabindex=0 so it\n // matches FOCUSABLE_EDITOR_SELECTOR, but blurring + re-focusing it\n // would cause infinite recursion.\n if (target === this.gridElement) return;\n if (target.matches(FOCUSABLE_EDITOR_SELECTOR)) {\n // If edit is locked (navigation mode), blur the input immediately\n if (this.#gridModeEditLocked) {\n target.blur();\n this.gridElement.focus();\n return;\n }\n\n // Snapshot cell value on initial focus or when moving to a different cell.\n // This allows Escape to revert the cell to its pre-edit value.\n const focusRow = internalGrid._focusRow;\n const focusCol = internalGrid._focusCol;\n const snap = this.#gridModeCellSnapshot;\n if (!snap || snap.rowIndex !== focusRow || snap.colIndex !== focusCol) {\n const column = internalGrid._visibleColumns?.[focusCol];\n const rowData = internalGrid._rows?.[focusRow];\n if (column?.field && rowData) {\n const field = column.field as string;\n this.#gridModeCellSnapshot = {\n rowIndex: focusRow,\n colIndex: focusCol,\n field,\n value: readCellField(rowData, field),\n };\n }\n }\n\n this.#gridModeInputFocused = true;\n }\n },\n { signal },\n );\n\n this.gridElement.addEventListener(\n 'focusout',\n (e: FocusEvent) => {\n const target = e.target as HTMLElement | null;\n const related = e.relatedTarget as HTMLElement | null;\n // Intra-editor focus moves MUST NOT flip the flag — the editor\n // is still logically focused. Cases observed in the wild:\n // - Native <select> opening: SELECT → child OPTION\n // - Native <select> popup ArrowDown: OPTION → sibling OPTION\n // - Framework editors moving focus to inner popup descendants\n // Detect via two ancestry checks: (a) `target` contains `related`\n // (parent-to-descendant), or (b) `related` lives inside an\n // editor element (input/select/textarea/contenteditable) — this\n // covers OPTION-to-OPTION and any other intra-editor traversal.\n // Exclude `gridElement` itself: it has tabindex=0 and so matches\n // FOCUSABLE_EDITOR_SELECTOR, but focus moving to the grid host\n // means we ARE leaving the editor — the explicit Escape/Enter\n // paths handle that by setting the flag to false themselves.\n if (target && related) {\n if (target.contains(related)) return;\n const relatedEditor = getEditorAncestor(related);\n if (relatedEditor && relatedEditor !== this.gridElement && this.gridElement.contains(relatedEditor)) {\n return;\n }\n }\n // Only clear if focus went outside grid (and external containers) or to a non-input element\n if (\n !related ||\n (!this.gridElement.contains(related) && !this.grid.containsFocus?.(related)) ||\n !related.matches(FOCUSABLE_EDITOR_SELECTOR)\n ) {\n this.#gridModeInputFocused = false;\n // Clear cell snapshot when leaving edit mode normally (not via Escape)\n this.#gridModeCellSnapshot = null;\n }\n },\n { signal },\n );\n\n // Handle Escape key directly on the grid element (capture phase)\n // This ensures we intercept Escape even when focus is inside an input\n this.gridElement.addEventListener(\n 'keydown',\n (e: KeyboardEvent) => {\n if (e.key === 'Escape' && this.#gridModeInputFocused) {\n // Check onBeforeEditClose to let overlays close first.\n if (shouldPreventEditClose(this.config, e)) {\n // Overlay is open — schedule deferred nav-mode transition\n // after the overlay tears down.\n queueMicrotask(() => {\n if (this.#gridModeInputFocused) {\n this.#enterGridModeNavigation();\n }\n });\n return;\n }\n this.#enterGridModeNavigation();\n e.preventDefault();\n e.stopPropagation();\n }\n },\n { capture: true, signal },\n );\n\n // Handle click on inputs - unlock edit mode when user explicitly clicks\n this.gridElement.addEventListener(\n 'mousedown',\n (e: MouseEvent) => {\n const target = e.target as HTMLElement;\n if (target.matches(FOCUSABLE_EDITOR_SELECTOR)) {\n this.#gridModeEditLocked = false; // User clicked input - allow edit\n }\n },\n { signal },\n );\n }\n\n /** @internal */\n override detach(): void {\n const internalGrid = this.#internalGrid;\n internalGrid._isGridEditMode = false;\n this.gridElement.classList.remove('tbw-grid-mode');\n this.#activeEditRow = -1;\n this.#activeEditRowId = undefined;\n this.#activeEditRowRef = undefined;\n this.#activeEditCol = -1;\n this.#rowEditSnapshots.clear();\n this.#dirty.clear();\n this.#editingCells.clear();\n this.#editorValueCallbacks.clear();\n this.#gridModeInputFocused = false;\n this.#gridModeEditLocked = false;\n this.#gridModeCellSnapshot = null;\n this.#singleCellEdit = false;\n this.#seededFromAttr = new WeakSet<HTMLElement>();\n super.detach();\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'isEditing') {\n // In grid mode, we're always editing\n return this.#isGridMode || this.#activeEditRow !== -1;\n }\n if (query.type === 'getCellEditableResolver') {\n // Return a predicate that applies the plugin's full per-cell editability\n // resolution (rowEditable gate + column.editable true/false/function).\n // Fields are mapped to columns once; consumers (e.g. clipboard paste)\n // then ask per cell without importing editing-owned config.\n const columns = (this.#internalGrid.effectiveConfig?.columns as ColumnConfig<T>[] | undefined) ?? [];\n const byField = new Map<string, ColumnConfig<T>>();\n for (const col of columns) byField.set(col.field, col);\n const resolver: CellEditablePredicate = (field, row) => {\n const col = byField.get(field);\n return col ? this.#isCellEditable(col, row as T) : false;\n };\n return resolver;\n }\n if (query.type === 'commitCellValue') {\n return this.#handleCommitCellValue(query.context as CommitCellValueContext);\n }\n return undefined;\n }\n\n /**\n * Answer the core `commitCellValue` query dispatched from `updateRow`/\n * `updateRows`. Routes the change through the full edit pipeline so\n * programmatic mutations participate in validation, dirty tracking, history,\n * and cascade — exactly like an interactive edit.\n *\n * @returns `true` when applied, `false` when a `cell-commit` handler vetoed\n * it (abortion), or `undefined` when the field/row can't be resolved (core\n * then applies the value directly).\n * @internal\n */\n #handleCommitCellValue(ctx: CommitCellValueContext): boolean | undefined {\n const internalGrid = this.#internalGrid;\n const columns = (internalGrid._visibleColumns as ColumnConfig<T>[] | undefined) ?? [];\n const column =\n columns.find((c) => c.field === ctx.field) ??\n (internalGrid._columns as ColumnConfig<T>[] | undefined)?.find((c) => c.field === ctx.field);\n const rowData =\n (ctx.row as T | undefined) ??\n (ctx.rowId != null ? internalGrid._getRowEntry(ctx.rowId)?.row : undefined) ??\n (internalGrid._rows?.[ctx.rowIndex] as T | undefined);\n\n if (ctx.source === 'sync') {\n // Declarative host sync (a framework adapter replacing its `rows` prop in\n // place). Authoritative external data, NOT a user edit: apply the value and\n // re-baseline the cell so the new value is the pristine truth — the row is\n // never marked dirty and no undo/redo history is recorded (and no cascade).\n // Handled before the column guard so non-column fields (dirty tracking\n // snapshots the whole row) are re-baselined too.\n if (!rowData || !isSafePropertyKey(ctx.field)) return undefined;\n writeCellField(rowData, ctx.field, ctx.newValue);\n invalidateAccessorCache(rowData as object);\n const rowId = this.#safeGetRowId(rowData);\n if (rowId && this.config.dirtyTracking) {\n this.#dirty.rebaselineCell(rowId, ctx.field, ctx.newValue);\n const stillDirty = this.#dirty.isRowDirty(rowId, rowData);\n if (!stillDirty) this.#dirty.changedRowIds.delete(rowId);\n this.#emitDirtyChange(rowId, rowData, stillDirty ? 'modified' : 'pristine');\n }\n return true;\n }\n\n if (!column || !rowData || !isSafePropertyKey(ctx.field)) return undefined; // core applies directly\n\n if (ctx.source === 'history') {\n // Undo/redo re-application: apply the value but DO NOT record a fresh\n // history entry or mark the row changed — the undo stack owns this change.\n // Recompute dirty so the row's changed flag reflects its baseline.\n writeCellField(rowData, ctx.field, ctx.newValue);\n invalidateAccessorCache(rowData as object);\n const rowId = this.#safeGetRowId(rowData);\n if (rowId && this.config.dirtyTracking) {\n const dirty = this.#dirty.isRowDirty(rowId, rowData);\n if (!dirty) this.#dirty.changedRowIds.delete(rowId);\n this.#emitDirtyChange(rowId, rowData, dirty ? 'modified' : 'pristine');\n }\n return true;\n }\n\n // Normal path: full commit pipeline (cancelable cell-commit for\n // validation/abortion, dirty tracking, history via cell-edit-committed,\n // cascade). #commitCellValue leaves the value unchanged when a handler\n // vetoes, so compare to detect abortion.\n this.#commitCellValue(ctx.rowIndex, column, ctx.newValue, rowData, ctx.source);\n return readCellField(rowData, ctx.field) === ctx.newValue;\n }\n\n // #endregion\n\n // #region Event Handlers (event distribution)\n\n /**\n * Handle cell clicks - start editing if configured for click mode.\n * Both click and dblclick events come through this handler.\n * Starts row-based editing (all editable cells in the row get editors).\n * @internal\n */\n override onCellClick(event: CellClickEvent): boolean | void {\n // In grid mode, all cells are already editable - no need to trigger row edit\n if (this.#isGridMode) return false;\n\n const internalGrid = this.#internalGrid;\n const editOn = this.config.editOn ?? internalGrid.effectiveConfig?.editOn;\n\n // Check if editing is disabled\n if (editOn === false || editOn === 'manual') return false;\n\n // Check if this is click or dblclick mode\n if (editOn !== 'click' && editOn !== 'dblclick') return false;\n\n // Check if the event type matches the edit mode\n const isDoubleClick = event.originalEvent.type === 'dblclick';\n if (editOn === 'click' && isDoubleClick) return false; // In click mode, only handle single clicks\n if (editOn === 'dblclick' && !isDoubleClick) return false; // In dblclick mode, only handle double clicks\n\n const { rowIndex } = event;\n\n // Check if any column in the row is potentially editable\n const hasEditableColumn = internalGrid._columns?.some((col) => this.#hasEditableConfig(col as ColumnConfig<T>));\n if (!hasEditableColumn) return false;\n\n // Row-level gate\n if (!this.#isRowEditable(internalGrid._rows[rowIndex] as T | undefined)) return false;\n\n // Start row-based editing (all editable cells get editors)\n event.originalEvent.stopPropagation();\n this.beginBulkEdit(rowIndex);\n return true; // Handled\n }\n\n /**\n * Handle keyboard events for edit lifecycle.\n * @internal\n */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n switch (event.key) {\n case 'Escape':\n return this.#onEscapeKey(event);\n case 'ArrowUp':\n case 'ArrowDown':\n case 'ArrowLeft':\n case 'ArrowRight':\n return this.#onArrowKey(event);\n case 'Tab':\n return this.#onTabKey(event);\n case ' ':\n case 'Spacebar':\n return this.#onSpaceKey(event);\n case 'Enter':\n // Modified Enter (Shift/Ctrl/Alt/Meta) is not ours — don't block it.\n if (event.shiftKey || event.ctrlKey || event.altKey || event.metaKey) return false;\n return this.#onEnterKey(event);\n case 'F2':\n return this.#onF2Key(event);\n default:\n // Don't block other keyboard events\n return false;\n }\n }\n\n /**\n * Escape: cancel the current edit (row mode) or leave edit mode (grid mode).\n *\n * NOTE: No `onBeforeEditClose` check here — the capture-phase handler is the\n * authoritative overlay guard. If the event reaches this bubble-phase handler,\n * either (a) the capture handler already bailed (overlay was open) and the\n * template handler (e.g. `select.close()`) addressed it, or (b) no overlay was\n * open. In both cases we should transition to navigation mode.\n */\n #onEscapeKey(event: KeyboardEvent): boolean {\n // In grid mode: revert cell, blur input, enter navigation mode.\n if (this.#isGridMode && this.#gridModeInputFocused) {\n this.#enterGridModeNavigation();\n // Update focus styling\n this.requestAfterRender();\n return true;\n }\n\n // In row mode: cancel edit\n if (this.#activeEditRow !== -1 && !this.#isGridMode) {\n if (shouldPreventEditClose(this.config, event)) return true;\n this.#exitRowEdit(this.#activeEditRow, true);\n return true;\n }\n\n return false;\n }\n\n /**\n * Arrow keys — decides whether the grid navigates or the editor keeps the key.\n *\n * `#gridModeInputFocused` is a cached flag, so `event.target` is used as a\n * fallback: a stale flag (e.g. between a native `<select>` popup opening and\n * our focusout/focusin guard updating it) must not hijack ArrowUp/Down away\n * from a focused editor. Uses `closest()` (not `matches()`) so descendants of\n * an editor — most notably `<option>` children of an open native `<select>`\n * popup — also count as \"keydown originating inside an editor\".\n */\n #onArrowKey(event: KeyboardEvent): boolean {\n const arrowEditorAncestor = getEditorAncestor(event.target);\n const targetIsEditor = !!arrowEditorAncestor && arrowEditorAncestor !== this.gridElement;\n const isVertical = event.key === 'ArrowUp' || event.key === 'ArrowDown';\n\n // Grid mode, no editor focused: let the grid's default navigation handle it.\n if (this.#isGridMode && !this.#gridModeInputFocused && !targetIsEditor) return false;\n\n // Grid mode with a focused editor: ArrowUp/Down belong to the editor\n // (e.g. ArrowDown opens autocomplete/datepicker overlays, ArrowUp/Down\n // navigates options). Handled: block grid navigation, let event reach editor.\n if (this.#isGridMode && (this.#gridModeInputFocused || targetIsEditor) && isVertical) return true;\n\n // Arrow Up/Down while a row is in edit mode (row mode): the editor owns\n // the key. The grid does NOT commit + jump to an adjacent row — the user\n // must explicitly leave edit mode (Enter / Escape / Tab / click) before\n // arrow keys resume cell navigation. Rationale:\n // - <input type=\"number\"> spinners must work natively\n // - <select> / native popups need ArrowUp/Down to traverse options\n // - <textarea> needs ArrowUp/Down to move the caret between lines\n // - Framework-adapter editors (Angular Material, MUI, etc.) commonly\n // bind ArrowUp/Down for autocomplete, datepicker, number-stepper,\n // and combobox interactions\n // Returning `true` blocks the core keyboard handler from running its\n // commit-and-navigate fallback (see `core/internal/keyboard.ts`'s\n // ArrowUp/Down switch case). The native event still reaches the focused\n // editor so it can consume it however it needs to.\n if (isVertical && this.#activeEditRow !== -1 && !this.#isGridMode) return true;\n\n return false;\n }\n\n /** Tab/Shift+Tab while editing: move to the next/previous editable cell. */\n #onTabKey(event: KeyboardEvent): boolean {\n if (this.#activeEditRow === -1 && !this.#isGridMode) return false;\n\n event.preventDefault();\n\n // In single-cell edit mode (F2), commit and close instead of navigating\n if (this.#singleCellEdit) {\n this.#exitRowEdit(this.#activeEditRow, false);\n return true;\n }\n\n this.#handleTabNavigation(!event.shiftKey);\n return true;\n }\n\n /** Space: toggle boolean cells (only when not editing — editors own their own space). */\n #onSpaceKey(event: KeyboardEvent): boolean {\n // If we're in row edit mode, let the event pass through to the editor (e.g., checkbox)\n if (this.#activeEditRow !== -1) return false;\n\n const internalGrid = this.#internalGrid;\n const focusRow = internalGrid._focusRow;\n const focusCol = internalGrid._focusCol;\n if (focusRow < 0 || focusCol < 0) return false;\n\n const column = internalGrid._visibleColumns[focusCol];\n const rowData = internalGrid._rows[focusRow];\n if (!column || !rowData || column.type !== 'boolean') return false;\n if (!this.#isCellEditable(column as ColumnConfig<T>, rowData as T)) return false;\n\n const field = column.field;\n // Space on a cell we cannot safely write - don't block keyboard navigation\n if (!isSafePropertyKey(field)) return false;\n\n this.#commitCellValue(focusRow, column, !readCellField(rowData, field), rowData);\n event.preventDefault();\n // Re-render to update the UI\n this.requestRender();\n return true;\n }\n\n /** Enter (unmodified): start row edit, commit, or enter edit mode in grid mode. */\n #onEnterKey(event: KeyboardEvent): boolean {\n // In grid mode when not editing: focus the current cell's input\n if (this.#isGridMode && !this.#gridModeInputFocused) {\n this.#focusCurrentCellEditor();\n return true;\n }\n\n if (this.#isGridMode && this.#gridModeInputFocused) return this.#onEnterWhileEditorFocused(event);\n\n if (this.#activeEditRow !== -1) {\n // ARIA-expanded fallback (#251): when the focused control declares\n // an open overlay via aria-expanded=\"true\" + aria-controls, defer\n // Enter to the overlay so combobox confirmation does not exit the\n // row. Mirrors the editor-injection.ts handler so the same guard\n // applies whether the editor host or the grid receives the event.\n const ariaTarget = event.target as HTMLElement | null;\n if (\n ariaTarget &&\n ariaTarget.getAttribute?.('aria-expanded') === 'true' &&\n ariaTarget.hasAttribute?.('aria-controls')\n ) {\n return false;\n }\n if (shouldPreventEditClose(this.config, event)) return true;\n // Already editing - let cell handlers deal with it\n return false;\n }\n\n return this.#beginRowEditFromEnter(event);\n }\n\n /**\n * Enter in grid mode while an editor (or its descendant — most notably an\n * `<option>` inside an open native `<select>` popup) has focus. Does NOT start\n * row-based editing or re-render. Two sub-cases:\n * - target is a **descendant** of an editor (popup option): let the browser's\n * native commit-and-close run untouched — calling `beginBulkEdit` /\n * re-rendering would destroy the open popup and abort the commit.\n * - target **is** the editor itself (focused SELECT after popup closed,\n * focused INPUT with no popup): commit the current value, blur the editor,\n * return focus to the grid so arrow keys resume cell navigation. Mirrors\n * Escape but accepts the value instead of reverting.\n */\n #onEnterWhileEditorFocused(event: KeyboardEvent): boolean {\n const enterEditorAncestor = getEditorAncestor(event.target);\n if (enterEditorAncestor && enterEditorAncestor !== event.target) {\n // Descendant — let native commit fire; do not interfere. Return true so\n // core's Enter handler (which would dispatch cell-activate) does not also\n // run. We don't call preventDefault, so the browser still commits the popup.\n return true;\n }\n // Editor itself — commit + blur + return to navigation mode.\n this.#gridModeCellSnapshot = null;\n const activeEl = document.activeElement as HTMLElement | null;\n if (activeEl && this.gridElement.contains(activeEl)) {\n activeEl.blur();\n this.gridElement.focus();\n }\n this.#gridModeInputFocused = false;\n this.#gridModeEditLocked = true;\n this.requestAfterRender();\n return true;\n }\n\n /**\n * Enter on a focused cell with no edit in progress: start row-based editing\n * (not just the focused cell), after giving consumers a cancelable\n * `cell-activate` event.\n */\n #beginRowEditFromEnter(event: KeyboardEvent): boolean {\n const internalGrid = this.#internalGrid;\n const editOn = this.config.editOn ?? internalGrid.effectiveConfig?.editOn;\n if (editOn === false || editOn === 'manual') return false;\n\n const focusRow = internalGrid._focusRow;\n const focusCol = internalGrid._focusCol;\n if (focusRow < 0) return false;\n\n // Check if ANY column in the row is potentially editable\n const hasEditableColumn = internalGrid._columns?.some((col) => this.#hasEditableConfig(col as ColumnConfig<T>));\n // Row-level gate. No editable columns - don't block keyboard navigation.\n const row = internalGrid._rows[focusRow];\n if (!hasEditableColumn || !this.#isRowEditable(row as T | undefined)) return false;\n\n // Emit cell-activate event BEFORE starting edit\n // This ensures consumers always get the activation event\n const column = internalGrid._visibleColumns[focusCol];\n const field = column?.field ?? '';\n const value = field && row ? readCellField(row, field) : undefined;\n const cellEl = this.gridElement.querySelector(`[data-row=\"${focusRow}\"][data-col=\"${focusCol}\"]`) as\n HTMLElement | undefined;\n\n const activateEvent = new CustomEvent('cell-activate', {\n cancelable: true,\n bubbles: true,\n detail: {\n rowIndex: focusRow,\n colIndex: focusCol,\n field,\n value,\n row,\n cellEl,\n trigger: 'keyboard' as const,\n originalEvent: event,\n },\n });\n this.gridElement.dispatchEvent(activateEvent);\n\n // If consumer canceled the activation, don't start editing\n if (activateEvent.defaultPrevented) {\n event.preventDefault();\n return true;\n }\n\n this.beginBulkEdit(focusRow);\n return true;\n }\n\n /** F2: begin single-cell edit on the focused cell. */\n #onF2Key(event: KeyboardEvent): boolean {\n if (this.#activeEditRow !== -1 || this.#isGridMode) return false;\n\n const internalGrid = this.#internalGrid;\n const editOn = this.config.editOn ?? internalGrid.effectiveConfig?.editOn;\n if (editOn === false) return false;\n\n const focusRow = internalGrid._focusRow;\n const focusCol = internalGrid._focusCol;\n if (focusRow < 0 || focusCol < 0) return false;\n\n const column = internalGrid._visibleColumns[focusCol];\n const rowData = internalGrid._rows[focusRow];\n if (!column || !rowData || !column.field) return false;\n if (!this.#isCellEditable(column as ColumnConfig<T>, rowData as T)) return false;\n\n event.preventDefault();\n this.beginCellEdit(focusRow, column.field);\n return true;\n }\n\n // #endregion\n\n // #region Render Hooks\n\n /**\n * Parse `data-*` attributes from a `<tbw-grid-type>` element into a camelCased map.\n */\n #readTypeParams(typeEl: HTMLElement): Record<string, unknown> {\n const params: Record<string, unknown> = {};\n for (const attr of Array.from(typeEl.attributes)) {\n if (!attr.name.startsWith('data-')) continue;\n const key = attr.name\n .slice(5)\n .replace(/-([a-z])/g, (_m, letter: string) => letter.toUpperCase())\n .trim();\n if (!key) continue;\n params[key] = attr.value;\n }\n return params;\n }\n\n /**\n * Seed type-level editor defaults from declarative `<tbw-grid-type>` light-DOM.\n *\n * This mirrors the column-level `<tbw-grid-column-editor>` behavior: editor\n * templates are editing-plugin-owned and only become active when the editing\n * plugin is imported.\n */\n #seedTypeEditorsFromLightDom(): void {\n const internalGrid = this.#internalGrid;\n const host = internalGrid._hostElement;\n if (!host) return;\n\n const effectiveConfig = internalGrid.effectiveConfig;\n if (!effectiveConfig) return;\n\n const typeElements = Array.from(host.children).filter((el) => el.tagName.toLowerCase() === 'tbw-grid-type');\n if (!typeElements.length) return;\n\n const adapter = internalGrid.__frameworkAdapter;\n const typeDefaults = (effectiveConfig.typeDefaults ??= {});\n\n for (let i = 0; i < typeElements.length; i++) {\n const typeEl = typeElements[i] as HTMLElement;\n const name = typeEl.getAttribute('name')?.trim();\n if (!name) continue;\n\n const existing = typeDefaults[name];\n // Programmatic (or already-seeded) editor always wins.\n if (existing?.editor) continue;\n\n const editorTpl = typeEl.querySelector('tbw-grid-column-editor') as HTMLElement | null;\n const editorTarget = (editorTpl ?? typeEl) as HTMLElement;\n\n let editor: TypeDefault<T>['editor'] | undefined = adapter?.canHandle?.(editorTarget)\n ? (adapter.createEditor?.(editorTarget) as TypeDefault<T>['editor'] | undefined)\n : undefined;\n\n if (!editor && editorTpl) {\n const params = this.#readTypeParams(typeEl);\n const compiled = compileTemplate(editorTpl.innerHTML);\n editor = ((ctx) =>\n compiled({\n row: ctx.row as T,\n value: ctx.value,\n field: ctx.field,\n column: ctx.column as ColumnInternal<T>,\n typeDefault: params,\n })) as TypeDefault<T>['editor'];\n }\n\n if (!editor) continue;\n\n typeDefaults[name] = { ...(existing ?? {}), editor };\n }\n }\n\n /**\n * Process columns to merge type-level editorParams with column-level and to\n * read editing-owned attributes from declarative `<tbw-grid-column>` markup.\n *\n * Column-level params take precedence over type-level. Editing-owned\n * attributes (`editable`, `<tbw-grid-column-editor>` template) are parsed\n * here from `col.__element` rather than in core, so the grid carries no\n * editing knowledge (issue #272).\n * @internal\n */\n override processColumns(columns: ColumnConfig<T>[]): ColumnConfig<T>[] {\n const internalGrid = this.#internalGrid;\n this.#seedTypeEditorsFromLightDom();\n const typeDefaults = (internalGrid as any).effectiveConfig?.typeDefaults;\n const adapter = internalGrid.__frameworkAdapter;\n const hasTypeDefaults = !!typeDefaults || !!adapter?.getTypeDefault;\n\n return columns.map((col) => {\n // Read editing-owned attributes from the originating light-DOM element.\n // Each element is seeded at most once: the attribute supplies the INITIAL\n // value only, so config and later runtime changes always win and are not\n // overridden by re-reading the attribute on subsequent passes (#272).\n const el = (col as ColumnInternal<T>).__element;\n if (el && !this.#seededFromAttr.has(el)) {\n this.#seededFromAttr.add(el);\n // `col.editable == null` lets a programmatic config value (including an\n // explicit `editable: false`) win over the attribute on this first pass.\n if (col.editable == null && el.hasAttribute('editable')) {\n col.editable = el.getAttribute('editable') !== 'false';\n }\n const internalCol = col as ColumnInternal<T>;\n if (!internalCol.__editorTemplate) {\n const editorTpl = el.querySelector('tbw-grid-column-editor');\n if (editorTpl) internalCol.__editorTemplate = editorTpl as HTMLElement;\n }\n }\n\n if (!col.type || !hasTypeDefaults) return col;\n\n // Get type-level editorParams\n let typeEditorParams: Record<string, unknown> | undefined;\n\n // Check grid-level typeDefaults first\n if (typeDefaults?.[col.type]?.editorParams) {\n typeEditorParams = typeDefaults[col.type].editorParams;\n }\n\n // Then check app-level (adapter) typeDefaults\n if (!typeEditorParams && adapter?.getTypeDefault) {\n const appDefault = adapter.getTypeDefault<T>(col.type, internalGrid._hostElement);\n if (appDefault?.editorParams) {\n typeEditorParams = appDefault.editorParams;\n }\n }\n\n // No type-level params to merge\n if (!typeEditorParams) return col;\n\n // Merge: type-level as base, column-level wins on conflicts\n return {\n ...col,\n editorParams: { ...typeEditorParams, ...col.editorParams },\n };\n });\n }\n\n /**\n * Stabilize the actively edited row across `rows` array replacements and\n * capture dirty tracking baselines.\n *\n * **Editing stability:** When the consumer reassigns `grid.rows` while\n * editing, the full pipeline (sort, filter, group) runs on the new data.\n * This hook finds the edited row in the new array by ID and swaps in the\n * in-progress row reference (`#activeEditRowRef`) so editors survive.\n *\n * **Dirty tracking baselines:** When `dirtyTracking` is enabled, captures\n * a `structuredClone` snapshot of each row on first appearance\n * (first-write-wins). This prevents Angular's feedback loop from\n * overwriting baselines.\n *\n * @internal Plugin API — part of the render pipeline\n */\n override processRows(rows: readonly T[]): T[] {\n const internalGrid = this.#internalGrid;\n\n // --- Dirty tracking: capture baselines (first-write-wins) ---\n if (this.config.dirtyTracking && internalGrid.getRowId) {\n this.#dirty.capture(rows, (r) => {\n try {\n return internalGrid.getRowId?.(r);\n } catch {\n return undefined;\n }\n });\n }\n\n // --- Editing stability: swap in the in-progress row ---\n if (this.#activeEditRow === -1 || this.#isGridMode) return rows as T[];\n\n const editRowId = this.#activeEditRowId;\n const editRowRef = this.#activeEditRowRef;\n\n // Without a stable row ID we cannot match across array replacements\n if (!editRowId || !editRowRef) return rows as T[];\n\n const result = [...rows] as T[];\n\n // Find the edited row's new position by ID\n let newIndex = -1;\n for (let i = 0; i < result.length; i++) {\n if (this.#safeGetRowId(result[i]) === editRowId) {\n newIndex = i;\n break;\n }\n }\n\n if (newIndex === -1) {\n // Row was deleted server-side — close the editor.\n // Cannot close synchronously during the processRows pipeline;\n // schedule for after the current render cycle completes.\n setTimeout(() => this.cancelActiveRowEdit(), 0);\n return result;\n }\n\n // Swap in the in-progress row data to preserve editor state\n result[newIndex] = editRowRef;\n\n // Update index-keyed state if the position changed (due to sort/filter)\n if (this.#activeEditRow !== newIndex) {\n this.#migrateEditRowIndex(this.#activeEditRow, newIndex);\n }\n\n return result;\n }\n\n /**\n * After render, reapply editors to cells in edit mode.\n * This handles virtualization - when a row scrolls back into view,\n * we need to re-inject the editor.\n * @internal\n */\n override afterRender(): void {\n const internalGrid = this.#internalGrid;\n\n // --- Editing stability: verify active edit row index ---\n // After processRows, subsequent plugins (filtering, grouping) may have\n // shifted row indices. Verify the index is still correct and fix if needed\n // before re-injecting editors.\n if (this.#activeEditRow !== -1 && this.#activeEditRowRef && !this.#isGridMode) {\n if (internalGrid._rows[this.#activeEditRow] !== this.#activeEditRowRef) {\n const newIndex = (internalGrid._rows as T[]).indexOf(this.#activeEditRowRef);\n if (newIndex !== -1) {\n this.#migrateEditRowIndex(this.#activeEditRow, newIndex);\n } else {\n // Row no longer in rendered set (filtered out or deleted)\n setTimeout(() => this.cancelActiveRowEdit(), 0);\n return;\n }\n }\n }\n\n // Restore focus after exiting edit mode\n if (this.#pendingFocusRestore) {\n this.#pendingFocusRestore = false;\n this.#restoreCellFocus(internalGrid);\n }\n\n // Animate the row after render completes (so the row element exists)\n if (this.#pendingRowAnimation !== -1) {\n const rowIndex = this.#pendingRowAnimation;\n this.#pendingRowAnimation = -1;\n internalGrid.animateRow?.(rowIndex, 'change');\n }\n\n // Emit baselines-captured event when new baselines were captured this cycle.\n // Emitted post-render so consumers can safely read grid.rows, query the DOM,\n // or call getOriginalRow() in their handler.\n const capturedCount = this.#dirty.drainCapturedFlag();\n if (capturedCount != null) {\n this.emit<BaselinesCapturedDetail>('baselines-captured', {\n count: capturedCount,\n });\n }\n\n // In 'grid' mode, editors are injected via afterCellRender hook during render\n if (this.#isGridMode) return;\n\n if (this.#editingCells.size === 0) return;\n\n // Re-inject editors for any editing cells that are visible\n for (const cellKey of this.#editingCells) {\n const [rowStr, colStr] = cellKey.split(':');\n const rowIndex = parseInt(rowStr, 10);\n const colIndex = parseInt(colStr, 10);\n\n const cellEl = this.#getCell(rowIndex, colIndex);\n if (!cellEl || cellEl.classList.contains('editing')) continue;\n\n // Cell is visible but not in editing mode - reinject editor\n const rowData = internalGrid._rows[rowIndex];\n const column = internalGrid._visibleColumns[colIndex];\n if (rowData && column) {\n this.#injectEditor(rowData, rowIndex, column, colIndex, cellEl, true);\n }\n }\n }\n\n /**\n * Hook called after each cell is rendered.\n * In grid mode, injects editors into editable cells during render (no DOM queries needed).\n * @internal\n */\n override afterCellRender(context: AfterCellRenderContext): void {\n const { row, rowIndex, column, colIndex, cellElement } = context;\n\n const editable = this.#isCellEditable(column as ColumnConfig<T>, row as T);\n\n // Set aria-readonly on non-editable cells so screen readers can distinguish\n if (!editable) {\n cellElement.setAttribute('aria-readonly', 'true');\n // In grid mode, tear down stale editors on cells that are no longer editable\n // (e.g., after virtualization recycles a row element for different row data)\n if (this.#isGridMode && cellElement.classList.contains('editing')) {\n cellElement.classList.remove('editing');\n const value = readCellField(row, (column as ColumnConfig<T>).field);\n cellElement.textContent = value == null ? '' : String(value);\n }\n } else {\n cellElement.removeAttribute('aria-readonly');\n }\n\n // Only inject editors in grid mode\n if (!this.#isGridMode) return;\n\n // Skip non-editable cells\n if (!editable) return;\n\n // Skip if already has editor\n if (cellElement.classList.contains('editing')) return;\n\n // Inject editor (don't track in editingCells - we're always editing in grid mode)\n // Pass rowElement so incrementEditingCount works even when cell is in a DocumentFragment\n this.#injectEditor(row as T, rowIndex, column as ColumnConfig<T>, colIndex, cellElement, true, context.rowElement);\n }\n\n /**\n * Apply dirty-tracking CSS classes to each rendered row.\n *\n * - `tbw-cell-dirty` on individual cells whose value differs from baseline\n * (applied on cell-commit, visible during editing)\n * - `tbw-row-dirty` on the row element only after the row edit session is\n * committed (edit-close without cancel)\n * - `tbw-row-new` when a row was inserted via `insertRow()` with no baseline\n *\n * Only active when `dirtyTracking: true`.\n *\n * @internal Plugin API\n */\n override afterRowRender(context: AfterRowRenderContext): void {\n if (!this.config.dirtyTracking) return;\n\n const internalGrid = this.#internalGrid;\n const rowId = internalGrid.getRowId?.(context.row as T);\n if (!rowId) return;\n\n const { isNew, isCommittedDirty, hasBaseline } = this.#dirty.getRowDirtyState(rowId, context.row as T);\n\n const el = context.rowElement;\n\n // Row-level classes (tbw-row-dirty only after row-commit AND data differs)\n el.classList.toggle('tbw-row-dirty', isCommittedDirty);\n el.classList.toggle('tbw-row-new', isNew);\n\n // Cell-level classes (tbw-cell-dirty on individual cells with changed values)\n // Only run the per-cell loop when the row has a baseline — avoids\n // querySelectorAll on the hot path for rows without dirty tracking state.\n if (hasBaseline) {\n const cells = el.querySelectorAll('.cell[data-field]');\n for (let i = 0; i < cells.length; i++) {\n const cell = cells[i] as HTMLElement;\n const field = cell.getAttribute('data-field');\n if (field) {\n cell.classList.toggle('tbw-cell-dirty', this.#dirty.isCellDirty(rowId, context.row as T, field));\n }\n }\n } else {\n // Clean up stale tbw-cell-dirty classes on recycled row elements\n // that previously displayed a dirty row but now show a pristine one.\n const dirtyCells = el.querySelectorAll('.tbw-cell-dirty');\n for (let i = 0; i < dirtyCells.length; i++) {\n dirtyCells[i].classList.remove('tbw-cell-dirty');\n }\n }\n }\n\n /**\n * On scroll render, reapply editors to recycled cells.\n * @internal\n */\n override onScrollRender(): void {\n this.afterRender();\n }\n\n // #endregion\n\n // #region Public API\n\n /**\n * Get all rows that have been modified.\n * Uses ID-based lookup for stability when rows are reordered.\n */\n get changedRows(): T[] {\n return this.#dirty.getChangedRows((id) => this.grid.getRow(id) as T | undefined);\n }\n\n /**\n * Get IDs of all modified rows.\n */\n get changedRowIds(): string[] {\n return this.#dirty.getChangedRowIds();\n }\n\n /**\n * Get the currently active edit row index, or -1 if not editing.\n */\n get activeEditRow(): number {\n return this.#activeEditRow;\n }\n\n /**\n * Get the currently active edit column index, or -1 if not editing.\n */\n get activeEditCol(): number {\n return this.#activeEditCol;\n }\n\n /**\n * Check if a specific row is currently being edited.\n */\n isRowEditing(rowIndex: number): boolean {\n return this.#activeEditRow === rowIndex;\n }\n\n /**\n * Check if a specific cell is currently being edited.\n */\n isCellEditing(rowIndex: number, colIndex: number): boolean {\n return this.#editingCells.has(`${rowIndex}:${colIndex}`);\n }\n\n /**\n * Check if a specific row has been modified.\n * @param rowIndex - Row index to check (will be converted to ID internally)\n */\n isRowChanged(rowIndex: number): boolean {\n const internalGrid = this.#internalGrid;\n const row = internalGrid._rows[rowIndex];\n if (!row) return false;\n try {\n const rowId = internalGrid.getRowId?.(row);\n return rowId ? this.#dirty.isRowChanged(rowId) : false;\n } catch {\n return false;\n }\n }\n\n /**\n * Check if a row with the given ID has been modified.\n * @param rowId - Row ID to check\n */\n isRowChangedById(rowId: string): boolean {\n return this.#dirty.isRowChanged(rowId);\n }\n\n // #region Dirty Tracking API (delegated to DirtyTrackingManager)\n\n /** Check if a row differs from its baseline. Requires `dirtyTracking: true`. */\n isDirty(rowId: string): boolean {\n if (!this.config.dirtyTracking) return false;\n if (this.#dirty.newRowIds.has(rowId)) return true;\n const row = this.grid.getRow(rowId) as T | undefined;\n if (!row) return false;\n return this.#dirty.isRowDirty(rowId, row);\n }\n\n /** Inverse of `isDirty`. */\n isPristine(rowId: string): boolean {\n return !this.isDirty(rowId);\n }\n\n /** Whether any row in the grid is dirty. */\n get dirty(): boolean {\n if (!this.config.dirtyTracking) return false;\n const internalGrid = this.#internalGrid;\n return this.#dirty.hasAnyDirty((rowId) => internalGrid._getRowEntry(rowId)?.row as T | undefined);\n }\n\n /** Whether all rows are pristine. */\n get pristine(): boolean {\n return !this.dirty;\n }\n\n /** Re-snapshot baseline from current data (call after a successful save). */\n markAsPristine(rowId: string): void {\n if (!this.config.dirtyTracking) return;\n const row = this.grid.getRow(rowId) as T | undefined;\n if (!row) return;\n this.#dirty.markPristine(rowId, row);\n // After mark-pristine, original === current — emit row as the canonical value.\n this.emit<DirtyChangeDetail<T>>('dirty-change', {\n rowId,\n row,\n original: row,\n type: 'pristine',\n });\n }\n\n /** Mark a row as new (auto-called by `insertRow()` when dirty tracking is on). */\n markAsNew(rowId: string): void {\n if (!this.config.dirtyTracking) return;\n this.#dirty.markNew(rowId);\n const row = this.grid.getRow(rowId) as T | undefined;\n // `original` is intentionally undefined for new rows — emit directly\n // rather than via #emitDirtyChange (which always derives original from\n // the baseline map).\n this.emit<DirtyChangeDetail<T>>('dirty-change', {\n rowId,\n row: row as T,\n original: undefined,\n type: 'new',\n });\n }\n\n /** Mark a row as dirty after an external mutation that bypassed the editing pipeline. */\n markAsDirty(rowId: string): void {\n if (!this.config.dirtyTracking) return;\n const row = this.grid.getRow(rowId) as T | undefined;\n if (!row) return;\n this.#dirty.markDirty(rowId);\n this.#emitDirtyChange(rowId, row, 'modified');\n }\n\n /** Mark all tracked rows as pristine (call after a batch save). */\n markAllPristine(): void {\n if (!this.config.dirtyTracking) return;\n const internalGrid = this.#internalGrid;\n this.#dirty.markAllPristine((rowId) => internalGrid._getRowEntry(rowId)?.row as T | undefined);\n }\n\n /** Get a deep clone of the original (baseline) row data. Returns `undefined` for new rows. */\n getOriginalRow(rowId: string): T | undefined {\n if (!this.config.dirtyTracking) return undefined;\n return this.#dirty.getOriginalRow(rowId);\n }\n\n /** Lightweight check for whether a baseline exists (no cloning). */\n hasBaseline(rowId: string): boolean {\n if (!this.config.dirtyTracking) return false;\n return this.#dirty.hasBaseline(rowId);\n }\n\n /** Get all dirty rows with their original and current data. */\n getDirtyRows(): DirtyRowEntry<T>[] {\n if (!this.config.dirtyTracking) return [];\n const internalGrid = this.#internalGrid;\n return this.#dirty.getDirtyRows((rowId) => internalGrid._getRowEntry(rowId)?.row as T | undefined);\n }\n\n /**\n * Get IDs of all dirty rows.\n */\n get dirtyRowIds(): string[] {\n if (!this.config.dirtyTracking) return [];\n const internalGrid = this.#internalGrid;\n return this.#dirty.getDirtyRowIds((rowId) => internalGrid._getRowEntry(rowId)?.row as T | undefined);\n }\n\n /**\n * Revert a row to its baseline values (mutates the current row in-place).\n * Triggers a re-render.\n *\n * @param rowId - Row ID (from `getRowId`)\n */\n revertRow(rowId: string): void {\n if (!this.config.dirtyTracking) return;\n const row = this.grid.getRow(rowId) as T | undefined;\n if (!row) return;\n if (this.#dirty.revertRow(rowId, row)) {\n this.#emitDirtyChange(rowId, row, 'reverted');\n this.requestRender();\n }\n }\n\n /**\n * Revert all dirty rows to their baseline values and re-render.\n */\n revertAll(): void {\n if (!this.config.dirtyTracking) return;\n const internalGrid = this.#internalGrid;\n this.#dirty.revertAll((rowId) => internalGrid._getRowEntry(rowId)?.row as T | undefined);\n this.requestRender();\n }\n\n // #endregion\n\n // #region Cell Validation (delegated to CellValidationManager)\n\n /**\n * Mark a cell as invalid with an optional validation message.\n * Invalid cells are marked with a `data-invalid` attribute for styling.\n *\n * @param rowId - The row ID (from getRowId)\n * @param field - The field name\n * @param message - Optional validation message (for tooltips or display)\n *\n * @example\n * ```typescript\n * // In cell-commit handler:\n * grid.on('cell-commit', (detail, e) => {\n * if (detail.field === 'email' && !isValidEmail(detail.value)) {\n * detail.setInvalid('Invalid email format');\n * }\n * });\n *\n * // Or programmatically:\n * editingPlugin.setInvalid('row-123', 'email', 'Invalid email format');\n * ```\n */\n setInvalid(rowId: string, field: string, message = ''): void {\n this.#validation.setInvalid(rowId, field, message);\n }\n\n /** Clear the invalid state for a specific cell. */\n clearInvalid(rowId: string, field: string): void {\n this.#validation.clearInvalid(rowId, field);\n }\n\n /** Clear all invalid cells for a specific row. */\n clearRowInvalid(rowId: string): void {\n this.#validation.clearRowInvalid(rowId);\n }\n\n /** Clear all invalid cell states across all rows. */\n clearAllInvalid(): void {\n this.#validation.clearAllInvalid();\n }\n\n /** Check if a specific cell is marked as invalid. */\n isCellInvalid(rowId: string, field: string): boolean {\n return this.#validation.isCellInvalid(rowId, field);\n }\n\n /** Get the validation message for an invalid cell. */\n getInvalidMessage(rowId: string, field: string): string | undefined {\n return this.#validation.getInvalidMessage(rowId, field);\n }\n\n /** Check if a row has any invalid cells. */\n hasInvalidCells(rowId: string): boolean {\n return this.#validation.hasInvalidCells(rowId);\n }\n\n /** Get all invalid fields for a row. */\n getInvalidFields(rowId: string): Map<string, string> {\n return this.#validation.getInvalidFields(rowId);\n }\n\n // #endregion\n\n /**\n * Reset all change tracking.\n * @param silent - If true, suppresses the `changed-rows-reset` event\n * @fires changed-rows-reset - Emitted when tracking is reset (unless silent)\n */\n resetChangedRows(silent?: boolean): void {\n const rows = this.changedRows;\n const ids = this.changedRowIds;\n this.#dirty.changedRowIds.clear();\n this.#dirty.committedDirtyRowIds.clear();\n this.#syncGridEditState();\n\n if (!silent) {\n this.emit<ChangedRowsResetDetail<T>>('changed-rows-reset', { rows, ids });\n }\n\n // Clear visual indicators\n const internalGrid = this.#internalGrid;\n internalGrid._rowPool?.forEach((r) => r.classList.remove('changed'));\n }\n\n /**\n * Programmatically begin editing a cell.\n * @param rowIndex - Index of the row to edit\n * @param field - Field name of the column to edit\n * @fires cell-commit - Emitted when the cell value is committed (on blur or Enter)\n */\n beginCellEdit(rowIndex: number, field: string): void {\n const internalGrid = this.#internalGrid;\n const colIndex = internalGrid._visibleColumns.findIndex((c) => c.field === field);\n if (colIndex === -1) return;\n\n const column = internalGrid._visibleColumns[colIndex];\n const rowData = internalGrid._rows[rowIndex];\n if (!column || !rowData || !this.#isCellEditable(column as ColumnConfig<T>, rowData as T)) return;\n\n const cellEl = this.#getCell(rowIndex, colIndex);\n if (!cellEl) return;\n\n this.#singleCellEdit = true;\n this.#beginCellEdit(rowIndex, colIndex, cellEl);\n }\n\n /**\n * Programmatically begin editing all editable cells in a row.\n * @param rowIndex - Index of the row to edit\n * @fires cell-commit - Emitted for each cell value that is committed\n * @fires row-commit - Emitted when focus leaves the row\n */\n beginBulkEdit(rowIndex: number): void {\n const internalGrid = this.#internalGrid;\n const editOn = this.config.editOn ?? internalGrid.effectiveConfig?.editOn;\n if (editOn === false) return;\n\n const hasEditableColumn = internalGrid._columns?.some((col) => this.#hasEditableConfig(col as ColumnConfig<T>));\n if (!hasEditableColumn) return;\n\n const rowEl = internalGrid.findRenderedRowElement?.(rowIndex);\n if (!rowEl) return;\n\n // Row-level gate\n const rowData = internalGrid._rows[rowIndex];\n if (!this.#isRowEditable(rowData as T | undefined)) return;\n\n // Bulk edit clears single-cell mode\n this.#singleCellEdit = false;\n\n // Start row edit\n this.#startRowEdit(rowIndex, rowData);\n\n // Enter edit mode on all editable cells\n Array.from(rowEl.children).forEach((cell, i) => {\n const col = internalGrid._visibleColumns[i];\n if (col && this.#isCellEditable(col as ColumnConfig<T>, rowData as T)) {\n const cellEl = cell as HTMLElement;\n if (!cellEl.classList.contains('editing')) {\n this.#injectEditor(rowData, rowIndex, col, i, cellEl, true);\n }\n }\n });\n\n // Focus the first editable cell\n setTimeout(() => {\n let targetCell = rowEl.querySelector(`.cell[data-col=\"${internalGrid._focusCol}\"]`);\n if (!targetCell?.classList.contains('editing')) {\n targetCell = rowEl.querySelector('.cell.editing');\n }\n if (targetCell?.classList.contains('editing')) {\n const editor = (targetCell as HTMLElement).querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n try {\n editor?.focus({ preventScroll: true });\n } catch {\n /* empty */\n }\n }\n }, 0);\n }\n\n /**\n * Commit the currently active row edit.\n * @fires row-commit - Emitted after the row edit is committed\n */\n commitActiveRowEdit(): void {\n if (this.#activeEditRow !== -1) {\n this.#exitRowEdit(this.#activeEditRow, false);\n }\n }\n\n /**\n * Cancel the currently active row edit.\n */\n cancelActiveRowEdit(): void {\n if (this.#activeEditRow !== -1) {\n this.#exitRowEdit(this.#activeEditRow, true);\n }\n }\n\n // #endregion\n\n // #region Internal Methods\n\n // --- Small private helpers (centralised to keep call sites uniform) ---\n\n /**\n * Safely resolve a row's ID via the configured `getRowId`. Returns\n * `undefined` when no ID can be derived (no `getRowId` callback, or it\n * threw — e.g. row has no key).\n */\n #safeGetRowId(row: T | undefined | null): string | undefined {\n if (!row) return undefined;\n try {\n return this.#internalGrid.getRowId?.(row);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Resolve a rendered cell element by row + column index. Returns `null`\n * when the row is not currently rendered or the cell is missing.\n */\n #getCell(rowIndex: number, colIndex: number): HTMLElement | null {\n const rowEl = this.#internalGrid.findRenderedRowElement?.(rowIndex);\n return (rowEl?.querySelector(`.cell[data-col=\"${colIndex}\"]`) as HTMLElement | null) ?? null;\n }\n\n /**\n * Row-level editability gate. Returns `false` only when\n * `gridConfig.rowEditable` is configured AND vetoes the row. Rows without\n * data return `true` (defer to the column-level check).\n */\n #isRowEditable(rowData: T | undefined): boolean {\n if (!rowData) return true;\n const rowEditable = this.#internalGrid.effectiveConfig?.rowEditable;\n if (!rowEditable) return true;\n return rowEditable(rowData as any) !== false;\n }\n\n /**\n * Emit a `dirty-change` event with the canonical `{ rowId, row, original, type }`\n * shape. Centralises baseline lookup so every emit site uses the same\n * source of truth.\n */\n #emitDirtyChange(rowId: string, row: T | undefined, type: DirtyChangeDetail<T>['type']): void {\n this.emit<DirtyChangeDetail<T>>('dirty-change', {\n rowId,\n row: row as T,\n original: this.#dirty.getOriginalRow(rowId),\n type,\n });\n }\n\n /**\n * Grid-mode \"Escape → navigation mode\" transition: revert the cell from\n * the focus snapshot, blur the active editor, return focus to the grid,\n * and flip the navigation/lock flags. Used by the capture-phase Escape\n * handler (both deferred and sync branches) and the bubble-phase Escape\n * handler in `onKeyDown`.\n */\n #enterGridModeNavigation(): void {\n this.#revertGridModeCellEdit();\n const activeEl = document.activeElement as HTMLElement | null;\n if (activeEl && this.gridElement.contains(activeEl)) {\n activeEl.blur();\n this.gridElement.focus();\n }\n this.#gridModeInputFocused = false;\n this.#gridModeEditLocked = true;\n }\n\n /**\n * Restore a row to its snapshot values and clear all per-row dirty\n * bookkeeping. Called both from the explicit-revert path and from the\n * `row-commit` cancellation path in `#exitRowEdit`.\n */\n #revertRowFromSnapshot(rowId: string | undefined, current: T, snapshot: T | undefined): void {\n if (!snapshot) return;\n Object.keys(snapshot as object).forEach((k) => {\n (current as Record<string, unknown>)[k] = (snapshot as Record<string, unknown>)[k];\n });\n if (rowId) {\n this.#dirty.changedRowIds.delete(rowId);\n this.#dirty.committedDirtyRowIds.delete(rowId);\n this.clearRowInvalid(rowId);\n }\n }\n\n /**\n * Sync the data-invalid attribute on a cell element.\n * Used as the DOM callback for CellValidationManager.\n */\n #syncInvalidCellAttribute(rowId: string, field: string, invalid: boolean): void {\n const internalGrid = this.#internalGrid;\n const colIndex = internalGrid._visibleColumns?.findIndex((c) => c.field === field);\n if (colIndex === -1 || colIndex === undefined) return;\n\n // Find the row element by rowId\n const rows = internalGrid._rows;\n const rowIndex = rows?.findIndex((r) => this.#safeGetRowId(r as T) === rowId);\n if (rowIndex === -1 || rowIndex === undefined) return;\n\n const cellEl = this.#getCell(rowIndex, colIndex);\n if (!cellEl) return;\n\n if (invalid) {\n cellEl.setAttribute('data-invalid', 'true');\n // `data-invalid` is styling only; `aria-invalid` is what actually reaches a\n // screen reader (SC 3.3.1 Error Identification).\n cellEl.setAttribute('aria-invalid', 'true');\n const message = this.#validation.getInvalidMessage(rowId, field);\n if (message) {\n cellEl.setAttribute('title', message);\n // Hand the title over: core would otherwise reclaim it as its own\n // truncation tooltip on the next hover and overwrite the message.\n cellEl.removeAttribute(GridDataAttrs.TRUNCATED);\n }\n } else {\n cellEl.removeAttribute('data-invalid');\n cellEl.removeAttribute('aria-invalid');\n cellEl.removeAttribute('title');\n }\n }\n\n /**\n * Migrate all index-keyed editing state when the active edit row moves to\n * a different position in `_rows` (e.g. after sort, filter, or new data push).\n *\n * Updates: `#activeEditRow`, `#editingCells`, `#rowEditSnapshots`,\n * `#editorValueCallbacks`, and syncs `_activeEditRows` on the grid.\n */\n #migrateEditRowIndex(oldIndex: number, newIndex: number): void {\n this.#activeEditRow = newIndex;\n\n // Migrate #editingCells keys (\"rowIndex:colIndex\")\n const migratedCells = new Set<string>();\n const prefix = `${oldIndex}:`;\n for (const cellKey of this.#editingCells) {\n if (cellKey.startsWith(prefix)) {\n migratedCells.add(`${newIndex}:${cellKey.substring(prefix.length)}`);\n } else {\n migratedCells.add(cellKey);\n }\n }\n this.#editingCells.clear();\n for (const key of migratedCells) {\n this.#editingCells.add(key);\n }\n\n // Migrate #rowEditSnapshots key\n const snapshot = this.#rowEditSnapshots.get(oldIndex);\n if (snapshot !== undefined) {\n this.#rowEditSnapshots.delete(oldIndex);\n this.#rowEditSnapshots.set(newIndex, snapshot);\n }\n\n // Migrate #editorValueCallbacks keys (\"rowIndex:field\")\n const updates: [string, (newValue: unknown) => void][] = [];\n for (const [key, cb] of this.#editorValueCallbacks) {\n if (key.startsWith(prefix)) {\n updates.push([`${newIndex}:${key.substring(prefix.length)}`, cb]);\n this.#editorValueCallbacks.delete(key);\n }\n }\n for (const [key, cb] of updates) {\n this.#editorValueCallbacks.set(key, cb);\n }\n\n // Sync the grid's rendering state so rows.ts checks the correct index\n this.#syncGridEditState();\n }\n\n /**\n * Begin editing a single cell.\n */\n #beginCellEdit(rowIndex: number, colIndex: number, cellEl: HTMLElement): void {\n const internalGrid = this.#internalGrid;\n const rowData = internalGrid._rows[rowIndex];\n const column = internalGrid._visibleColumns[colIndex];\n\n if (!rowData || !column || !this.#isCellEditable(column as ColumnConfig<T>, rowData as T)) return;\n if (cellEl.classList.contains('editing')) return;\n\n // Start row edit if not already\n if (this.#activeEditRow !== rowIndex) {\n this.#startRowEdit(rowIndex, rowData);\n }\n\n this.#activeEditCol = colIndex;\n this.#injectEditor(rowData, rowIndex, column, colIndex, cellEl, false);\n }\n\n /**\n * Revert the focused cell's value from the snapshot taken when the editor\n * first received focus, then emit a `cell-cancel` event so framework\n * adapters (e.g., GridFormArray) can revert their FormControls.\n *\n * Called by the grid-mode Escape handlers (both capture and bubble phase).\n */\n #revertGridModeCellEdit(): void {\n const snapshot = this.#gridModeCellSnapshot;\n if (!snapshot) return;\n\n const internalGrid = this.#internalGrid;\n const rowData = internalGrid._rows?.[snapshot.rowIndex];\n if (rowData) {\n writeCellField(rowData, snapshot.field, snapshot.value);\n }\n\n // Push the reverted value to the editor's input element so that the\n // subsequent blur-commit (triggered by activeEl.blur()) reads the\n // reverted value instead of the user's typed text. This makes the\n // blur-commit a no-op (oldValue === newValue) and prevents it from\n // overwriting the revert.\n const callbackKey = `${snapshot.rowIndex}:${snapshot.field}`;\n const cb = this.#editorValueCallbacks.get(callbackKey);\n if (cb) cb(snapshot.value);\n\n // Notify framework adapters to revert FormControls\n this.emit<CellCancelDetail>('cell-cancel', {\n rowIndex: snapshot.rowIndex,\n colIndex: snapshot.colIndex,\n field: snapshot.field,\n previousValue: snapshot.value,\n });\n\n // After reverting, clean up changedRowIds so the built-in `.changed` class\n // toggle in rows.ts doesn't fight with consumer's rowClass callback.\n // changedRowIds.add() is unconditional during commit, so cleanup must also\n // be unconditional — otherwise the Set retains stale IDs when dirtyTracking\n // is disabled and the built-in toggle re-adds `.changed` on every render.\n if (rowData) {\n const rowId = this.#safeGetRowId(rowData as T);\n if (rowId) {\n if (this.config.dirtyTracking) {\n // With dirty tracking, only remove if the row has no other dirty cells\n if (!this.#dirty.isRowDirty(rowId, rowData as T)) {\n this.#dirty.changedRowIds.delete(rowId);\n this.#emitDirtyChange(rowId, rowData as T, 'reverted');\n }\n } else {\n // Without dirty tracking there's no baseline to compare, so always\n // remove — the consumer manages their own change state via rowClass.\n this.#dirty.changedRowIds.delete(rowId);\n }\n }\n }\n\n // Always re-render after revert so rowClass callbacks re-evaluate\n // (e.g., consumer may toggle a 'changed' class based on local state\n // updated in response to the cell-cancel event above).\n this.requestRender();\n\n this.#gridModeCellSnapshot = null;\n }\n\n /**\n * Focus the editor input in the currently focused cell (grid mode only).\n * Used when pressing Enter to enter edit mode from navigation mode.\n */\n #focusCurrentCellEditor(): void {\n const internalGrid = this.#internalGrid;\n const focusRow = internalGrid._focusRow;\n const focusCol = internalGrid._focusCol;\n\n if (focusRow < 0 || focusCol < 0) return;\n\n const cellEl = this.#getCell(focusRow, focusCol);\n\n if (cellEl?.classList.contains('editing')) {\n const editor = cellEl.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n if (editor) {\n this.#gridModeEditLocked = false; // Unlock edit mode - user pressed Enter\n editor.focus();\n this.#gridModeInputFocused = true;\n // Select all text in text inputs for quick replacement\n if (editor instanceof HTMLInputElement && (editor.type === 'text' || editor.type === 'number')) {\n editor.select();\n }\n }\n }\n }\n\n /**\n * Handle Tab/Shift+Tab navigation while editing.\n * Moves to next/previous editable cell, staying in edit mode.\n * Wraps to next/previous row when reaching row boundaries.\n */\n #handleTabNavigation(forward: boolean): void {\n const internalGrid = this.#internalGrid;\n const rows = internalGrid._rows;\n // In grid mode, use focusRow since there's no active edit row\n const currentRow = this.#isGridMode ? internalGrid._focusRow : this.#activeEditRow;\n const currentRowData = rows[currentRow] as T;\n\n // Get editable column indices for the CURRENT row\n const editableCols = internalGrid._visibleColumns\n .map((c, i) => (currentRowData && this.#isCellEditable(c as ColumnConfig<T>, currentRowData) ? i : -1))\n .filter((i) => i >= 0);\n if (editableCols.length === 0) return;\n\n const currentIdx = editableCols.indexOf(internalGrid._focusCol);\n const nextIdx = currentIdx + (forward ? 1 : -1);\n\n // Can move within same row?\n if (nextIdx >= 0 && nextIdx < editableCols.length) {\n internalGrid._focusCol = editableCols[nextIdx];\n const cellEl = this.#getCell(currentRow, editableCols[nextIdx]);\n if (cellEl?.classList.contains('editing')) {\n const editor = cellEl.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n editor?.focus({ preventScroll: true });\n }\n ensureCellVisible(internalGrid, { forceHorizontalScroll: true });\n return;\n }\n\n // Can move to adjacent row?\n const nextRow = currentRow + (forward ? 1 : -1);\n if (nextRow >= 0 && nextRow < rows.length) {\n const nextRowData = rows[nextRow] as T;\n // Compute editable columns for the next row\n const nextEditableCols = internalGrid._visibleColumns\n .map((c, i) => (nextRowData && this.#isCellEditable(c as ColumnConfig<T>, nextRowData) ? i : -1))\n .filter((i) => i >= 0);\n if (nextEditableCols.length === 0) return; // Next row has no editable cells\n\n // In grid mode, just move focus (all rows are always editable)\n if (this.#isGridMode) {\n internalGrid._focusRow = nextRow;\n internalGrid._focusCol = forward ? nextEditableCols[0] : nextEditableCols[nextEditableCols.length - 1];\n ensureCellVisible(internalGrid, { forceHorizontalScroll: true });\n // Focus the editor in the new cell after render\n this.requestAfterRender();\n setTimeout(() => {\n const cellEl = this.#getCell(nextRow, internalGrid._focusCol);\n if (cellEl?.classList.contains('editing')) {\n const editor = cellEl.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n editor?.focus({ preventScroll: true });\n }\n }, 0);\n } else {\n // In row mode, commit current row and enter next row\n this.#exitRowEdit(currentRow, false);\n internalGrid._focusRow = nextRow;\n internalGrid._focusCol = forward ? nextEditableCols[0] : nextEditableCols[nextEditableCols.length - 1];\n this.beginBulkEdit(nextRow);\n ensureCellVisible(internalGrid, { forceHorizontalScroll: true });\n }\n }\n // else: at boundary - stay put\n }\n\n /**\n * Sync the internal grid state with the plugin's editing state.\n */\n #syncGridEditState(): void {\n const internalGrid = this.#internalGrid;\n internalGrid._activeEditRows = this.#activeEditRow;\n internalGrid._rowEditSnapshots = this.#rowEditSnapshots;\n }\n\n /**\n * Snapshot original row data and mark as editing.\n */\n #startRowEdit(rowIndex: number, rowData: T): void {\n if (this.#activeEditRow !== rowIndex) {\n // Commit the previous row before starting a new one\n if (this.#activeEditRow !== -1) {\n this.#exitRowEdit(this.#activeEditRow, false);\n }\n this.#rowEditSnapshots.set(rowIndex, { ...rowData });\n this.#activeEditRow = rowIndex;\n this.#activeEditRowRef = rowData;\n\n // Store stable row ID for resilience against _rows replacement during editing\n this.#activeEditRowId = this.#safeGetRowId(rowData);\n\n this.#syncGridEditState();\n\n // Broadcast edit-open so consumers (DOM listeners) AND other plugins\n // (notably SelectionPlugin via the plugin event bus) stay in sync with\n // the row currently being edited. Issue #284.\n // Row mode only — in grid mode every row is perpetually editable.\n if (!this.#isGridMode) {\n this.broadcast<EditOpenDetail<T>>('edit-open', {\n rowIndex,\n rowId: this.#activeEditRowId ?? '',\n row: rowData,\n });\n announce(this.gridElement, getA11yMessage(this.gridElement, 'editingStarted', rowIndex));\n }\n }\n }\n\n /**\n * Exit editing for a row.\n */\n #exitRowEdit(rowIndex: number, revert: boolean): void {\n if (this.#activeEditRow !== rowIndex) return;\n\n const internalGrid = this.#internalGrid;\n const snapshot = this.#rowEditSnapshots.get(rowIndex);\n const rowEl = internalGrid.findRenderedRowElement?.(rowIndex);\n const { rowId, current } = this.#resolveEditedRow(rowIndex);\n\n // Collect and commit values from active editors before re-rendering\n if (!revert && rowEl && current) {\n this.#commitActiveEditors(rowEl, rowIndex, current);\n }\n\n // Flush managed editors (framework adapters) before clearing state.\n // At this point the commit() callback is still active, so editors can\n // synchronously commit their pending values in response to this event.\n if (!revert && !this.#isGridMode && current) {\n this.emit<BeforeEditCloseDetail<T>>('before-edit-close', {\n rowIndex,\n rowId: rowId ?? '',\n row: current,\n });\n }\n\n // Revert if requested\n if (revert && current) {\n this.#revertRowFromSnapshot(rowId, current, snapshot);\n } else if (!revert && current) {\n this.#finalizeRowCommit(rowIndex, rowId, current, snapshot);\n }\n\n this.#clearRowEditState(rowIndex);\n\n // Mark that focus should be restored after the upcoming render completes.\n // This must be set BEFORE refreshVirtualWindow because it calls afterRender()\n // synchronously, which reads this flag.\n this.#pendingFocusRestore = true;\n\n // Re-render the row to remove editors\n if (rowEl) {\n this.#teardownRowEditors(rowEl, internalGrid);\n } else {\n // Row not visible - restore focus immediately (no render will happen)\n this.#restoreCellFocus(internalGrid);\n this.#pendingFocusRestore = false;\n }\n\n // Broadcast edit-close (row mode only, fires for both commit and revert)\n // so consumers AND other plugins receive it. Issue #284.\n if (!this.#isGridMode && current) {\n this.broadcast<EditCloseDetail<T>>('edit-close', {\n rowIndex,\n rowId: rowId ?? '',\n row: current,\n reverted: revert,\n });\n if (!revert) {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'editingCommitted', rowIndex));\n }\n }\n }\n\n /**\n * Resolve the row being edited using the stored row ID.\n *\n * The `_rows` array may have been replaced (e.g. Angular pushing new rows via\n * directive effect) since editing started, so `_rows[rowIndex]` could point to\n * a completely different row — the ID map is always up to date. Without an ID\n * we fall back to the row reference stored at edit-open (`#activeEditRowRef`),\n * which is safer than the possibly-stale `_rows[rowIndex]`.\n */\n #resolveEditedRow(rowIndex: number): { rowId: string | undefined; current: T | undefined } {\n const internalGrid = this.#internalGrid;\n let rowId = this.#activeEditRowId;\n const entry = rowId ? internalGrid._getRowEntry(rowId) : undefined;\n const current = entry?.row ?? this.#activeEditRowRef ?? internalGrid._rows[rowIndex];\n\n if (!rowId && current) {\n rowId = this.#safeGetRowId(current);\n }\n return { rowId, current };\n }\n\n /**\n * Read pending values out of every native editor in the row and commit the\n * ones that actually changed.\n */\n #commitActiveEditors(rowEl: HTMLElement, rowIndex: number, current: T): void {\n const internalGrid = this.#internalGrid;\n rowEl.querySelectorAll('.cell.editing').forEach((cell) => {\n const colIndex = Number((cell as HTMLElement).getAttribute('data-col'));\n if (isNaN(colIndex)) return;\n const col = internalGrid._visibleColumns[colIndex];\n if (!col) return;\n\n // Skip cells with externally-managed editors (framework adapters like Angular/React/Vue).\n // These editors handle their own commits via the commit() callback - we should NOT\n // try to read values from their DOM inputs (which may contain formatted display values).\n if ((cell as HTMLElement).hasAttribute('data-editor-managed')) return;\n\n const input = cell.querySelector('input,textarea,select') as\n HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null;\n if (!input) return;\n\n const field = col.field;\n const originalValue = readCellField(current, field) as T[keyof T];\n const val = getInputValue(input, col, originalValue);\n if (originalValue !== val) {\n this.#commitCellValue(rowIndex, col, val, current);\n }\n });\n }\n\n /**\n * Emit the cancelable `row-commit` event and apply its outcome — revert on\n * `preventDefault()`, otherwise refresh committed-dirty tracking and queue the\n * change animation.\n */\n #finalizeRowCommit(rowIndex: number, rowId: string | undefined, current: T, snapshot: T | undefined): void {\n // Compare snapshot vs current to detect if changes were made during THIS edit session\n const changedThisSession = hasRowChanged(snapshot, current);\n\n // Check if this row has any cumulative changes (via ID tracking)\n // Fall back to session-based detection when no row ID is available\n const changed = rowId ? this.#dirty.changedRowIds.has(rowId) : changedThisSession;\n\n const cancelled = this.emitCancelable<RowCommitDetail<T>>('row-commit', {\n rowIndex,\n rowId: rowId ?? '',\n row: current,\n oldValue: snapshot,\n newValue: current,\n changed,\n changedRows: this.changedRows,\n changedRowIds: this.changedRowIds,\n });\n\n // If consumer called preventDefault(), revert the row\n if (cancelled) {\n if (snapshot) this.#revertRowFromSnapshot(rowId, current, snapshot);\n return;\n }\n\n // Mark row as committed-dirty if it has actual changes vs baseline\n if (rowId && this.config.dirtyTracking) {\n if (this.#dirty.isRowDirty(rowId, current)) {\n this.#dirty.committedDirtyRowIds.add(rowId);\n } else {\n this.#dirty.committedDirtyRowIds.delete(rowId);\n }\n }\n\n if (changedThisSession && this.isAnimationEnabled) {\n // Animate the row only if changes were made during this edit session\n // (deferred to afterRender so the row element exists after re-render)\n this.#pendingRowAnimation = rowIndex;\n }\n }\n\n /**\n * Clear all per-row editing bookkeeping.\n *\n * The `#editingCells` / `#editorValueCallbacks` keys use the rowIndex captured\n * at edit-open time. Even if `_rows` was replaced and the row moved to a\n * different index, the keys still match what was inserted during this session.\n */\n #clearRowEditState(rowIndex: number): void {\n this.#rowEditSnapshots.delete(rowIndex);\n this.#activeEditRow = -1;\n this.#activeEditRowId = undefined;\n this.#activeEditRowRef = undefined;\n this.#activeEditCol = -1;\n this.#singleCellEdit = false;\n this.#syncGridEditState();\n\n for (const cellKey of this.#editingCells) {\n if (cellKey.startsWith(`${rowIndex}:`)) {\n this.#editingCells.delete(cellKey);\n }\n }\n for (const callbackKey of this.#editorValueCallbacks.keys()) {\n if (callbackKey.startsWith(`${rowIndex}:`)) {\n this.#editorValueCallbacks.delete(callbackKey);\n }\n }\n }\n\n /**\n * Release framework editor components, drop the editing state from the cells\n * and re-render the row so the display values come back.\n */\n #teardownRowEditors(rowEl: HTMLElement, internalGrid: InternalGrid<T>): void {\n // Release framework editor components (Angular/React/Vue) BEFORE clearing\n // editing state. This ensures releaseCell runs while the editor DOM is\n // still inside each cell, so the adapter can find and destroy ComponentRefs.\n // Without this, overlay editors (BaseOverlayEditor) leak panels on <body>\n // with active MutationObservers that react to cell-focus class changes.\n const adapter = internalGrid.__frameworkAdapter;\n const editingCells = rowEl.querySelectorAll('.cell.editing');\n if (adapter?.releaseCell) {\n editingCells.forEach((cell) => {\n adapter.releaseCell!(cell as HTMLElement);\n });\n }\n\n // Remove editing class and re-render cells\n editingCells.forEach((cell) => {\n cell.classList.remove('editing');\n clearEditingState(cell.parentElement as RowElementInternal);\n });\n\n // Refresh the virtual window to restore cell content WITHOUT rebuilding\n // the row model. requestRender() would trigger processRows (ROWS phase)\n // which re-sorts — causing the edited row to jump to a new position and\n // disappear from view. refreshVirtualWindow re-renders visible cells from\n // the current _rows order, keeping the row in place until the user\n // explicitly sorts again or new data arrives.\n internalGrid.refreshVirtualWindow(true);\n }\n\n /**\n * Commit a single cell value change.\n * Uses ID-based change tracking for stability when rows are reordered.\n */\n #commitCellValue(\n rowIndex: number,\n column: ColumnConfig<T>,\n newValue: unknown,\n rowData: T,\n source: UpdateSource = 'user',\n ): void {\n const field = column.field;\n if (!isSafePropertyKey(field)) return;\n const oldValue = readCellField(rowData, field);\n if (oldValue === newValue) return;\n\n const internalGrid = this.#internalGrid;\n\n // Get row ID for change tracking (may not exist if getRowId not configured)\n const rowId = this.#safeGetRowId(rowData);\n\n const firstTime = rowId ? !this.#dirty.changedRowIds.has(rowId) : true;\n\n // Create updateRow helper for cascade updates (noop if row has no ID)\n const updateRow: (changes: Partial<T>) => void = rowId\n ? (changes) => this.grid.updateRow(rowId!, changes as Record<string, unknown>, 'cascade')\n : noopUpdateRow;\n\n // Track whether setInvalid was called during event handling\n let invalidWasSet = false;\n\n // Create setInvalid callback for validation (noop if row has no ID)\n const setInvalid = rowId\n ? (message?: string) => {\n invalidWasSet = true;\n this.setInvalid(rowId!, field, message ?? '');\n }\n : () => {}; // eslint-disable-line @typescript-eslint/no-empty-function\n\n // Emit cancelable event BEFORE applying the value.\n //\n // Re-entrancy guard: a `cell-commit` listener commonly cascades by calling\n // `detail.updateRow()` / `grid.updateRow()` (which route back through this\n // commit pipeline) or forces a row re-render the same way. If that nested\n // update targets the SAME cell that is still mid-commit, re-emitting\n // `cell-commit` would recurse until the call stack overflows\n // (`RangeError: Maximum call stack size exceeded`).\n //\n // When we detect a re-entrant commit of a cell already in flight we RETURN\n // EARLY rather than re-applying: the OUTER commit still owns this cell and\n // will apply the value + emit `cell-edit-committed` exactly once when its\n // own emit returns. Re-applying here would instead (a) fire a duplicate\n // `cell-edit-committed` → a phantom UndoRedo history entry, and (b) sneak\n // the value in even when the outer listener called `preventDefault()`,\n // bypassing the cancelable-commit contract. Cascades to OTHER cells still\n // emit normally, and the set is keyed per (row, field) so distinct fields\n // can never form an unbounded chain.\n const commitKey = `${rowId ?? rowIndex}\\u0000${field}`;\n if (this.#committingCells.has(commitKey)) return;\n\n let cancelled = false;\n this.#committingCells.add(commitKey);\n try {\n cancelled = this.emitCancelable<CellCommitDetail<T>>('cell-commit', {\n row: rowData,\n rowId: rowId ?? '',\n field,\n oldValue,\n value: newValue,\n source,\n rowIndex,\n changedRows: this.changedRows,\n changedRowIds: this.changedRowIds,\n firstTimeForRow: firstTime,\n updateRow,\n setInvalid,\n });\n } finally {\n this.#committingCells.delete(commitKey);\n }\n\n // If consumer called preventDefault(), abort the commit\n if (cancelled) return;\n\n // Clear any previous invalid state for this cell ONLY if setInvalid wasn't called\n // (if setInvalid was called, the handler wants it to remain invalid)\n if (rowId && !invalidWasSet && this.isCellInvalid(rowId, field)) {\n this.clearInvalid(rowId, field);\n }\n\n // Apply the value and mark row as changed.\n // Whole-row invalidation (not per-`field`): `field` here is this column's\n // own key, but OTHER columns' `valueAccessor`s may derive from it while\n // being cached under their own `column.field`. Per-field invalidation would\n // refresh only this column and leave those dependent columns stale.\n writeCellField(rowData, field, newValue);\n invalidateAccessorCache(rowData as object);\n if (rowId) {\n this.#dirty.changedRowIds.add(rowId);\n }\n this.#syncGridEditState();\n\n // Emit dirty-change event if dirty tracking is enabled\n if (this.config.dirtyTracking && rowId) {\n const dirty = this.#dirty.isRowDirty(rowId, rowData);\n this.#emitDirtyChange(rowId, rowData, dirty ? 'modified' : 'pristine');\n }\n\n // Notify other plugins (e.g., UndoRedoPlugin) about the committed edit\n this.emitPluginEvent('cell-edit-committed', {\n rowIndex,\n field,\n oldValue,\n newValue,\n });\n\n // Mark the row visually as changed (animation happens when row edit closes)\n const rowEl = internalGrid.findRenderedRowElement?.(rowIndex);\n if (rowEl) {\n rowEl.classList.add('changed');\n }\n }\n\n /**\n * Inject an editor into a cell.\n * Delegates to the extracted `editor-injection` module.\n */\n #injectEditor(\n rowData: T,\n rowIndex: number,\n column: ColumnConfig<T>,\n colIndex: number,\n cell: HTMLElement,\n skipFocus: boolean,\n parentRowEl?: HTMLElement,\n ): void {\n injectEditorImpl(this.#editorDeps, rowData, rowIndex, column, colIndex, cell, skipFocus, parentRowEl);\n }\n\n /**\n * Restore focus to cell after exiting edit mode.\n */\n #restoreCellFocus(internalGrid: InternalGrid<T>): void {\n queueMicrotask(() => {\n try {\n const rowIdx = internalGrid._focusRow;\n const colIdx = internalGrid._focusCol;\n const rowEl = internalGrid.findRenderedRowElement?.(rowIdx);\n if (rowEl) {\n Array.from(internalGrid._bodyEl.querySelectorAll('.cell-focus')).forEach((el) =>\n el.classList.remove('cell-focus'),\n );\n const cell = rowEl.querySelector(`.cell[data-row=\"${rowIdx}\"][data-col=\"${colIdx}\"]`) as HTMLElement | null;\n if (cell) {\n cell.classList.add('cell-focus');\n cell.setAttribute('aria-selected', 'true');\n if (!cell.hasAttribute('tabindex')) cell.setAttribute('tabindex', '-1');\n cell.focus({ preventScroll: true });\n }\n }\n } catch {\n /* empty */\n }\n });\n }\n\n // #endregion\n}\n"],"mappings":"sEAoBA,IAgBa,EAsBF,UAmDE,EAWA,qBC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Aa,UACtB,EAAS,EAAa,UACtB,EAAQ,EAAa,yBAAyB,GACpD,GAAI,EAAO,CACT,MAAM,KAAK,EAAa,QAAQ,iBAAiB,gBAAgB,QAAS,GACxE,EAAG,UAAU,OAAO,eAEtB,MAAM,EAAO,EAAM,cAAc,mBAAmB,iBAAsB,OACtE,IACF,EAAK,UAAU,IAAI,cACnB,EAAK,aAAa,gBAAiB,QAC9B,EAAK,aAAa,aAAa,EAAK,aAAa,WAAY,MAClE,EAAK,MAAM,CAAE,eAAe,IAEhC,CACF,CAAA,MAEA,GAEJ"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../libs/grid/src/lib/core/constants.ts","../../../../../../libs/grid/src/lib/core/defaults.ts","../../../../../../libs/grid/src/lib/core/internal/aria.ts","../../../../../../libs/grid/src/lib/core/internal/utils.ts","../../../../../../libs/grid/src/lib/core/internal/value-accessor.ts","../../../../../../libs/grid/src/lib/core/internal/virtualization.ts","../../../../../../libs/grid/src/lib/core/internal/keyboard.ts","../../../../../../libs/grid/src/lib/core/internal/sanitize.ts","../../../../../../libs/grid/src/lib/core/internal/diagnostics.ts","../../../../../../libs/grid/src/lib/core/plugin/base-plugin.ts","../../../../../../libs/grid/src/lib/plugins/editing/editing.css?inline","../../../../../../libs/grid/src/lib/plugins/editing/editors.ts","../../../../../../libs/grid/src/lib/plugins/editing/internal/cell-validation.ts","../../../../../../libs/grid/src/lib/plugins/editing/internal/dirty-tracking.ts","../../../../../../libs/grid/src/lib/plugins/editing/internal/dirty-tracking-manager.ts","../../../../../../libs/grid/src/lib/plugins/editing/internal/helpers.ts","../../../../../../libs/grid/src/lib/plugins/editing/internal/editor-injection.ts","../../../../../../libs/grid/src/lib/plugins/editing/editing-plugin.ts"],"sourcesContent":["/**\n * Grid DOM Constants\n *\n * Centralized constants for CSS classes, data attributes, and selectors\n * used throughout the grid. Use these instead of magic strings.\n *\n * Note: Some constants here are used by plugins but defined in core because:\n * 1. The core CSS needs to style these elements (e.g., sticky positioning)\n * 2. Multiple plugins may share the same class names\n *\n * Plugins can define their own additional constants and export them.\n * See each plugin's index.ts for plugin-specific exports.\n */\n\n/**\n * CSS selector for focusable editor elements within a cell.\n * Used by EditingPlugin, UndoRedoPlugin, and keyboard navigation. Defined here\n * (a leaf module) rather than in `rows.ts` so `keyboard.ts` can consume it\n * without creating a rows ↔ keyboard import cycle.\n */\nexport const FOCUSABLE_EDITOR_SELECTOR =\n 'input,select,textarea,[contenteditable=\"true\"],[contenteditable=\"\"],[tabindex]:not([tabindex=\"-1\"])';\n\n// #region CSS Classes\n\n/**\n * CSS class names used in the grid's DOM.\n * Use these when adding/removing classes or querying elements.\n *\n * Classes are organized by:\n * - Core: Used by the grid core for structure and basic functionality\n * - Shared: Used by multiple features/plugins, styled by core CSS\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridClasses = {\n // ─── Core Structure ───────────────────────────────────────────────\n ROOT: 'tbw-grid-root',\n HEADER: 'header',\n HEADER_ROW: 'header-row',\n HEADER_CELL: 'header-cell',\n\n // Body structure\n ROWS_VIEWPORT: 'rows-viewport',\n ROWS_SPACER: 'rows-spacer',\n ROWS_CONTAINER: 'rows',\n\n // Row elements\n DATA_ROW: 'data-grid-row',\n GROUP_ROW: 'group-row',\n\n // Cell elements\n DATA_CELL: 'cell',\n\n // ─── Core States ──────────────────────────────────────────────────\n SELECTED: 'selected',\n FOCUSED: 'focused',\n EDITING: 'editing',\n EXPANDED: 'expanded',\n COLLAPSED: 'collapsed',\n DRAGGING: 'dragging',\n RESIZING: 'resizing',\n\n // Sorting (core feature)\n SORTABLE: 'sortable',\n SORTED_ASC: 'sorted-asc',\n SORTED_DESC: 'sorted-desc',\n\n // Visibility\n HIDDEN: 'hidden',\n\n // ─── Shared Classes (used by plugins, styled by core CSS) ────────\n // These are defined here because core CSS provides the base styling.\n // Plugins apply these classes; core CSS defines how they look.\n\n // Sticky positioning (PinnedColumnsPlugin applies, core CSS styles)\n STICKY_LEFT: 'sticky-left',\n STICKY_RIGHT: 'sticky-right',\n\n // Pinned rows (PinnedRowsPlugin applies, core CSS styles)\n PINNED_TOP: 'pinned-top',\n PINNED_BOTTOM: 'pinned-bottom',\n\n // Tree structure (TreePlugin applies, core CSS styles)\n TREE_TOGGLE: 'tree-toggle',\n TREE_INDENT: 'tree-indent',\n\n // Grouping (GroupingRowsPlugin applies, core CSS styles)\n GROUP_TOGGLE: 'group-toggle',\n GROUP_LABEL: 'group-label',\n GROUP_COUNT: 'group-count',\n\n // Selection (SelectionPlugin applies, core CSS styles)\n RANGE_SELECTION: 'range-selection',\n SELECTION_OVERLAY: 'selection-overlay',\n} as const;\n\n// #endregion\n\n// #region Data Attributes\n\n/**\n * Data attribute names used on grid elements.\n * Use these when getting/setting data attributes.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridDataAttrs = {\n // ─── Core Attributes ──────────────────────────────────────────────\n FIELD: 'data-field',\n\n /**\n * Marks a `title` the grid itself put on a cell to reveal ellipsised text\n * (WCAG SC 1.4.12). Anything that sets its own `title` on a cell must clear\n * this, or the grid will later mistake that title for its own and replace it.\n *\n * @since 3.6.0\n */\n TRUNCATED: 'data-tbw-truncated',\n\n // ─── Shared Attributes (used by plugins) ──────────────────────────\n GROUP_KEY: 'data-group-key', // GroupingRowsPlugin\n} as const;\n\n// #endregion\n\n// #region Selectors\n\n/**\n * Common CSS selectors for querying grid elements.\n * Built from the class constants for consistency.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridSelectors = {\n ROOT: `.${GridClasses.ROOT}`,\n HEADER: `.${GridClasses.HEADER}`,\n HEADER_ROW: `.${GridClasses.HEADER_ROW}`,\n HEADER_CELL: `.${GridClasses.HEADER_CELL}`,\n ROWS_VIEWPORT: `.${GridClasses.ROWS_VIEWPORT}`,\n ROWS_CONTAINER: `.${GridClasses.ROWS_CONTAINER}`,\n DATA_ROW: `.${GridClasses.DATA_ROW}`,\n DATA_CELL: `.${GridClasses.DATA_CELL}`,\n GROUP_ROW: `.${GridClasses.GROUP_ROW}`,\n\n // By data attribute\n CELL_BY_FIELD: (field: string) => `.${GridClasses.DATA_CELL}[${GridDataAttrs.FIELD}=\"${field}\"]`,\n\n // State selectors\n SELECTED_ROWS: `.${GridClasses.DATA_ROW}.${GridClasses.SELECTED}`,\n EDITING_CELL: `.${GridClasses.DATA_CELL}.${GridClasses.EDITING}`,\n} as const;\n\n// #endregion\n\n// #region CSS Custom Properties\n\n/**\n * CSS custom property names for theming.\n * Use these when programmatically setting styles.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport const GridCSSVars = {\n // Colors\n COLOR_BG: '--tbw-color-bg',\n COLOR_FG: '--tbw-color-fg',\n COLOR_FG_MUTED: '--tbw-color-fg-muted',\n COLOR_BORDER: '--tbw-color-border',\n COLOR_ACCENT: '--tbw-color-accent',\n COLOR_HEADER_BG: '--tbw-color-header-bg',\n COLOR_HEADER_FG: '--tbw-color-header-fg',\n COLOR_SELECTION: '--tbw-color-selection',\n COLOR_ROW_HOVER: '--tbw-color-row-hover',\n COLOR_ROW_ALT: '--tbw-color-row-alt',\n\n // Sizing\n ROW_HEIGHT: '--tbw-row-height',\n HEADER_HEIGHT: '--tbw-header-height',\n CELL_PADDING: '--tbw-cell-padding',\n\n // Typography\n FONT_FAMILY: '--tbw-font-family',\n FONT_SIZE: '--tbw-font-size',\n\n // Borders\n BORDER_RADIUS: '--tbw-border-radius',\n FOCUS_OUTLINE: '--tbw-focus-outline',\n} as const;\n\n// #endregion\n\n// Type helpers\n\n/**\n * Union of all CSS class names used in the grid's DOM.\n * Use `GridClasses` to access individual values by key.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport type GridClassName = (typeof GridClasses)[keyof typeof GridClasses];\n\n/**\n * Union of all `data-*` attribute names used on grid elements.\n * Use `GridDataAttrs` to access individual values by key.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport type GridDataAttr = (typeof GridDataAttrs)[keyof typeof GridDataAttrs];\n\n/**\n * Union of all CSS custom property names (`--tbw-*`) available for theming.\n * Use `GridCSSVars` to access individual values by key.\n *\n * @category Plugin Development\n * @since 0.1.1\n */\nexport type GridCSSVar = (typeof GridCSSVars)[keyof typeof GridCSSVars];\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 * ARIA Accessibility Helpers\n *\n * Pure functions for managing ARIA attributes on grid elements.\n * Implements caching to avoid redundant DOM writes during scroll.\n *\n * @module internal/aria\n */\n\nimport { DEFAULT_A11Y_MESSAGES } from '../defaults';\nimport type { A11yMessages, GridConfig } from '../types';\n\n// #region Types\n\n/**\n * State for caching ARIA attributes to avoid redundant DOM writes.\n */\nexport interface AriaState {\n /** Last set row count */\n rowCount: number;\n /** Last set column count */\n colCount: number;\n /** Last set aria-label */\n ariaLabel: string | undefined;\n /** Last set aria-labelledby */\n ariaLabelledBy: string | undefined;\n /** Last set aria-describedby */\n ariaDescribedBy: string | undefined;\n /** Last set aria-roledescription */\n ariaRoleDescription: string | undefined;\n /** Last source row count announced via `dataLoaded`; used to suppress duplicate announcements */\n lastAnnouncedSourceCount: number;\n}\n\n/**\n * Create initial ARIA state.\n */\nexport function createAriaState(): AriaState {\n return {\n rowCount: -1,\n colCount: -1,\n ariaLabel: undefined,\n ariaLabelledBy: undefined,\n ariaDescribedBy: undefined,\n ariaRoleDescription: undefined,\n lastAnnouncedSourceCount: -1,\n };\n}\n\n// #endregion\n\n// #region Count Updates\n\n/**\n * Update ARIA row and column counts on grid elements.\n * Uses caching to avoid redundant DOM writes on every scroll frame.\n *\n * @param state - ARIA state for caching\n * @param rowsBodyEl - Element to set aria-rowcount/aria-colcount on\n * @param bodyEl - Element to set role=\"rowgroup\" on\n * @param rowCount - Current row count\n * @param colCount - Current column count\n * @returns true if anything was updated\n */\nexport function updateAriaCounts(\n state: AriaState,\n rowsBodyEl: HTMLElement | null,\n bodyEl: HTMLElement | null,\n rowCount: number,\n colCount: number,\n): boolean {\n // Skip if nothing changed (hot path optimization for scroll)\n if (rowCount === state.rowCount && colCount === state.colCount) {\n return false;\n }\n\n const prevRowCount = state.rowCount;\n state.rowCount = rowCount;\n state.colCount = colCount;\n\n // Update ARIA counts on inner grid element\n if (rowsBodyEl) {\n rowsBodyEl.setAttribute('aria-rowcount', String(rowCount));\n rowsBodyEl.setAttribute('aria-colcount', String(colCount));\n }\n\n // Set role=\"rowgroup\" on .rows only when there are rows (ARIA compliance)\n if (rowCount !== prevRowCount && bodyEl) {\n if (rowCount > 0) {\n bodyEl.setAttribute('role', 'rowgroup');\n } else {\n bodyEl.removeAttribute('role');\n }\n }\n\n return true;\n}\n\n// #endregion\n\n// #region Label Updates\n\n/**\n * Determine the effective aria-label for the grid.\n * Priority: explicit config > shell title > nothing\n *\n * The shell title is read from `config.shell.header.title`. The shell plugin\n * folds any light-DOM `<tbw-grid-header title>` into that field via its\n * `processConfig` hook (extraction #370), so core needs no plugin state here.\n *\n * @param config - Grid configuration (the merged effective config)\n * @returns The aria-label to use, or undefined\n */\nexport function getEffectiveAriaLabel<T>(config: GridConfig<T> | undefined): string | undefined {\n const explicitLabel = config?.gridAriaLabel;\n if (explicitLabel) return explicitLabel;\n\n return config?.shell?.header?.title ?? undefined;\n}\n\n/**\n * Update ARIA label and describedby attributes on the grid container.\n * Uses caching to avoid redundant DOM writes.\n *\n * @param state - ARIA state for caching\n * @param rowsBodyEl - Element to set aria-label/aria-describedby on\n * @param config - Grid configuration (the merged effective config)\n * @returns true if anything was updated\n */\nexport function updateAriaLabels<T>(\n state: AriaState,\n rowsBodyEl: HTMLElement | null,\n config: GridConfig<T> | undefined,\n): boolean {\n if (!rowsBodyEl) return false;\n\n let updated = false;\n\n // aria-labelledby wins per WAI-ARIA accessible-name precedence — when set,\n // `aria-label` is suppressed even if explicitly configured to avoid two\n // competing names being computed by AT.\n const ariaLabelledBy = config?.gridAriaLabelledBy;\n const effectiveLabel = ariaLabelledBy ? undefined : getEffectiveAriaLabel(config);\n\n // Update aria-labelledby only if changed\n if (ariaLabelledBy !== state.ariaLabelledBy) {\n state.ariaLabelledBy = ariaLabelledBy;\n if (ariaLabelledBy) {\n rowsBodyEl.setAttribute('aria-labelledby', ariaLabelledBy);\n } else {\n rowsBodyEl.removeAttribute('aria-labelledby');\n }\n updated = true;\n }\n\n // Update aria-label only if changed\n if (effectiveLabel !== state.ariaLabel) {\n state.ariaLabel = effectiveLabel;\n if (effectiveLabel) {\n rowsBodyEl.setAttribute('aria-label', effectiveLabel);\n } else {\n rowsBodyEl.removeAttribute('aria-label');\n }\n updated = true;\n }\n\n // Update aria-describedby only if changed\n const ariaDescribedBy = config?.gridAriaDescribedBy;\n if (ariaDescribedBy !== state.ariaDescribedBy) {\n state.ariaDescribedBy = ariaDescribedBy;\n if (ariaDescribedBy) {\n rowsBodyEl.setAttribute('aria-describedby', ariaDescribedBy);\n } else {\n rowsBodyEl.removeAttribute('aria-describedby');\n }\n updated = true;\n }\n\n // Update aria-roledescription only if changed. Apps can override the\n // announced role name (e.g. localized \"Tabell\" instead of generic \"grid\").\n const ariaRoleDescription = config?.gridAriaRoleDescription;\n if (ariaRoleDescription !== state.ariaRoleDescription) {\n state.ariaRoleDescription = ariaRoleDescription;\n if (ariaRoleDescription) {\n rowsBodyEl.setAttribute('aria-roledescription', ariaRoleDescription);\n } else {\n rowsBodyEl.removeAttribute('aria-roledescription');\n }\n updated = true;\n }\n\n return updated;\n}\n\n// #endregion\n\n// #region Live Announcements\n\n/**\n * Announce a message to screen readers via the grid's aria-live region.\n * Clears then sets text to ensure repeated messages are re-announced.\n *\n * Respects `effectiveConfig.a11y.announcements` — if set to `false`,\n * the announcement is silently skipped.\n *\n * @param gridEl - The grid host element (or any ancestor containing `.tbw-sr-only`)\n * @param message - The message to announce\n */\nexport function announce(gridEl: HTMLElement, message: string): void {\n // Check if announcements are disabled via config.\n // gridEl is always a DataGridElement at runtime — use property access safely.\n if (!gridEl) return;\n const config =\n 'effectiveConfig' in gridEl\n ? (gridEl as HTMLElement & { effectiveConfig?: GridConfig }).effectiveConfig\n : undefined;\n if (config?.a11y?.announcements === false) return;\n\n const el = gridEl.querySelector?.('.tbw-sr-only');\n if (!el) return;\n // Clear first so identical consecutive messages are still announced\n el.textContent = '';\n // `requestAnimationFrame` can be undefined if a debounced announcement fires\n // after the DOM/host environment is torn down (notably in unit tests). Fall\n // back to a direct assignment so `announce` never throws out of band.\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => {\n el.textContent = message;\n });\n } else {\n el.textContent = message;\n }\n}\n\n/**\n * Get an announcement message, preferring custom overrides from config.\n * Falls back to default English messages when no override is provided.\n *\n * @param gridEl - The grid host element\n * @param key - The message key from A11yMessages\n * @param args - Arguments to pass to the message function\n */\nexport function getA11yMessage<K extends keyof A11yMessages>(\n gridEl: HTMLElement,\n key: K,\n ...args: Parameters<A11yMessages[K]>\n): string {\n const config =\n gridEl && 'effectiveConfig' in gridEl\n ? (gridEl as HTMLElement & { effectiveConfig?: GridConfig }).effectiveConfig\n : undefined;\n const customFn = config?.a11y?.messages?.[key] as ((...a: Parameters<A11yMessages[K]>) => string) | undefined;\n if (customFn) return customFn(...args);\n return (DEFAULT_A11Y_MESSAGES[key] as (...a: Parameters<A11yMessages[K]>) => string)(...args);\n}\n\n/**\n * Announce a `dataLoaded` message — but only when the source row count has\n * actually changed since the last announcement. This prevents announcement\n * spam from internal `data-change` emits triggered by sort/filter/edit, which\n * have their own dedicated announcements.\n *\n * @param gridEl - The grid host element\n * @param state - ARIA state (tracks last announced count)\n * @param sourceRowCount - Current source row count\n */\nexport function announceDataLoaded(gridEl: HTMLElement, state: AriaState, sourceRowCount: number): void {\n if (sourceRowCount === state.lastAnnouncedSourceCount) return;\n const previousAnnouncedSourceCount = state.lastAnnouncedSourceCount;\n state.lastAnnouncedSourceCount = sourceRowCount;\n // Skip only the initial sentinel → 0 transition (empty grid mount). A later\n // transition to 0 (e.g. data cleared / reloaded to an empty result set) should\n // still announce so screen-reader users hear that the grid is now empty.\n if (sourceRowCount === 0 && previousAnnouncedSourceCount < 0) return;\n announce(gridEl, getA11yMessage(gridEl, 'dataLoaded', sourceRowCount));\n}\n\n// #endregion\n","// #region Environment Helpers\n\n/**\n * Check if we're running in a development environment.\n * Returns true for localhost or when NODE_ENV !== 'production'.\n * Used to show warnings only in development.\n */\nexport function isDevelopment(): boolean {\n // Check for localhost (browser environment)\n if (typeof window !== 'undefined' && window.location) {\n const hostname = window.location.hostname;\n if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1') {\n return true;\n }\n }\n // Check for NODE_ENV (build-time or SSR)\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n return true;\n }\n return false;\n}\n\n// #endregion\n\n// #region Cell Rendering Helpers\n\n/**\n * Generate accessible HTML for a boolean cell.\n * Uses role=\"checkbox\" with proper aria attributes.\n */\nexport function booleanCellHTML(value: boolean): string {\n return `<span role=\"checkbox\" aria-checked=\"${value}\" aria-label=\"${value}\">${value ? '🗹' : '☐'}</span>`;\n}\n\n/**\n * Format a date value for display.\n * Handles Date objects, timestamps, and date strings.\n * Returns empty string for invalid dates.\n */\nexport function formatDateValue(value: unknown): string {\n if (value == null || value === '') return '';\n if (value instanceof Date) {\n return isNaN(value.getTime()) ? '' : value.toLocaleDateString();\n }\n if (typeof value === 'number' || typeof value === 'string') {\n const d = new Date(value);\n return isNaN(d.getTime()) ? '' : d.toLocaleDateString();\n }\n return '';\n}\n\n/**\n * Get the row index from a cell element's data-row attribute.\n * Falls back to calculating from parent row's DOM position if data-row is missing.\n * Returns -1 if no valid row index is found.\n */\nexport function getRowIndexFromCell(cell: Element | null): number {\n if (!cell) return -1;\n const attr = cell.getAttribute('data-row');\n if (attr) return parseInt(attr, 10);\n\n // Fallback: find the parent .data-grid-row and calculate index from siblings\n const rowEl = cell.closest('.data-grid-row');\n if (!rowEl) return -1;\n\n const parent = rowEl.parentElement;\n if (!parent) return -1;\n\n // Get all data-grid-row siblings and find this row's index\n const rows = parent.querySelectorAll(':scope > .data-grid-row');\n for (let i = 0; i < rows.length; i++) {\n if (rows[i] === rowEl) return i;\n }\n return -1;\n}\n\n/**\n * Get the column index from a cell element's data-col attribute.\n * Returns -1 if no valid column index is found.\n */\nexport function getColIndexFromCell(cell: Element | null): number {\n if (!cell) return -1;\n const attr = cell.getAttribute('data-col');\n return attr ? parseInt(attr, 10) : -1;\n}\n\n/**\n * Clear all cell-focus styling from a root element.\n * Used when changing focus or when selection plugin takes over focus management.\n */\nexport function clearCellFocus(root: Element | null): void {\n if (!root) return;\n root.querySelectorAll('.cell-focus').forEach((el) => el.classList.remove('cell-focus'));\n}\n// #endregion\n\n// #region RTL Helpers\n\n/** Text direction */\nexport type TextDirection = 'ltr' | 'rtl';\n\n/**\n * Get the text direction for an element.\n * Reads from the computed style, which respects the `dir` attribute on the element\n * or any ancestor, as well as CSS `direction` property.\n *\n * @param element - The element to check direction for\n * @returns 'ltr' or 'rtl'\n *\n * @example\n * ```typescript\n * // Detect grid's direction\n * const dir = getDirection(gridElement);\n * if (dir === 'rtl') {\n * // Handle RTL layout\n * }\n * ```\n */\nexport function getDirection(element: Element): TextDirection {\n // Try computed style first (works in real browsers)\n try {\n const computedDir = getComputedStyle(element).direction;\n if (computedDir === 'rtl') return 'rtl';\n } catch {\n // getComputedStyle may fail in some test environments\n }\n\n // Fallback: check dir attribute on element or ancestors\n // This handles test environments where getComputedStyle may not reflect dir attribute\n try {\n const dirAttr = element.closest?.('[dir]')?.getAttribute('dir');\n if (dirAttr === 'rtl') return 'rtl';\n } catch {\n // closest may not be available on mock elements\n }\n\n return 'ltr';\n}\n\n/**\n * Check if an element is in RTL mode.\n *\n * @param element - The element to check\n * @returns true if the element's text direction is right-to-left\n */\nexport function isRTL(element: Element): boolean {\n return getDirection(element) === 'rtl';\n}\n\n/**\n * Resolve a logical inline position to a physical position based on text direction.\n *\n * - `'start'` → `'left'` in LTR, `'right'` in RTL\n * - `'end'` → `'right'` in LTR, `'left'` in RTL\n * - `'left'` / `'right'` → unchanged (physical values)\n *\n * @param position - Logical or physical position\n * @param direction - Text direction ('ltr' or 'rtl')\n * @returns Physical position ('left' or 'right')\n *\n * @example\n * ```typescript\n * resolveInlinePosition('start', 'ltr'); // 'left'\n * resolveInlinePosition('start', 'rtl'); // 'right'\n * resolveInlinePosition('left', 'rtl'); // 'left' (unchanged)\n * ```\n */\nexport function resolveInlinePosition(\n position: 'left' | 'right' | 'start' | 'end',\n direction: TextDirection,\n): 'left' | 'right' {\n if (position === 'left' || position === 'right') {\n return position;\n }\n if (direction === 'rtl') {\n return position === 'start' ? 'right' : 'left';\n }\n return position === 'start' ? 'left' : 'right';\n}\n// #endregion\n","/**\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 * Row Virtualization Module\n *\n * Provides all virtualization-related functionality for the grid:\n *\n * 1. **Position Cache** (index-based): Maps row index → {offset, height, measured}\n * - Rebuilt when row count changes (expand/collapse, filter)\n * - Used for scroll position → row index lookups (binary search)\n *\n * 2. **Height Cache** (identity-based): Maps row identity → height\n * - Persists across expand/collapse\n * - Uses rowId string keys when available, WeakMap otherwise\n * - Synthetic rows use __rowCacheKey for stable identity\n *\n * 3. **Virtual Window**: Computes which rows to render based on scroll position\n *\n * 4. **Row Measurement**: Measures rendered row heights from DOM\n */\n\n// #region Types\n\n/**\n * Position entry for a single row in the position cache.\n * @category Plugin Development\n */\nexport interface RowPosition {\n /** Cumulative offset from top in pixels */\n offset: number;\n /** Row height in pixels */\n height: number;\n /** Whether this is a measured value (true) or estimate (false) */\n measured: boolean;\n}\n\n/**\n * Height cache that persists row heights across position cache rebuilds.\n * Uses dual storage: Map for string keys (rowId, __rowCacheKey) and WeakMap for object refs.\n * @category Plugin Development\n */\nexport interface HeightCache {\n /** Heights keyed by string (for synthetic rows with __rowCacheKey or rowId-keyed rows) */\n byKey: Map<string, number>;\n /** Heights keyed by object reference (for data rows without rowId) */\n byRef: WeakMap<object, number>;\n}\n\n/**\n * Configuration for the position cache.\n */\nexport interface PositionCacheConfig<T = unknown> {\n /** Function to get row ID (if configured) */\n rowId?: (row: T) => string | number;\n}\n\n// #endregion\n\n// #region Height Cache Operations\n\n/**\n * Create a new empty height cache.\n */\nexport function createHeightCache(): HeightCache {\n return {\n byKey: new Map(),\n byRef: new WeakMap(),\n };\n}\n\n/**\n * Get the cache key for a row.\n * Returns string for synthetic rows (__rowCacheKey) or rowId-keyed rows,\n * or the row object itself for WeakMap lookup.\n */\nexport function getRowCacheKey<T>(row: T, rowId?: (row: T) => string | number): string | T {\n if (!row || typeof row !== 'object') return row;\n\n // 1. Synthetic rows: plugins MUST add __rowCacheKey\n if ('__rowCacheKey' in row) {\n return (row as { __rowCacheKey: string }).__rowCacheKey;\n }\n\n // 2. rowId property directly on the row (common pattern)\n if ('rowId' in row && (row as { rowId: string | number }).rowId != null) {\n return `id:${(row as { rowId: string | number }).rowId}`;\n }\n\n // 3. User-provided rowId function (if configured)\n if (rowId) {\n return `id:${rowId(row)}`;\n }\n\n // 4. Object identity (for WeakMap)\n return row;\n}\n\n/**\n * Get cached height for a row.\n * @returns Cached height or undefined if not cached\n */\nexport function getCachedHeight<T>(\n cache: HeightCache,\n row: T,\n rowId?: (row: T) => string | number,\n): number | undefined {\n const key = getRowCacheKey(row, rowId);\n\n if (typeof key === 'string') {\n return cache.byKey.get(key);\n }\n\n // Object key - use WeakMap\n if (key && typeof key === 'object') {\n return cache.byRef.get(key);\n }\n\n return undefined;\n}\n\n/**\n * Set cached height for a row.\n */\nexport function setCachedHeight<T>(\n cache: HeightCache,\n row: T,\n height: number,\n rowId?: (row: T) => string | number,\n): void {\n const key = getRowCacheKey(row, rowId);\n\n if (typeof key === 'string') {\n cache.byKey.set(key, height);\n } else if (key && typeof key === 'object') {\n cache.byRef.set(key, height);\n }\n}\n\n// #endregion\n\n// #region Position Cache Operations\n\n/**\n * Rebuild position cache preserving known heights from height cache.\n * Called when row count changes (expand/collapse, filter, data change).\n *\n * @param rows - Array of row data\n * @param heightCache - Height cache with persisted measurements\n * @param estimatedHeight - Estimated height for unmeasured rows\n * @param config - Position cache configuration\n * @param getPluginHeight - Optional function to get height from plugins\n * @returns New position cache\n */\nexport function rebuildPositionCache<T>(\n rows: T[],\n heightCache: HeightCache,\n estimatedHeight: number,\n config: PositionCacheConfig<T>,\n getPluginHeight?: (row: T, index: number) => number | undefined,\n): RowPosition[] {\n const cache: RowPosition[] = new Array(rows.length);\n let offset = 0;\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n\n // Height resolution order:\n // 1. Plugin's getRowHeight() (for synthetic rows with known heights)\n let height = getPluginHeight?.(row, i);\n let measured = height !== undefined;\n\n // 2. Cached height from previous measurements\n if (height === undefined) {\n height = getCachedHeight(heightCache, row, config.rowId);\n measured = height !== undefined;\n }\n\n // 3. Fall back to estimate\n if (height === undefined) {\n height = estimatedHeight;\n measured = false;\n }\n\n cache[i] = { offset, height, measured };\n offset += height;\n }\n\n return cache;\n}\n\n/**\n * Update a single row's height in the position cache.\n * Recalculates offsets for all subsequent rows.\n *\n * @param cache - Position cache to update\n * @param index - Row index to update\n * @param newHeight - New measured height\n */\nexport function updateRowHeight(cache: RowPosition[], index: number, newHeight: number): void {\n if (index < 0 || index >= cache.length) return;\n\n const entry = cache[index];\n const heightDiff = newHeight - entry.height;\n\n // Latch `measured` even when the height is unchanged, otherwise callers that enqueue on\n // `!measured` re-measure the same row on every render pass.\n entry.measured = true;\n\n if (heightDiff === 0) return;\n\n // Update this row\n entry.height = newHeight;\n\n // Recalculate offsets for all subsequent rows\n for (let i = index + 1; i < cache.length; i++) {\n cache[i].offset += heightDiff;\n }\n}\n\nexport interface RowHeightChange {\n /** Row index into the position cache. */\n index: number;\n /** Measured height in pixels. */\n height: number;\n}\n\n/**\n * Update multiple row heights while recalculating the affected cache suffix once.\n *\n * @param cache - Position cache to update (mutated in place)\n * @param changes - Height changes in any order; each row index should occur at most once\n */\nexport function updateRowHeights(cache: RowPosition[], changes: RowHeightChange[]): void {\n if (changes.length === 0 || cache.length === 0) return;\n\n // Callers usually collect in DOM order, which is already ascending — skip the copy then.\n let sortedChanges = changes;\n for (let i = 1; i < changes.length; i++) {\n if (changes[i].index < changes[i - 1].index) {\n sortedChanges = [...changes].sort((a, b) => a.index - b.index);\n break;\n }\n }\n\n let changeIndex = 0;\n while (changeIndex < sortedChanges.length && sortedChanges[changeIndex].index < 0) changeIndex++;\n if (changeIndex >= sortedChanges.length || sortedChanges[changeIndex].index >= cache.length) return;\n\n let cumulativeDiff = 0;\n const firstChangedIndex = sortedChanges[changeIndex].index;\n for (let index = firstChangedIndex; index < cache.length; index++) {\n const entry = cache[index];\n entry.offset += cumulativeDiff;\n\n while (changeIndex < sortedChanges.length && sortedChanges[changeIndex].index === index) {\n const height = sortedChanges[changeIndex].height;\n const heightDiff = height - entry.height;\n entry.measured = true;\n if (heightDiff !== 0) {\n entry.height = height;\n cumulativeDiff += heightDiff;\n }\n changeIndex++;\n }\n }\n}\n\n/**\n * Get total content height from position cache.\n *\n * @param cache - Position cache\n * @returns Total height in pixels\n */\nexport function getTotalHeight(cache: RowPosition[]): number {\n if (cache.length === 0) return 0;\n const last = cache[cache.length - 1];\n return last.offset + last.height;\n}\n\n// #endregion\n\n// #region Binary Search\n\n/**\n * Find the row index at a given scroll offset using binary search.\n * Returns the index of the row that contains the given pixel offset.\n *\n * @param cache - Position cache\n * @param targetOffset - Scroll offset in pixels\n * @returns Row index at that offset, or -1 if cache is empty\n */\nexport function getRowIndexAtOffset(cache: RowPosition[], targetOffset: number): number {\n if (cache.length === 0) return -1;\n if (targetOffset <= 0) return 0;\n\n let low = 0;\n let high = cache.length - 1;\n\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const entry = cache[mid];\n const entryEnd = entry.offset + entry.height;\n\n if (targetOffset < entry.offset) {\n high = mid - 1;\n } else if (targetOffset >= entryEnd) {\n low = mid + 1;\n } else {\n // targetOffset is within this row\n return mid;\n }\n }\n\n // Return the closest row (low will be just past the target)\n return Math.max(0, Math.min(low, cache.length - 1));\n}\n\n// #endregion\n\n// #region Statistics\n\n/**\n * Calculate the average measured height.\n * Used for estimating unmeasured rows.\n *\n * @param cache - Position cache\n * @param defaultHeight - Default height to use if no measurements\n * @returns Average measured height\n */\nexport function calculateAverageHeight(cache: RowPosition[], defaultHeight: number): number {\n let totalHeight = 0;\n let measuredCount = 0;\n\n for (const entry of cache) {\n if (entry.measured) {\n totalHeight += entry.height;\n measuredCount++;\n }\n }\n\n return measuredCount > 0 ? totalHeight / measuredCount : defaultHeight;\n}\n\n/**\n * Count how many rows have been measured.\n *\n * @param cache - Position cache\n * @returns Number of measured rows\n */\nexport function countMeasuredRows(cache: RowPosition[]): number {\n let count = 0;\n for (const entry of cache) {\n if (entry.measured) count++;\n }\n return count;\n}\n\n// #endregion\n// #region Row Measurement\n\n/**\n * Result of measuring rendered row heights.\n */\nexport interface RowMeasurementResult {\n /** Whether any heights changed */\n hasChanges: boolean;\n /** Updated measured row count */\n measuredCount: number;\n /** Updated average height */\n averageHeight: number;\n}\n\n/**\n * Context for measuring rendered rows.\n */\nexport interface RowMeasurementContext<T> {\n /** Position cache to update */\n positionCache: RowPosition[];\n /** Height cache for persistence */\n heightCache: HeightCache;\n /** Row data array */\n rows: T[];\n /** Default row height */\n defaultHeight: number;\n /** Start index of rendered window */\n start: number;\n /** End index of rendered window (exclusive) */\n end: number;\n /** Function to get plugin height for a row */\n getPluginHeight?: (row: T, index: number) => number | undefined;\n /** Function to get row ID for height cache keying */\n getRowId?: (row: T) => string | number;\n}\n\n/**\n * Measure rendered row heights from DOM elements and update caches.\n * Returns measurement statistics for updating virtualization state.\n *\n * @param context - Measurement context with all dependencies\n * @param rowElements - NodeList of rendered row elements\n * @returns Measurement result with flags and statistics\n */\nexport function measureRenderedRowHeights<T>(\n context: RowMeasurementContext<T>,\n rowElements: NodeListOf<Element>,\n): RowMeasurementResult {\n const { positionCache, heightCache, rows, start, end, getPluginHeight, getRowId } = context;\n\n let hasChanges = false;\n const heightChanges: RowHeightChange[] = [];\n\n rowElements.forEach((rowEl) => {\n const rowIndexStr = (rowEl as HTMLElement).dataset.rowIndex;\n if (!rowIndexStr) return;\n\n const rowIndex = parseInt(rowIndexStr, 10);\n if (rowIndex < start || rowIndex >= end || rowIndex >= rows.length) return;\n\n const row = rows[rowIndex];\n\n // Check if a plugin provides the height for this row\n const pluginHeight = getPluginHeight?.(row, rowIndex);\n\n if (pluginHeight !== undefined) {\n // Plugin provides height - use it for position cache\n const currentEntry = positionCache[rowIndex];\n if (!currentEntry.measured || Math.abs(currentEntry.height - pluginHeight) > 1) {\n heightChanges.push({ index: rowIndex, height: pluginHeight });\n hasChanges = true;\n }\n return; // Don't measure DOM for plugin-managed rows\n }\n\n // No plugin height - use DOM measurement\n const measuredHeight = (rowEl as HTMLElement).offsetHeight;\n\n if (measuredHeight > 0) {\n const currentEntry = positionCache[rowIndex];\n\n // Only update if height differs significantly (> 1px to avoid oscillation)\n if (!currentEntry.measured || Math.abs(currentEntry.height - measuredHeight) > 1) {\n heightChanges.push({ index: rowIndex, height: measuredHeight });\n setCachedHeight(heightCache, row, measuredHeight, getRowId);\n hasChanges = true;\n }\n }\n });\n\n updateRowHeights(positionCache, heightChanges);\n\n // Recompute stats\n const measuredCount = hasChanges ? countMeasuredRows(positionCache) : 0;\n const averageHeight = hasChanges ? calculateAverageHeight(positionCache, context.defaultHeight) : 0;\n\n return { hasChanges, measuredCount, averageHeight };\n}\n\n/**\n * Compute measurement statistics for a position cache, excluding plugin-managed rows.\n * Used after rebuilding position cache to get accurate averages for non-plugin rows.\n *\n * @param cache - Position cache\n * @param rows - Row data array\n * @param defaultHeight - Default height if no measurements\n * @param getPluginHeight - Function to check if plugin manages row height\n * @returns Object with measured count and average height\n */\nexport function computeAverageExcludingPluginRows<T>(\n cache: RowPosition[],\n rows: T[],\n defaultHeight: number,\n getPluginHeight?: (row: T, index: number) => number | undefined,\n): { measuredCount: number; averageHeight: number } {\n let measuredCount = 0;\n let totalMeasured = 0;\n\n for (let i = 0; i < cache.length; i++) {\n const entry = cache[i];\n if (entry.measured) {\n // Only include in average if plugin doesn't provide height for this row\n const pluginHeight = getPluginHeight?.(rows[i], i);\n if (pluginHeight === undefined) {\n totalMeasured += entry.height;\n measuredCount++;\n }\n }\n }\n\n return {\n measuredCount,\n averageHeight: measuredCount > 0 ? totalMeasured / measuredCount : defaultHeight,\n };\n}\n\n// #endregion\n\n// #region Scroll Mapping (max element-height cap)\n\n/**\n * Maximum spacer element height (px) before browsers cap the rendered height.\n *\n * Chromium's hard cap is `2^25 = 33,554,432` px; Firefox/Safari are similar or larger.\n * We pick `33,500,000` — ~54 KB of headroom under Chromium's cap so that floating-point\n * drift in the fractional mapping math (`scrollTop * rMax / sMax`) cannot push a computed\n * spacer position past the engine cap and silently truncate.\n *\n * For datasets where `totalRows * rowHeight` exceeds this value, the faux-vscroll\n * spacer would silently truncate, making the tail of the dataset unreachable via\n * the native scrollbar / `Ctrl+End`. The grid switches to fractional scroll mapping\n * above this threshold — see {@link computeScrollMapping}.\n *\n * @category Plugin Development\n * @since 2.13.0\n */\nexport const MAX_ELEMENT_HEIGHT_PX = 33_500_000;\n\n/**\n * Mapping between native `scrollTop` (clamped spacer space) and \"virtual\" scroll\n * position (raw row-content space). See {@link computeScrollMapping}.\n *\n * @category Plugin Development\n * @since 2.13.0\n */\nexport interface ScrollMapping {\n /** Raw row-content height in pixels (totalRows * rowHeight or sum of variable heights). */\n rawContentHeight: number;\n /** Effective spacer DOM height — `min(rawContentHeight, maxSpacerHeight)`. */\n spacerHeight: number;\n /** Viewport height used for computing scrollable extents. */\n viewportHeight: number;\n /** True when `rawContentHeight > maxSpacerHeight` — fractional mapping is active. */\n capped: boolean;\n}\n\n/**\n * Compute a mapping between the spacer's native scrollTop and the virtual\n * row-content scroll offset.\n *\n * For datasets within `maxSpacerHeight`, mapping is identity (no transform).\n * Above the cap, the spacer is clamped and `scrollTop` units no longer equal\n * row-content units — call {@link toVirtualScrollTop} / {@link fromVirtualScrollTop}\n * to translate between the two coordinate spaces.\n *\n * @category Plugin Development\n * @since 2.13.0\n */\nexport function computeScrollMapping(\n rawContentHeight: number,\n viewportHeight: number,\n maxSpacerHeight = MAX_ELEMENT_HEIGHT_PX,\n): ScrollMapping {\n const spacerHeight = Math.min(rawContentHeight, maxSpacerHeight);\n return {\n rawContentHeight,\n spacerHeight,\n viewportHeight,\n capped: rawContentHeight > maxSpacerHeight,\n };\n}\n\n/**\n * Translate a native `scrollTop` (spacer space) into a virtual scroll offset\n * in raw row-content space. Identity when the mapping is not capped.\n *\n * The result is clamped to `[0, rawContentHeight - viewportHeight]` so callers\n * never index past the dataset, even when the spacer's actual scrollable extent\n * slightly exceeds `spacerHeight - viewportHeight` (e.g. when a horizontal scrollbar\n * adds bottom padding to the faux spacer).\n *\n * @category Plugin Development\n * @since 2.13.0\n */\nexport function toVirtualScrollTop(scrollTop: number, mapping: ScrollMapping): number {\n if (!mapping.capped) return scrollTop;\n const sMax = mapping.spacerHeight - mapping.viewportHeight;\n const rMax = mapping.rawContentHeight - mapping.viewportHeight;\n if (sMax <= 0 || rMax <= 0) return scrollTop;\n const virtual = (scrollTop * rMax) / sMax;\n if (virtual < 0) return 0;\n if (virtual > rMax) return rMax;\n return virtual;\n}\n\n/**\n * Translate a virtual scroll offset (raw row-content space) into a native\n * `scrollTop` value (spacer space). Identity when the mapping is not capped.\n *\n * @category Plugin Development\n * @since 2.13.0\n */\nexport function fromVirtualScrollTop(virtualTop: number, mapping: ScrollMapping): number {\n if (!mapping.capped) return virtualTop;\n const sMax = mapping.spacerHeight - mapping.viewportHeight;\n const rMax = mapping.rawContentHeight - mapping.viewportHeight;\n if (sMax <= 0 || rMax <= 0) return virtualTop;\n return (virtualTop * sMax) / rMax;\n}\n\n/**\n * Identity scroll mapping (no cap applied). Useful as a default in places that\n * don't yet know the dataset extents. `viewportHeight` is `0` until the first\n * `calculateTotalSpacerHeight` call populates the real extents — safe because\n * `capped: false` short-circuits both translation helpers before they read it.\n *\n * @category Plugin Development\n * @since 2.13.0\n */\nexport function createIdentityScrollMapping(): ScrollMapping {\n return { rawContentHeight: 0, spacerHeight: 0, viewportHeight: 0, capped: false };\n}\n\n// #endregion\n\n// #region Scroll Transform\n\n/**\n * Sub-pixel `translateY` for the `.rows` element at a given native scroll position.\n *\n * Bypass mode (all rows rendered) tracks the raw scroll offset directly. Virtualized mode\n * offsets only the remainder past the window's first row, and rounds that start down to an\n * even index so DOM `nth-child(even)` zebra parity keeps matching data-row parity.\n *\n * @param v Virtual state (structural subset of `VirtualState`).\n * @param rawScrollTop Native `scrollTop` of the faux scrollbar (clamped spacer space).\n */\nexport function computeRowsTranslateY(\n v: {\n rowHeight: number;\n bypassThreshold: number;\n variableHeights: boolean;\n positionCache: RowPosition[] | null;\n scrollMapping: ScrollMapping;\n },\n totalRows: number,\n rawScrollTop: number,\n): number {\n if (totalRows <= v.bypassThreshold) return -rawScrollTop;\n\n const currentScrollTop = toVirtualScrollTop(rawScrollTop, v.scrollMapping);\n const cache = v.positionCache;\n let startRowOffset: number;\n\n if (v.variableHeights && cache && cache.length > 0) {\n let rawStart = getRowIndexAtOffset(cache, currentScrollTop);\n if (rawStart === -1) rawStart = 0;\n const evenAlignedStart = rawStart - (rawStart % 2);\n startRowOffset = cache[evenAlignedStart]?.offset ?? evenAlignedStart * v.rowHeight;\n } else {\n const rawStart = Math.floor(currentScrollTop / v.rowHeight);\n startRowOffset = (rawStart - (rawStart % 2)) * v.rowHeight;\n }\n\n return -(currentScrollTop - startRowOffset);\n}\n\n// #endregion\n\n// #region Fixed-Height Virtual Window\n\n/**\n * Result of computing a virtual window for fixed-height rows.\n * Used by plugins like FilteringPlugin for virtualized dropdowns.\n */\nexport interface VirtualWindow {\n /** First row index to render (inclusive) */\n start: number;\n /** Last row index to render (exclusive) */\n end: number;\n /** Pixel offset to apply to the rows container (translateY) */\n offsetY: number;\n /**\n * Effective spacer DOM height — use this for the scrollable spacer element.\n * Equal to `min(totalRows * rowHeight, maxSpacerHeight)`. Above the cap this\n * is clamped; use {@link VirtualWindow.rawContentHeight} for the un-clamped value.\n */\n totalHeight: number;\n /**\n * Raw, un-clamped row-content height (`totalRows * rowHeight`). Equal to\n * `totalHeight` when the dataset is below `maxSpacerHeight`.\n *\n * @since 2.13.0\n */\n rawContentHeight: number;\n}\n\n/** Parameters for computing the virtual window */\nexport interface VirtualWindowParams {\n /** Total number of rows */\n totalRows: number;\n /** Height of the viewport in pixels */\n viewportHeight: number;\n /** Current scroll top position */\n scrollTop: number;\n /** Height of each row in pixels */\n rowHeight: number;\n /** Number of extra rows to render above/below viewport */\n overscan: number;\n /**\n * Optional cap on the spacer's DOM height. When `totalRows * rowHeight` exceeds\n * this value, `scrollTop` is treated as a spacer-space position and translated\n * to virtual row-content space via fractional mapping. Defaults to {@link MAX_ELEMENT_HEIGHT_PX}.\n * Pass `Infinity` to disable.\n *\n * @since 2.13.0\n */\n maxSpacerHeight?: number;\n}\n\n/**\n * Compute the virtual row window based on scroll position and viewport.\n * Simple fixed-height implementation for plugins needing basic virtualization.\n *\n * For datasets where `totalRows * rowHeight > maxSpacerHeight`, scroll position\n * is mapped fractionally so the entire dataset stays reachable past the browser's\n * single-element height cap (Chromium ~33.5M px). See {@link computeScrollMapping}.\n *\n * @param params - Parameters for computing the window\n * @returns VirtualWindow with start/end indices and transforms\n */\nexport function computeVirtualWindow(params: VirtualWindowParams): VirtualWindow {\n const { totalRows, viewportHeight, scrollTop, rowHeight, overscan, maxSpacerHeight = MAX_ELEMENT_HEIGHT_PX } = params;\n\n const visibleRows = Math.ceil(viewportHeight / rowHeight);\n const rawContentHeight = totalRows * rowHeight;\n const mapping = computeScrollMapping(rawContentHeight, viewportHeight, maxSpacerHeight);\n const virtualScrollTop = toVirtualScrollTop(scrollTop, mapping);\n\n // Render overscan rows in each direction (total window = visible + 2*overscan)\n let start = Math.floor(virtualScrollTop / rowHeight) - overscan;\n if (start < 0) start = 0;\n\n let end = start + visibleRows + overscan * 2;\n if (end > totalRows) end = totalRows;\n\n // Ensure start is adjusted if we hit the end\n if (end === totalRows && start > 0) {\n start = Math.max(0, end - visibleRows - overscan * 2);\n }\n\n return {\n start,\n end,\n offsetY: start * rowHeight,\n totalHeight: mapping.spacerHeight,\n rawContentHeight,\n };\n}\n\n/**\n * Determine if virtualization should be bypassed for small datasets.\n * When there are very few items, the overhead of virtualization isn't worth it.\n *\n * @param totalRows - Total number of items\n * @param threshold - Bypass threshold (skip virtualization if totalRows <= threshold)\n * @returns True if virtualization should be bypassed\n */\nexport function shouldBypassVirtualization(totalRows: number, threshold: number): boolean {\n return totalRows <= threshold;\n}\n\n// #endregion\n","/**\n * Central keyboard handler attached to the host element. Manages navigation, paging,\n * and edit lifecycle triggers while respecting active form field interactions.\n */\nimport { FOCUSABLE_EDITOR_SELECTOR, GridClasses } from '../constants';\nimport type { GridHost } from '../types';\nimport { clearCellFocus, isRTL } from './utils';\nimport { readCellField } from './value-accessor';\nimport { fromVirtualScrollTop, toVirtualScrollTop } from './virtualization';\n\n/** Commit active row edit if the editing plugin provides this method. */\nfunction tryCommitEdit(grid: GridHost): void {\n if (typeof grid.commitActiveRowEdit === 'function') grid.commitActiveRowEdit();\n}\n\nfunction isFormField(el: HTMLElement | null): boolean {\n if (!el) return false;\n const tag = el.tagName;\n if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') return true;\n if (el.isContentEditable) return true;\n return false;\n}\n\n/** True while a row-scoped edit session is active. */\nfunction isRowEditing(grid: GridHost): boolean {\n return grid._activeEditRows !== undefined && grid._activeEditRows !== -1;\n}\n\n// #region Keyboard Handler\n/**\n * Guard chain deciding whether this keydown belongs to something other than\n * cell navigation and must be left alone.\n */\nfunction shouldIgnoreKeyDown(grid: GridHost, e: KeyboardEvent, target: HTMLElement | null): boolean {\n // Keyboard events whose target lives inside the grid host but OUTSIDE the\n // rows body (toolpanel inputs/buttons, shell-header controls, light-DOM\n // children of <tbw-grid>) own their own keyboard interactions. Treating\n // ArrowUp/ArrowDown/Enter on such a target as cell navigation steals the\n // user's actual interaction target on the very next render cycle.\n // Cells and the grid host itself remain valid navigation targets.\n if (target && target !== grid && !target.closest?.('.rows-body')) return true;\n\n if (isFormField(target)) {\n switch (e.key) {\n // Home/End and horizontal arrows navigate within the text input; Enter\n // and Escape are handled by the input's own handlers first.\n case 'Home':\n case 'End':\n case 'ArrowLeft':\n case 'ArrowRight':\n case 'Enter':\n case 'Escape':\n return true;\n case 'ArrowUp':\n case 'ArrowDown':\n // Number spinners own the vertical arrows; other fields fall through.\n if ((target as HTMLInputElement).tagName === 'INPUT' && (target as HTMLInputElement).type === 'number') {\n return true;\n }\n break;\n }\n }\n\n const colType = grid._visibleColumns[grid._focusCol]?.type;\n return isRowEditing(grid) && colType === 'select' && (e.key === 'ArrowDown' || e.key === 'ArrowUp');\n}\n\n/** Tab / Shift+Tab: advance one cell, wrapping to the next/previous row. */\nfunction navigateTab(grid: GridHost, e: KeyboardEvent, maxRow: number, maxCol: number): void {\n e.preventDefault();\n if (!e.shiftKey) {\n if (grid._focusCol < maxCol) {\n grid._focusCol += 1;\n return;\n }\n tryCommitEdit(grid);\n if (grid._focusRow < maxRow) {\n grid._focusRow += 1;\n grid._focusCol = 0;\n }\n return;\n }\n if (grid._focusCol > 0) {\n grid._focusCol -= 1;\n } else if (grid._focusRow > 0) {\n if (grid._activeEditRows === grid._focusRow) tryCommitEdit(grid);\n grid._focusRow -= 1;\n grid._focusCol = maxCol;\n }\n}\n\n/**\n * ArrowLeft/ArrowRight. `towardEnd` is the LOGICAL direction (ArrowRight); in\n * RTL the physical arrow maps to the opposite column index.\n */\nfunction navigateHorizontal(grid: GridHost, e: KeyboardEvent, maxCol: number, towardEnd: boolean): void {\n const forward = isRTL(grid) ? !towardEnd : towardEnd;\n grid._focusCol = forward ? Math.min(maxCol, grid._focusCol + 1) : Math.max(0, grid._focusCol - 1);\n e.preventDefault();\n}\n\n/** Home/End (plus Ctrl/Cmd variants which also jump to the first/last row). */\nfunction navigateRowEdge(grid: GridHost, e: KeyboardEvent, maxRow: number, maxCol: number, toEnd: boolean): void {\n if (e.ctrlKey || e.metaKey) {\n if (isRowEditing(grid)) tryCommitEdit(grid);\n grid._focusRow = toEnd ? maxRow : 0;\n }\n grid._focusCol = toEnd ? maxCol : 0;\n e.preventDefault();\n ensureCellVisible(grid, toEnd ? { forceScrollRight: true } : { forceScrollLeft: true });\n}\n\n/** Dispatch the unified `cell-activate` event. Returns true when cancelled. */\nfunction emitCellActivate(grid: GridHost, e: KeyboardEvent): boolean {\n const rowIndex = grid._focusRow;\n const colIndex = grid._focusCol;\n const column = grid._visibleColumns[colIndex];\n const row = grid._rows[rowIndex];\n const field = column?.field ?? '';\n const activateEvent = new CustomEvent('cell-activate', {\n cancelable: true,\n detail: {\n rowIndex,\n colIndex,\n column,\n field,\n value: field && row ? readCellField(row, field) : undefined,\n row,\n cellEl: grid.querySelector(`[data-row=\"${rowIndex}\"][data-col=\"${colIndex}\"]`) as HTMLElement | undefined,\n trigger: 'keyboard' as const,\n originalEvent: e,\n },\n });\n grid.dispatchEvent(activateEvent);\n return activateEvent.defaultPrevented;\n}\n\nexport function handleGridKeyDown(grid: GridHost, e: KeyboardEvent): void {\n // Dispatch to plugin system first - if any plugin handles it, stop here\n if (grid._dispatchKeyDown?.(e)) return;\n\n const path = e.composedPath?.() ?? [];\n const target = (path.length ? path[0] : e.target) as HTMLElement | null;\n if (shouldIgnoreKeyDown(grid, e, target)) return;\n\n const maxRow = grid._rows.length - 1;\n const maxCol = grid._visibleColumns.length - 1;\n\n switch (e.key) {\n case 'Tab':\n navigateTab(grid, e, maxRow, maxCol);\n break;\n case 'ArrowDown':\n if (isRowEditing(grid)) tryCommitEdit(grid);\n grid._focusRow = Math.min(maxRow, grid._focusRow + 1);\n e.preventDefault();\n break;\n case 'ArrowUp':\n if (isRowEditing(grid)) tryCommitEdit(grid);\n grid._focusRow = Math.max(0, grid._focusRow - 1);\n e.preventDefault();\n break;\n case 'ArrowRight':\n navigateHorizontal(grid, e, maxCol, true);\n break;\n case 'ArrowLeft':\n navigateHorizontal(grid, e, maxCol, false);\n break;\n case 'Home':\n navigateRowEdge(grid, e, maxRow, maxCol, false);\n return;\n case 'End':\n navigateRowEdge(grid, e, maxRow, maxCol, true);\n return;\n case 'PageDown':\n grid._focusRow = Math.min(maxRow, grid._focusRow + 20);\n e.preventDefault();\n break;\n case 'PageUp':\n grid._focusRow = Math.max(0, grid._focusRow - 20);\n e.preventDefault();\n break;\n // NOTE: Enter is normally handled by EditingPlugin. If no plugin handled\n // it, dispatch the unified cell-activate event for custom handling.\n case 'Enter':\n if (emitCellActivate(grid, e)) {\n e.preventDefault();\n return;\n }\n break;\n default:\n return;\n }\n ensureCellVisible(grid);\n}\n// #endregion\n\n// #region Cell Visibility\n/**\n * Options for ensureCellVisible to control scroll behavior.\n */\ninterface EnsureCellVisibleOptions {\n /** Force scroll to the leftmost position (for Home key) */\n forceScrollLeft?: boolean;\n /** Force scroll to the rightmost position (for End key) */\n forceScrollRight?: boolean;\n /** Force horizontal scroll even in edit mode (for Tab navigation) */\n forceHorizontalScroll?: boolean;\n}\n\n/**\n * Vertical: scroll the virtualized container so the focused row is in view.\n *\n * `y` is in raw row-content space (rowHeight × index). Above the browser height\n * cap (#326), `scrollEl.scrollTop` is in clamped spacer space — the two\n * coordinate systems are not interchangeable, so translate scrollTop into\n * virtual space for the comparison and back into native space when writing.\n * For sub-cap datasets the mapping is identity, so this is a no-op.\n *\n * Plugins that paint over the viewport (sticky rows) report the space they\n * obscure via `_getVerticalScrollOffsets`, so the row lands clear of the\n * overlay instead of underneath it — WCAG 2.2 SC 2.4.11 Focus Not Obscured.\n */\nfunction scrollFocusedRowIntoView(grid: GridHost): void {\n if (!grid._virtualization?.enabled) return;\n const { rowHeight, container, viewportEl, scrollMapping } = grid._virtualization;\n // container is the faux scrollbar element that handles actual scrolling;\n // viewportEl is the visible area element that has the correct height.\n const scrollEl = container as HTMLElement | undefined;\n const visibleHeight = viewportEl?.clientHeight ?? scrollEl?.clientHeight ?? 0;\n if (!scrollEl || visibleHeight <= 0) return;\n\n const offsets = grid._getVerticalScrollOffsets?.(grid._focusRow) ?? { top: 0, bottom: 0 };\n if (offsets.skipScroll) return;\n // A malformed or oversized report must never invert the visible band.\n const top = Math.max(0, offsets.top);\n const bottom = Math.max(0, offsets.bottom);\n const usableHeight = visibleHeight - top - bottom;\n if (usableHeight <= 0) return;\n\n const y = grid._focusRow * rowHeight;\n const virtualScrollTop = scrollMapping ? toVirtualScrollTop(scrollEl.scrollTop, scrollMapping) : scrollEl.scrollTop;\n if (y < virtualScrollTop + top) {\n const target = Math.max(0, y - top);\n scrollEl.scrollTop = scrollMapping ? fromVirtualScrollTop(target, scrollMapping) : target;\n } else if (y + rowHeight > virtualScrollTop + top + usableHeight) {\n const target = Math.max(0, y - usableHeight + rowHeight - top);\n scrollEl.scrollTop = scrollMapping ? fromVirtualScrollTop(target, scrollMapping) : target;\n }\n}\n\n/**\n * Resolve the rendered cell for the focused row/col, or `undefined` when the\n * focused row is outside the current virtual window.\n */\nfunction findFocusedCell(grid: GridHost): { rowEl: HTMLElement | null; cell: HTMLElement } | undefined {\n const rowIndex = grid._focusRow;\n const vStart = grid._virtualization.start ?? 0;\n const vEnd = grid._virtualization.end ?? grid._rows.length;\n if (rowIndex < vStart || rowIndex >= vEnd) return undefined;\n\n const rowEl = grid._bodyEl.querySelectorAll('.data-grid-row')[rowIndex - vStart] as HTMLElement | null;\n // Try exact column match first, then query by data-col, then fall back to the\n // first cell (full-width group rows).\n let cell = rowEl?.children[grid._focusCol] as HTMLElement | undefined;\n if (!cell || !cell.classList?.contains('cell')) {\n cell = (rowEl?.querySelector(`.cell[data-col=\"${grid._focusCol}\"]`) ?? rowEl?.querySelector('.cell[data-col]')) as\n HTMLElement | undefined;\n }\n return cell ? { rowEl: rowEl ?? null, cell } : undefined;\n}\n\n/** Horizontal: bring the focused cell into the `.tbw-scroll-area` viewport. */\nfunction scrollCellIntoViewHorizontally(\n grid: GridHost,\n rowEl: HTMLElement | null,\n cell: HTMLElement,\n options?: EnsureCellVisibleOptions,\n): void {\n const scrollArea = grid.querySelector('.tbw-scroll-area') as HTMLElement | null;\n if (!scrollArea) return;\n\n // Home/End always scroll to the edge.\n if (options?.forceScrollLeft) {\n scrollArea.scrollLeft = 0;\n return;\n }\n if (options?.forceScrollRight) {\n scrollArea.scrollLeft = scrollArea.scrollWidth - scrollArea.clientWidth;\n return;\n }\n\n // Plugins (e.g. pinned columns) report how much of the scroll area they\n // obscure, and whether the focused cell should skip scrolling entirely\n // (pinned cells are always visible).\n const offsets = grid._getHorizontalScrollOffsets?.(rowEl ?? undefined, cell) ?? { left: 0, right: 0 };\n if (offsets.skipScroll) return;\n\n const cellRect = cell.getBoundingClientRect();\n const scrollAreaRect = scrollArea.getBoundingClientRect();\n const cellLeft = cellRect.left - scrollAreaRect.left + scrollArea.scrollLeft;\n const cellRight = cellLeft + cellRect.width;\n const visibleLeft = scrollArea.scrollLeft + offsets.left;\n const visibleRight = scrollArea.scrollLeft + scrollArea.clientWidth - offsets.right;\n if (cellLeft < visibleLeft) {\n scrollArea.scrollLeft = cellLeft - offsets.left;\n } else if (cellRight > visibleRight) {\n scrollArea.scrollLeft = cellRight - scrollArea.clientWidth + offsets.right;\n }\n}\n\n/** Move real DOM focus to the editor, the cell, or the grid host. */\nfunction applyFocusTarget(grid: GridHost, cell: HTMLElement, isEditing: boolean): void {\n if (isEditing && cell.classList.contains(GridClasses.EDITING)) {\n // Editing cell: focus the editor input inside it\n const focusTarget = cell.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n if (focusTarget && document.activeElement !== focusTarget) {\n try {\n focusTarget.focus({ preventScroll: true });\n } catch {\n /* empty */\n }\n }\n return;\n }\n\n if (isEditing) {\n // Active edit row but this cell isn't the editing cell — focus it so Tab\n // navigation within the row can attach editors.\n if (cell.contains(document.activeElement)) return;\n if (!cell.hasAttribute('tabindex')) cell.setAttribute('tabindex', '-1');\n try {\n cell.focus({ preventScroll: true });\n } catch {\n /* empty */\n }\n return;\n }\n\n // NOT editing: keep focus on the grid element (tabindex=0) rather than\n // individual cells. In a virtualized grid, cells can be detached by\n // subsequent render cycles (e.g., SelectionPlugin's requestAfterRender\n // → RAF → row recycling). A detached focused cell causes activeElement\n // to revert to <body>, breaking keyboard navigation.\n // Visual focus is managed by the .cell-focus CSS class + data-has-focus.\n //\n // BUT: don't steal focus from a real focused descendant (toolpanel\n // input, shell-header button, registered overlay control). Cell focus\n // is virtual; if the user is actively typing in a non-cell input, we\n // must leave that input alone. We only reclaim focus when nothing\n // meaningful inside the grid currently holds it (active element is\n // outside grid, on the grid host itself, or on a bare cell).\n const active = document.activeElement;\n const meaningful =\n active instanceof HTMLElement &&\n active !== grid &&\n typeof grid.contains === 'function' &&\n grid.contains(active) &&\n !active.classList.contains('cell') &&\n !active.closest('.cell');\n if (!meaningful && active !== grid) {\n grid.focus({ preventScroll: true });\n }\n}\n\n/**\n * Scroll the viewport (virtualized or static) so the focused cell's row is visible\n * and apply visual focus styling / tabindex management.\n */\nexport function ensureCellVisible(grid: GridHost, options?: EnsureCellVisibleOptions): void {\n scrollFocusedRowIntoView(grid);\n\n const isEditing = isRowEditing(grid) || !!grid._isGridEditMode;\n // Skip refreshVirtualWindow when in edit mode to avoid wiping editors\n if (!isEditing) grid.refreshVirtualWindow(false);\n\n clearCellFocus(grid._bodyEl);\n // Clear previous aria-selected markers\n Array.from(grid._bodyEl.querySelectorAll('[aria-selected=\"true\"]')).forEach((el) => {\n el.setAttribute('aria-selected', 'false');\n });\n\n const focused = findFocusedCell(grid);\n if (!focused) return;\n const { rowEl, cell } = focused;\n\n cell.classList.add('cell-focus');\n cell.setAttribute('aria-selected', 'true');\n\n // Skip horizontal scrolling in edit mode to prevent scroll jumps when editors\n // are created — unless forceHorizontalScroll is set (Tab while editing).\n if (!isEditing || options?.forceHorizontalScroll) {\n scrollCellIntoViewHorizontally(grid, rowEl, cell, options);\n }\n\n applyFocusTarget(grid, cell, isEditing);\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, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\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 * 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","/**\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 * Editing Plugin Styles\n *\n * These styles are injected into the document when the EditingPlugin is loaded.\n * CSS custom properties use fallbacks to core grid variables for consistency.\n * Uses CSS nesting for scoping to tbw-grid elements.\n */\n\n@layer tbw-plugins {\n /* ============================================================================\n CSS Custom Properties for Editing\n ============================================================================\n These are defined here so they can be overridden by consumers.\n They reference core grid variables with sensible defaults.\n ============================================================================ */\n tbw-grid {\n /* Editing cell/row backgrounds */\n --tbw-editing-bg: var(--tbw-color-selection);\n --tbw-editing-row-bg: var(--tbw-editing-bg);\n\n /* Editing input styling */\n --tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));\n --tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);\n --tbw-font-size-editor: inherit;\n\n /* Row outline when editing */\n --tbw-editing-row-outline-color: var(--tbw-color-accent);\n --tbw-editing-row-outline-width: 1px;\n\n /* ============================================================================\n Row Editing State\n ============================================================================ */\n\n /* Highlight entire row when any cell is being edited (only in row mode, not grid mode) */\n &:not(.tbw-grid-mode) .data-grid-row:has(.editing) {\n background: var(--tbw-editing-row-bg);\n outline: var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);\n outline-offset: calc(-1 * var(--tbw-editing-row-outline-width));\n }\n\n /* ============================================================================\n Cell Editing State\n ============================================================================ */\n\n /* Cell in edit mode */\n .data-grid-row > .cell.editing {\n overflow: hidden;\n padding: 0;\n /* Override block to flex for editing inputs */\n display: flex;\n /* Match the non-editing cell height exactly. Non-editing height is:\n max(--tbw-row-height [border-box], line-height + padding + border [content-driven])\n Since editing cells have padding:0, min-height must compensate for both cases:\n - Content-driven: line-height (1lh) + original vertical padding + border\n - Min-height-driven: just var(--tbw-row-height) (border-box already includes padding+border) */\n min-height: max(\n var(--tbw-row-height),\n calc(1lh + 2 * var(--tbw-cell-padding-v, 0.25em) + var(--tbw-border-width, 1px))\n );\n align-items: center;\n justify-content: center;\n }\n\n /* Standard form inputs inside editing cells */\n .data-grid-row > .cell.editing input:not([type='checkbox']),\n .data-grid-row > .cell.editing select,\n .data-grid-row > .cell.editing textarea {\n width: 100%;\n height: 100%;\n flex: 1 1 auto;\n align-self: stretch;\n min-width: 0;\n border: var(--tbw-editing-border);\n padding: var(--tbw-padding-editing-input);\n font-size: var(--tbw-font-size-editor);\n }\n\n /* ============================================================================\n Editor Host\n ============================================================================ */\n\n /* Editor host wrapper uses display:contents to let editor fill cell */\n .tbw-editor-host {\n display: contents;\n }\n\n /* ============================================================================\n Changed Row Indicator\n ============================================================================ */\n\n /* Visual indicator for rows that have been modified */\n .data-grid-row.changed {\n /* Could add a left border or background tint here */\n }\n\n /* ============================================================================\n Invalid Cell Indicator\n ============================================================================ */\n\n /* Default invalid cell color - can be overridden by consumers */\n --tbw-invalid-bg: light-dark(#fef2f2, #450a0a);\n --tbw-invalid-border-color: light-dark(#ef4444, #f87171);\n\n /* Visual indicator for cells marked as invalid */\n .data-grid-row > .cell[data-invalid='true'] {\n background: var(--tbw-invalid-bg);\n outline: 1px solid var(--tbw-invalid-border-color);\n outline-offset: -1px;\n }\n }\n} /* End @layer tbw-plugins */\n","/**\n * Default Editors Module\n *\n * Provides built-in editor factories for different column types.\n * Each editor type has its own factory function for consistency and readability.\n *\n * IMPORTANT: Editor factories should NOT call focus() on elements - they are called\n * before the element is appended to the DOM. The calling code (beginBulkEdit,\n * inlineEnterEdit) is responsible for focusing the correct editor after insertion.\n */\n\nimport type { ColumnConfig, ColumnEditorContext } from '../../core/types';\nimport type { DateEditorParams, NumberEditorParams, SelectEditorParams, TextEditorParams } from './types';\n\n// ============================================================================\n// Type Aliases\n// ============================================================================\n\n/** Option shape used by select editor (matches column.options) */\ntype ColumnOption = { label: string; value: unknown };\n\n/** Column with any row type (used for editor factories) */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyColumn = ColumnConfig<any>;\n\n// ============================================================================\n// Utilities\n// ============================================================================\n\n/** Resolve column.options (handles both array and function forms) */\nfunction resolveOptions(column: AnyColumn): ColumnOption[] {\n const raw = column.options;\n if (!raw) return [];\n return typeof raw === 'function' ? raw() : raw;\n}\n\n/** Format a Date as YYYY-MM-DD string */\nfunction toISODate(date: Date): string {\n const y = date.getFullYear();\n const m = String(date.getMonth() + 1).padStart(2, '0');\n const d = String(date.getDate()).padStart(2, '0');\n return `${y}-${m}-${d}`;\n}\n\n// ============================================================================\n// Editor Factories\n// ============================================================================\n\n/** Creates a number input editor */\nfunction createNumberEditor(column: AnyColumn): (ctx: ColumnEditorContext) => HTMLElement {\n return (ctx) => {\n const params = column.editorParams as NumberEditorParams | undefined;\n const input = document.createElement('input');\n input.type = 'number';\n input.value = ctx.value != null ? String(ctx.value) : '';\n\n if (params?.min !== undefined) input.min = String(params.min);\n if (params?.max !== undefined) input.max = String(params.max);\n if (params?.step !== undefined) input.step = String(params.step);\n if (params?.placeholder) input.placeholder = params.placeholder;\n\n const commit = () => {\n if (input.value === '') {\n if (column.nullable) {\n ctx.commit(null);\n } else {\n // Non-nullable: fall back to min value or 0\n ctx.commit(params?.min ?? 0);\n }\n } else {\n ctx.commit(Number(input.value));\n }\n };\n input.addEventListener('blur', commit);\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Enter') commit();\n if (e.key === 'Escape') ctx.cancel();\n });\n\n return input;\n };\n}\n\n/** Creates a checkbox editor for boolean values */\nfunction createBooleanEditor(): (ctx: ColumnEditorContext) => HTMLElement {\n return (ctx) => {\n const input = document.createElement('input');\n input.type = 'checkbox';\n input.checked = !!ctx.value;\n input.addEventListener('change', () => ctx.commit(input.checked));\n return input;\n };\n}\n\n/** Creates a date input editor */\nfunction createDateEditor(column: AnyColumn): (ctx: ColumnEditorContext) => HTMLElement {\n return (ctx) => {\n const params = column.editorParams as DateEditorParams | undefined;\n const input = document.createElement('input');\n input.type = 'date';\n\n // Set initial value - handle both Date objects and string dates\n if (ctx.value instanceof Date) {\n input.valueAsDate = ctx.value;\n } else if (typeof ctx.value === 'string' && ctx.value) {\n // String date like \"2019-10-09\" - set directly as value\n input.value = ctx.value.split('T')[0]; // Handle ISO strings too\n }\n if (params?.min) input.min = params.min;\n if (params?.max) input.max = params.max;\n if (params?.placeholder) input.placeholder = params.placeholder;\n\n // Commit function preserves original type (string vs Date)\n const commit = () => {\n if (!input.value) {\n if (column.nullable) {\n ctx.commit(null);\n } else {\n // Non-nullable: use configured default or today\n const fallback = params?.default;\n if (typeof ctx.value === 'string' || typeof fallback === 'string') {\n // String mode: use default string or today as YYYY-MM-DD\n ctx.commit(typeof fallback === 'string' ? fallback : toISODate(fallback ?? new Date()));\n } else {\n // Date object mode\n ctx.commit(fallback instanceof Date ? fallback : new Date());\n }\n }\n return;\n }\n if (typeof ctx.value === 'string') {\n // Original was string, return string in YYYY-MM-DD format\n ctx.commit(input.value);\n } else {\n ctx.commit(input.valueAsDate);\n }\n };\n\n input.addEventListener('change', commit);\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') ctx.cancel();\n });\n\n return input;\n };\n}\n\n/** Sentinel value used internally to identify the nullable \"(Blank)\" option */\nconst NULLABLE_BLANK_VALUE = '__tbw_null__';\n\n/** Creates a select dropdown editor */\nfunction createSelectEditor(column: AnyColumn): (ctx: ColumnEditorContext) => HTMLElement {\n return (ctx) => {\n const params = column.editorParams as SelectEditorParams | undefined;\n const select = document.createElement('select');\n if (column.multi) select.multiple = true;\n\n // Add blank option: nullable columns always get one, otherwise respect includeEmpty\n const showBlank = column.nullable || params?.includeEmpty;\n if (showBlank) {\n const emptyOpt = document.createElement('option');\n emptyOpt.value = column.nullable ? NULLABLE_BLANK_VALUE : '';\n emptyOpt.textContent = column.nullable ? (params?.emptyLabel ?? '(Blank)') : (params?.emptyLabel ?? '');\n if (ctx.value == null) emptyOpt.selected = true;\n select.appendChild(emptyOpt);\n }\n\n // Populate options from column.options\n const options = resolveOptions(column);\n options.forEach((opt) => {\n const o = document.createElement('option');\n o.value = String(opt.value);\n o.textContent = opt.label;\n if (column.multi && Array.isArray(ctx.value) && ctx.value.includes(opt.value)) {\n o.selected = true;\n } else if (!column.multi && ctx.value === opt.value) {\n o.selected = true;\n }\n select.appendChild(o);\n });\n\n const commit = () => {\n if (column.multi) {\n const values = Array.from(select.selectedOptions).map((o) => o.value);\n ctx.commit(values);\n } else if (column.nullable && select.value === NULLABLE_BLANK_VALUE) {\n ctx.commit(null);\n } else {\n ctx.commit(select.value);\n }\n };\n\n select.addEventListener('change', commit);\n select.addEventListener('blur', commit);\n select.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') ctx.cancel();\n });\n\n return select;\n };\n}\n\n/** Creates a text input editor (default) */\nfunction createTextEditor(column: AnyColumn): (ctx: ColumnEditorContext) => HTMLElement {\n return (ctx) => {\n const params = column.editorParams as TextEditorParams | undefined;\n const input = document.createElement('input');\n input.type = 'text';\n input.value = ctx.value != null ? String(ctx.value) : '';\n\n if (params?.maxLength !== undefined) input.maxLength = params.maxLength;\n if (params?.pattern) input.pattern = params.pattern;\n if (params?.placeholder) input.placeholder = params.placeholder;\n\n // Commit function preserves original type when possible\n const commit = () => {\n const inputVal = input.value;\n\n // Empty input handling\n if (inputVal === '') {\n if (column.nullable) {\n ctx.commit(null);\n } else {\n // Non-nullable: commit empty string so the field is never null\n ctx.commit('');\n }\n return;\n }\n\n // Preserve values with characters that <input> can't represent (newlines, etc.).\n // If stripping those characters produces the same string, the user didn't change anything.\n if (typeof ctx.value === 'string' && inputVal === ctx.value.replace(/[\\n\\r]/g, '')) {\n return;\n }\n // Preserve numeric type for custom column types (e.g., currency)\n if (typeof ctx.value === 'number') {\n ctx.commit(Number(inputVal));\n } else {\n ctx.commit(inputVal);\n }\n };\n\n input.addEventListener('blur', commit);\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Enter') commit();\n if (e.key === 'Escape') ctx.cancel();\n });\n\n return input;\n };\n}\n\n// ============================================================================\n// Main Entry Point\n// ============================================================================\n\n/**\n * Returns a default editor factory function for the given column type.\n * Each editor handles commit on blur/Enter, and cancel on Escape.\n *\n * Note: Focus is NOT called here - the calling code handles focusing after DOM insertion.\n * @since 0.4.0\n */\nexport function defaultEditorFor(column: AnyColumn): (ctx: ColumnEditorContext) => HTMLElement | string {\n switch (column.type) {\n case 'number':\n return createNumberEditor(column);\n case 'boolean':\n return createBooleanEditor();\n case 'date':\n return createDateEditor(column);\n case 'select':\n return createSelectEditor(column);\n default:\n return createTextEditor(column);\n }\n}\n\n// ============================================================================\n// Utility Export (used by EditingPlugin)\n// ============================================================================\n\n/**\n * Resolve a numeric editor value. Empty input falls back to `null` for nullable\n * columns, otherwise to the configured `min` (or `0`).\n */\nfunction readNumericValue(raw: string, column?: AnyColumn): unknown {\n if (raw === '') {\n if (column?.nullable) return null;\n const params = column?.editorParams as NumberEditorParams | undefined;\n return params?.min ?? 0;\n }\n return Number(raw);\n}\n\n/**\n * Resolve a `<input type=\"date\">` value, preserving the original value's type\n * (string dates stay `YYYY-MM-DD` strings, Date objects stay `Date`).\n */\nfunction readDateValue(input: HTMLInputElement, column?: AnyColumn, originalValue?: unknown): unknown {\n if (!input.value) {\n if (column?.nullable) return null;\n // Non-nullable: preserve original or fall back to today\n if (typeof originalValue === 'string') return originalValue || new Date().toISOString().slice(0, 10);\n return (originalValue as Date) ?? new Date();\n }\n // Preserve original type: if original was a string, return string (YYYY-MM-DD format)\n if (typeof originalValue === 'string') {\n return input.value; // input.value is already in YYYY-MM-DD format\n }\n return input.valueAsDate;\n}\n\n/**\n * Resolve a plain text `<input>` value, preserving numeric originals and values\n * containing characters `<input>` cannot represent.\n */\nfunction readTextInputValue(input: HTMLInputElement, column?: AnyColumn, originalValue?: unknown): unknown {\n // For text inputs, check if original value was a number to preserve type\n if (typeof originalValue === 'number') return readNumericValue(input.value, column);\n // Nullable text: empty → null; non-nullable: empty → ''\n if (input.value === '' && (originalValue === null || originalValue === undefined)) {\n return column?.nullable ? null : '';\n }\n // Preserve values with characters <input> can't represent (newlines, etc.)\n if (typeof originalValue === 'string' && input.value === originalValue.replace(/[\\n\\r]/g, '')) {\n return originalValue;\n }\n return input.value;\n}\n\n/**\n * Resolve a `<textarea>` / `<select>` value using the column type or the\n * original value's type.\n */\nfunction readTextControlValue(\n input: HTMLTextAreaElement | HTMLSelectElement,\n column?: AnyColumn,\n originalValue?: unknown,\n): unknown {\n // Check column type OR original value type — preserves numeric type for\n // custom column types (e.g., currency).\n if (input.value !== '' && (column?.type === 'number' || typeof originalValue === 'number')) {\n return Number(input.value);\n }\n // Nullable: empty → null; non-nullable: empty → ''\n if ((originalValue === null || originalValue === undefined) && input.value === '') {\n return column?.nullable ? null : '';\n }\n return input.value;\n}\n\n/**\n * Get the typed value from an input element based on its type, column config, and original value.\n * Preserves the type of the original value (e.g., numeric currency values stay as numbers,\n * string dates stay as strings, null/undefined for empty fields).\n */\nexport function getInputValue(\n input: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n column?: AnyColumn,\n originalValue?: unknown,\n): unknown {\n if (!(input instanceof HTMLInputElement)) return readTextControlValue(input, column, originalValue);\n switch (input.type) {\n case 'checkbox':\n return input.checked;\n case 'number':\n return readNumericValue(input.value, column);\n case 'date':\n return readDateValue(input, column, originalValue);\n default:\n return readTextInputValue(input, column, originalValue);\n }\n}\n","/**\n * Cell Validation Manager\n *\n * Manages invalid-cell state for the Editing Plugin.\n * Extracted from EditingPlugin to reduce the main plugin file size.\n *\n * The manager owns the `Map<rowId, Map<field, message>>` state and exposes\n * read/write methods. DOM synchronization is handled via an injected callback.\n *\n * @internal\n */\n\n/** Callback to sync the data-invalid attribute on a cell element in the DOM. */\nexport type SyncInvalidAttributeFn = (rowId: string, field: string, invalid: boolean) => void;\n\n/**\n * Manages validation state for grid cells.\n *\n * Tracks which cells are marked invalid and their validation messages.\n * The DOM side-effect (adding/removing `data-invalid` attribute) is delegated\n * to the `syncAttribute` callback provided at construction time.\n */\nexport class CellValidationManager {\n /** Invalid cell tracking: Map<rowId, Map<field, message>> */\n readonly #cells = new Map<string, Map<string, string>>();\n\n /** Callback to sync DOM attributes when validation state changes */\n readonly #syncAttribute: SyncInvalidAttributeFn;\n\n constructor(syncAttribute: SyncInvalidAttributeFn) {\n this.#syncAttribute = syncAttribute;\n }\n\n // #region Write Operations\n\n /**\n * Mark a cell as invalid with an optional validation message.\n *\n * @param rowId - The row ID (from getRowId)\n * @param field - The field name\n * @param message - Optional validation message (for tooltips or display)\n */\n setInvalid(rowId: string, field: string, message = ''): void {\n let rowInvalids = this.#cells.get(rowId);\n if (!rowInvalids) {\n rowInvalids = new Map();\n this.#cells.set(rowId, rowInvalids);\n }\n rowInvalids.set(field, message);\n this.#syncAttribute(rowId, field, true);\n }\n\n /**\n * Clear the invalid state for a specific cell.\n *\n * @param rowId - The row ID (from getRowId)\n * @param field - The field name\n */\n clearInvalid(rowId: string, field: string): void {\n const rowInvalids = this.#cells.get(rowId);\n if (rowInvalids) {\n rowInvalids.delete(field);\n if (rowInvalids.size === 0) {\n this.#cells.delete(rowId);\n }\n }\n this.#syncAttribute(rowId, field, false);\n }\n\n /**\n * Clear all invalid cells for a specific row.\n *\n * @param rowId - The row ID (from getRowId)\n */\n clearRowInvalid(rowId: string): void {\n const rowInvalids = this.#cells.get(rowId);\n if (rowInvalids) {\n const fields = Array.from(rowInvalids.keys());\n this.#cells.delete(rowId);\n fields.forEach((field) => this.#syncAttribute(rowId, field, false));\n }\n }\n\n /**\n * Clear all invalid cell states across all rows.\n */\n clearAllInvalid(): void {\n const entries = Array.from(this.#cells.entries());\n this.#cells.clear();\n entries.forEach(([rowId, fields]) => {\n fields.forEach((_, field) => this.#syncAttribute(rowId, field, false));\n });\n }\n\n // #endregion\n\n // #region Read Operations\n\n /**\n * Check if a specific cell is marked as invalid.\n *\n * @param rowId - The row ID (from getRowId)\n * @param field - The field name\n * @returns True if the cell is marked as invalid\n */\n isCellInvalid(rowId: string, field: string): boolean {\n return this.#cells.get(rowId)?.has(field) ?? false;\n }\n\n /**\n * Get the validation message for an invalid cell.\n *\n * @param rowId - The row ID (from getRowId)\n * @param field - The field name\n * @returns The validation message, or undefined if cell is valid\n */\n getInvalidMessage(rowId: string, field: string): string | undefined {\n return this.#cells.get(rowId)?.get(field);\n }\n\n /**\n * Check if a row has any invalid cells.\n *\n * @param rowId - The row ID (from getRowId)\n * @returns True if the row has at least one invalid cell\n */\n hasInvalidCells(rowId: string): boolean {\n const rowInvalids = this.#cells.get(rowId);\n return rowInvalids ? rowInvalids.size > 0 : false;\n }\n\n /**\n * Get all invalid fields for a row.\n *\n * @param rowId - The row ID (from getRowId)\n * @returns Map of field names to validation messages\n */\n getInvalidFields(rowId: string): Map<string, string> {\n return new Map(this.#cells.get(rowId) ?? []);\n }\n\n // #endregion\n}\n","/**\n * Pure functions for dirty tracking baseline management.\n *\n * Extracted from EditingPlugin to keep the plugin under the 2,000 line target.\n * All functions are stateless — the caller owns the baseline `Map`.\n *\n * @internal\n */\n\nimport { readCellField } from '../../../core/internal/value-accessor';\n\n// #region Types\n\n/**\n * Detail for `dirty-change` custom events.\n * @since 1.23.0\n */\nexport interface DirtyChangeDetail<T = unknown> {\n /** Row ID (from getRowId) */\n rowId: string;\n /** Current row data */\n row: T;\n /** Baseline (original) row data, or undefined for newly inserted rows */\n original: T | undefined;\n /**\n * Transition type:\n * - `'modified'` — row differs from baseline\n * - `'new'` — row was inserted via `insertRow()` and has no baseline\n * - `'reverted'` — row was reverted to baseline via `revertRow()`\n * - `'pristine'` — row was explicitly marked pristine via `markAsPristine()`\n */\n type: 'modified' | 'new' | 'reverted' | 'pristine';\n}\n\n/**\n * Result of getDirtyRows(): each entry has the row ID, original (baseline),\n * and current data.\n * @since 1.23.0\n */\nexport interface DirtyRowEntry<T = unknown> {\n id: string;\n /** The original (baseline) row data, or `undefined` for newly inserted rows. */\n original: T | undefined;\n current: T;\n}\n\n/**\n * Detail for `baselines-captured` custom events.\n *\n * Emitted after the render pipeline completes when new baseline snapshots\n * were captured during `processRows`.\n * @since 1.23.0\n */\nexport interface BaselinesCapturedDetail {\n /** Total number of tracked baselines (not just newly captured). */\n count: number;\n}\n\n// #endregion\n\n// #region Baseline Capture\n\n/**\n * Capture baselines for rows not already tracked (first-write-wins).\n *\n * Uses `structuredClone` for deep copy so nested objects cannot be mutated\n * through shared references.\n *\n * @param baselines - Map of rowId → deep-cloned baseline row data\n * @param rows - Rows to snapshot\n * @param getRowId - Function to resolve row ID (may throw; exceptions are swallowed)\n */\nexport function captureBaselines<T>(\n baselines: Map<string, T>,\n rows: readonly T[],\n getRowId: (row: T) => string | undefined,\n): void {\n for (const row of rows) {\n try {\n const id = getRowId(row);\n if (id != null && !baselines.has(id)) {\n baselines.set(id, structuredClone(row));\n }\n } catch {\n // Row has no resolvable ID — skip\n }\n }\n}\n\n// #endregion\n\n// #region Dirty Detection\n\n/**\n * Check whether a row's current data differs from its baseline.\n *\n * Uses deep property comparison so that `structuredClone`'d baselines\n * with nested objects/arrays/Dates compare correctly.\n */\nexport function isRowDirty<T>(baselines: Map<string, T>, rowId: string, currentRow: T): boolean {\n const baseline = baselines.get(rowId);\n if (!baseline) return false; // No baseline → row is \"new\" or untracked\n return !deepEqual(baseline, currentRow);\n}\n\n/**\n * Check whether a single cell (field) differs from its baseline value.\n *\n * Returns `false` when no baseline exists for the row.\n */\nexport function isCellDirty<T>(baselines: Map<string, T>, rowId: string, currentRow: T, field: string): boolean {\n const baseline = baselines.get(rowId);\n if (!baseline) return false;\n const baselineValue = readCellField(baseline, field);\n const currentValue = readCellField(currentRow, field);\n return !deepEqual(baselineValue, currentValue);\n}\n\n/**\n * Deep comparison of two values. Handles primitives, plain objects, arrays,\n * and Dates — the value types produced by `structuredClone` on row data.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a == null || b == null) return false;\n if (typeof a !== typeof b) return false;\n\n // Date comparison\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n\n // Array comparison\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n\n // Object comparison\n if (typeof a === 'object') {\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const keysA = Object.keys(aObj);\n const keysB = Object.keys(bObj);\n if (keysA.length !== keysB.length) return false;\n for (const key of keysA) {\n if (!deepEqual(aObj[key], bObj[key])) return false;\n }\n return true;\n }\n\n return false;\n}\n\n// #endregion\n\n// #region State Transitions\n\n/**\n * Mark a row as pristine: re-snapshot baseline from current data.\n *\n * After calling this, `isRowDirty` returns `false` for the row (until it\n * is edited again).\n */\nexport function markPristine<T>(baselines: Map<string, T>, rowId: string, currentRow: T): void {\n baselines.set(rowId, structuredClone(currentRow));\n}\n\n/**\n * Get the original (baseline) row data as a deep clone.\n *\n * Returns `undefined` if no baseline exists (e.g. newly inserted row).\n */\nexport function getOriginalRow<T>(baselines: Map<string, T>, rowId: string): T | undefined {\n const baseline = baselines.get(rowId);\n return baseline ? structuredClone(baseline) : undefined;\n}\n\n/**\n * Revert a row to its baseline values by mutating the current row in-place.\n *\n * Returns `true` if a baseline existed and the row was reverted, `false` otherwise.\n */\nexport function revertToBaseline<T>(baselines: Map<string, T>, rowId: string, currentRow: T): boolean {\n const baseline = baselines.get(rowId);\n if (!baseline) return false;\n const baselineObj = baseline as Record<string, unknown>;\n const currentObj = currentRow as Record<string, unknown>;\n for (const key of Object.keys(baselineObj)) {\n currentObj[key] = baselineObj[key];\n }\n return true;\n}\n\n// #endregion\n","/**\n * Stateful manager for dirty tracking in the EditingPlugin.\n *\n * Owns all dirty-tracking-related state (baselines, changed/new/committed sets)\n * and exposes high-level methods that coordinate pure functions from\n * `dirty-tracking.ts`.\n *\n * The EditingPlugin delegates all dirty tracking operations to this manager,\n * keeping the plugin class focused on orchestration (row resolution, event\n * emission, render scheduling).\n *\n * @internal\n */\n\nimport { writeCellField } from '../../../core/internal/value-accessor';\nimport {\n captureBaselines,\n getOriginalRow,\n isCellDirty,\n isRowDirty,\n markPristine,\n revertToBaseline,\n type DirtyRowEntry,\n} from './dirty-tracking';\n\n// #region Types\n\n/**\n * Callback that resolves a row object by its ID.\n * Returns `undefined` when the row is not found.\n */\nexport type RowResolver<T> = (rowId: string) => T | undefined;\n\n// #endregion\n\n// #region DirtyTrackingManager\n\nexport class DirtyTrackingManager<T> {\n // --- Owned state ---\n\n /** Baseline snapshots: rowId → deep-cloned original row data (first-write-wins) */\n readonly baselines = new Map<string, T>();\n\n /** Whether new baselines were captured during the current processRows cycle */\n private baselinesWereCaptured = false;\n\n /** Row IDs inserted via `insertRow()` (no baseline available) */\n readonly newRowIds = new Set<string>();\n\n /** Row IDs that have been modified (edit committed) */\n readonly changedRowIds = new Set<string>();\n\n /** Row IDs whose edit session was committed (gates `tbw-row-dirty` CSS class) */\n readonly committedDirtyRowIds = new Set<string>();\n\n // --- Lifecycle ---\n\n /** Reset all dirty tracking state (called from detach / resetChangedRows). */\n clear(): void {\n this.changedRowIds.clear();\n this.committedDirtyRowIds.clear();\n this.baselines.clear();\n this.newRowIds.clear();\n this.baselinesWereCaptured = false;\n }\n\n // --- Baseline capture (called from processRows) ---\n\n /**\n * Capture baselines for rows not already tracked (first-write-wins).\n * Sets the `baselinesWereCaptured` flag when new rows are snapshotted.\n */\n capture(rows: readonly T[], getRowId: (r: T) => string | undefined): void {\n const sizeBefore = this.baselines.size;\n captureBaselines(this.baselines, rows, getRowId);\n if (this.baselines.size > sizeBefore) {\n this.baselinesWereCaptured = true;\n }\n }\n\n /**\n * Drain the baselines-captured flag (called from afterRender).\n * Returns `null` when no new captures occurred, or the baseline count.\n */\n drainCapturedFlag(): number | null {\n if (!this.baselinesWereCaptured) return null;\n this.baselinesWereCaptured = false;\n return this.baselines.size;\n }\n\n // --- Row dirty queries ---\n\n /** Check if a specific row differs from its baseline. */\n isRowDirty(rowId: string, row: T): boolean {\n return isRowDirty(this.baselines, rowId, row);\n }\n\n /** Check if ANY row is dirty (requires row resolver for baseline iteration). */\n hasAnyDirty(resolveRow: RowResolver<T>): boolean {\n if (this.newRowIds.size > 0) return true;\n for (const [rowId] of this.baselines) {\n const row = resolveRow(rowId);\n if (row && isRowDirty(this.baselines, rowId, row)) return true;\n }\n return false;\n }\n\n // --- Cell dirty queries ---\n\n /** Check if a single cell differs from its baseline value. */\n isCellDirty(rowId: string, row: T, field: string): boolean {\n return isCellDirty(this.baselines, rowId, row, field);\n }\n\n // --- Render-time helpers ---\n\n /**\n * Get the dirty-state tuple needed by afterRowRender to toggle CSS classes.\n *\n * `isCommittedDirty` requires BOTH committed status AND actual data divergence\n * from baseline (handles undo: after CTRL+Z, row is no longer visually dirty).\n */\n getRowDirtyState(rowId: string, row: T): { isNew: boolean; isCommittedDirty: boolean; hasBaseline: boolean } {\n const isNew = this.newRowIds.has(rowId);\n const isCommittedDirty = !isNew && this.committedDirtyRowIds.has(rowId) && isRowDirty(this.baselines, rowId, row);\n return { isNew, isCommittedDirty, hasBaseline: this.baselines.has(rowId) };\n }\n\n // --- Mark operations ---\n\n /** Re-snapshot baseline from current data and remove from all sets. */\n markPristine(rowId: string, row: T): void {\n markPristine(this.baselines, rowId, row);\n this.newRowIds.delete(rowId);\n this.changedRowIds.delete(rowId);\n this.committedDirtyRowIds.delete(rowId);\n }\n\n /**\n * Update a single field's baseline to an externally-synced value.\n *\n * Used for `source: 'sync'` (declarative host data replacement): the incoming\n * value becomes the new pristine truth for that cell without touching other\n * fields' baselines or the row's dirty membership sets. No-op when the row has\n * no captured baseline (an untracked row is not dirty anyway).\n */\n rebaselineCell(rowId: string, field: string, value: unknown): void {\n const baseline = this.baselines.get(rowId);\n if (baseline) writeCellField(baseline, field, value);\n }\n\n /** Mark a row as newly inserted (no baseline). */\n markNew(rowId: string): void {\n this.newRowIds.add(rowId);\n this.committedDirtyRowIds.add(rowId);\n }\n\n /** Mark a row as dirty (external mutation). */\n markDirty(rowId: string): void {\n this.changedRowIds.add(rowId);\n this.committedDirtyRowIds.add(rowId);\n }\n\n /** Re-snapshot all baselines and clear all tracking sets. */\n markAllPristine(resolveRow: RowResolver<T>): void {\n for (const [rowId] of this.baselines) {\n const row = resolveRow(rowId);\n if (row) markPristine(this.baselines, rowId, row);\n }\n this.newRowIds.clear();\n this.changedRowIds.clear();\n this.committedDirtyRowIds.clear();\n }\n\n // --- Original row access ---\n\n /** Get deep-cloned baseline (undefined for new/untracked rows). */\n getOriginalRow(rowId: string): T | undefined {\n return getOriginalRow<T>(this.baselines, rowId);\n }\n\n /** Lightweight check whether a baseline exists (no cloning). */\n hasBaseline(rowId: string): boolean {\n return this.baselines.has(rowId);\n }\n\n // --- Aggregate queries ---\n\n /** Get all dirty rows with original + current data. Requires a row resolver. */\n getDirtyRows(resolveRow: RowResolver<T>): DirtyRowEntry<T>[] {\n const result: DirtyRowEntry<T>[] = [];\n for (const [rowId, baseline] of this.baselines) {\n const row = resolveRow(rowId);\n if (row && isRowDirty(this.baselines, rowId, row)) {\n result.push({ id: rowId, original: structuredClone(baseline), current: row });\n }\n }\n for (const newId of this.newRowIds) {\n const row = resolveRow(newId);\n if (row) {\n result.push({ id: newId, original: undefined, current: row });\n }\n }\n return result;\n }\n\n /** Get IDs of all dirty rows. Requires a row resolver. */\n getDirtyRowIds(resolveRow: RowResolver<T>): string[] {\n const ids: string[] = [];\n for (const [rowId] of this.baselines) {\n const row = resolveRow(rowId);\n if (row && isRowDirty(this.baselines, rowId, row)) ids.push(rowId);\n }\n for (const newId of this.newRowIds) ids.push(newId);\n return ids;\n }\n\n // --- Revert operations ---\n\n /**\n * Revert a row to its baseline values (mutates row in-place).\n * Returns `true` when baseline existed and row was reverted.\n */\n revertRow(rowId: string, row: T): boolean {\n const reverted = revertToBaseline(this.baselines, rowId, row);\n if (reverted) {\n this.changedRowIds.delete(rowId);\n this.committedDirtyRowIds.delete(rowId);\n }\n return reverted;\n }\n\n /** Revert all rows to baseline values. Requires a row resolver. */\n revertAll(resolveRow: RowResolver<T>): void {\n for (const [rowId] of this.baselines) {\n const row = resolveRow(rowId);\n if (row) revertToBaseline(this.baselines, rowId, row);\n }\n this.changedRowIds.clear();\n this.committedDirtyRowIds.clear();\n }\n\n // --- Changed row queries ---\n\n /** Resolve changed row IDs to row objects. */\n getChangedRows(resolveRow: RowResolver<T>): T[] {\n const rows: T[] = [];\n for (const id of this.changedRowIds) {\n const row = resolveRow(id);\n if (row) rows.push(row);\n }\n return rows;\n }\n\n /** Get a copy of changed row IDs. */\n getChangedRowIds(): string[] {\n return Array.from(this.changedRowIds);\n }\n\n /** Check if a row has been marked as changed. */\n isRowChanged(rowId: string): boolean {\n return this.changedRowIds.has(rowId);\n }\n}\n\n// #endregion\n","/**\n * Pure helper functions for the Editing Plugin.\n *\n * Extracted from EditingPlugin to reduce the main plugin file size.\n * All functions are stateless — they have no `this` access.\n *\n * @internal\n */\n\nimport type {\n ColumnConfig,\n ColumnEditorSpec,\n ColumnInternal,\n InternalGrid,\n RowElementInternal,\n} from '../../../core/types';\nimport { getInputValue } from '../editors';\nimport type { EditingConfig } from '../types';\n\n// #region Constants\n\n/**\n * CSS selector for focusable editor elements inside a cell.\n * Duplicated from core/internal/rows to avoid cross-boundary imports\n * that Vite externalises to `@toolbox-web/grid` during plugin bundling.\n *\n * @internal\n */\nexport const FOCUSABLE_EDITOR_SELECTOR =\n 'input,select,textarea,[contenteditable=\"true\"],[contenteditable=\"\"],[tabindex]:not([tabindex=\"-1\"])';\n\n/**\n * Returns the closest ancestor (or `target` itself) that matches\n * {@link FOCUSABLE_EDITOR_SELECTOR}, or `null` if none exists.\n *\n * Always prefer this over `target.matches(FOCUSABLE_EDITOR_SELECTOR)` —\n * non-focusable editor descendants (e.g. `<option>` inside an open\n * native `<select>` popup; spans inside `contenteditable`) need to be\n * recognised as \"inside the editor\" but do not themselves match the\n * selector.\n *\n * @internal\n */\nexport function getEditorAncestor(target: EventTarget | null | undefined): Element | null {\n const el = target as Element | null | undefined;\n return el?.closest?.(FOCUSABLE_EDITOR_SELECTOR) ?? null;\n}\n\n// #endregion\n\n// #region Editor Resolution\n\n/**\n * Resolves the editor for a column using the priority chain:\n * 1. Column-level (`column.editor`)\n * 2. Light DOM template (`__editorTemplate` → returns 'template')\n * 3. Grid-level (`gridConfig.typeDefaults[column.type]`)\n * 4. App-level (framework adapter's `getTypeDefault`)\n * 5. Returns undefined (caller uses built-in defaultEditorFor)\n */\nexport function resolveEditor<TRow>(\n grid: InternalGrid<TRow>,\n col: ColumnInternal<TRow>,\n): ColumnEditorSpec<TRow, unknown> | 'template' | undefined {\n // 1. Column-level editor (highest priority)\n if (col.editor) return col.editor;\n\n // 2. Light DOM template\n const tplHolder = col.__editorTemplate;\n if (tplHolder) return 'template';\n\n // No type specified - no type defaults to check\n if (!col.type) return undefined;\n\n // 3. Grid-level typeDefaults (access via effectiveConfig)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const gridTypeDefaults = (grid as any).effectiveConfig?.typeDefaults;\n if (gridTypeDefaults?.[col.type]?.editor) {\n return gridTypeDefaults[col.type].editor as ColumnEditorSpec<TRow, unknown>;\n }\n\n // 4. App-level registry (via framework adapter)\n const adapter = grid.__frameworkAdapter;\n if (adapter?.getTypeDefault) {\n const appDefault = adapter.getTypeDefault<TRow>(col.type, grid._hostElement);\n if (appDefault?.editor) {\n return appDefault.editor as ColumnEditorSpec<TRow, unknown>;\n }\n }\n\n // 5. No custom editor - caller uses built-in defaultEditorFor\n return undefined;\n}\n\n// #endregion\n\n// #region Property Key Safety\n\n/**\n * Returns true if the given property key is safe to use on a plain object.\n */\nexport function isSafePropertyKey(key: unknown): key is string {\n if (typeof key !== 'string') return false;\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') return false;\n return true;\n}\n\n// #endregion\n\n// #region Row Element State\n\n/**\n * Increment the editing cell count on a row element.\n */\nexport function incrementEditingCount(rowEl: RowElementInternal): void {\n const count = (rowEl.__editingCellCount ?? 0) + 1;\n rowEl.__editingCellCount = count;\n rowEl.setAttribute('data-has-editing', '');\n}\n\n/**\n * Clear all editing state from a row element.\n */\nexport function clearEditingState(rowEl: RowElementInternal): void {\n rowEl.__editingCellCount = 0;\n rowEl.removeAttribute('data-has-editing');\n}\n\n// #endregion\n\n// #region No-op Helpers\n\n/**\n * No-op updateRow function for rows without IDs.\n * Extracted to a named function to satisfy eslint no-empty-function.\n */\nexport function noopUpdateRow(_changes: unknown): void {\n // Row has no ID - cannot update\n}\n\n// #endregion\n\n// #region Editor Input Wiring\n\n/**\n * Auto-wire commit/cancel lifecycle for input elements in string-returned editors.\n */\nexport function wireEditorInputs(\n editorHost: HTMLElement,\n column: ColumnConfig<unknown>,\n commit: (value: unknown) => void,\n originalValue?: unknown,\n): void {\n const input = editorHost.querySelector('input,textarea,select') as\n | HTMLInputElement\n | HTMLTextAreaElement\n | HTMLSelectElement\n | null;\n if (!input) return;\n\n input.addEventListener('blur', () => {\n commit(getInputValue(input, column, originalValue));\n });\n\n if (input instanceof HTMLInputElement && input.type === 'checkbox') {\n input.addEventListener('change', () => commit(input.checked));\n } else if (input instanceof HTMLSelectElement) {\n input.addEventListener('change', () => commit(getInputValue(input, column, originalValue)));\n }\n}\n\n// #endregion\n\n// #region Edit Guard\n\n/**\n * Returns `true` when the configured `onBeforeEditClose` callback vetoes\n * the close (i.e. returns `false`). Use as a one-liner guard:\n *\n * ```ts\n * if (shouldPreventEditClose(config, e)) return;\n * ```\n */\nexport function shouldPreventEditClose(config: EditingConfig, event: MouseEvent | KeyboardEvent): boolean {\n return config.onBeforeEditClose?.(event) === false;\n}\n\n// #endregion\n\n// #region ARIA Overlay Detection\n\n/**\n * Returns `true` when `target` is inside an overlay panel that is currently\n * \"owned\" by an open combobox/listbox/menu inside `scopeEl`.\n *\n * Detection uses the WAI-ARIA pattern: a control with\n * `aria-expanded=\"true\"` and `aria-controls=\"<id>\"` declares ownership of\n * the panel with that id. Used by the editing plugin as a generic fallback\n * so portal-rendered overlays from libraries like Downshift, Material UI,\n * or Headless UI are recognised as part of the active editor without the\n * consumer having to call `registerExternalFocusContainer` (#251).\n *\n * Cheap: only walks elements with `aria-expanded=\"true\"` inside the\n * editor scope (typically zero or one).\n *\n * @internal\n */\nexport function isInsideOpenAriaOverlay(target: Node | null | undefined, scopeEl: HTMLElement): boolean {\n if (!target) return false;\n const triggers = scopeEl.querySelectorAll<HTMLElement>('[aria-expanded=\"true\"][aria-controls]');\n for (let i = 0; i < triggers.length; i++) {\n const id = triggers[i].getAttribute('aria-controls');\n if (!id) continue;\n const panel = scopeEl.ownerDocument?.getElementById(id);\n if (panel && panel.contains(target as Node)) return true;\n }\n return false;\n}\n\n// #endregion\n\n// #region Row Comparison\n\n/**\n * Shallow-compare a snapshot against the current row to detect changes.\n * Returns `true` if any own-property value differs between the two objects.\n */\nexport function hasRowChanged<T>(snapshot: T | undefined, current: T): boolean {\n if (!snapshot) return false;\n const snapshotObj = snapshot as Record<string, unknown>;\n const currentObj = current as Record<string, unknown>;\n const allKeys = new Set([...Object.keys(snapshotObj), ...Object.keys(currentObj)]);\n for (const key of allKeys) {\n if (snapshotObj[key] !== currentObj[key]) return true;\n }\n return false;\n}\n\n// #endregion\n","/**\n * Editor injection logic for the Editing Plugin.\n *\n * Extracted from EditingPlugin to reduce the main file size.\n * Contains the DOM-heavy editor creation and template rendering,\n * while the plugin retains state management and event emission.\n *\n * @internal\n */\n\nimport { EDITOR_MOUNT_ERROR, warnDiagnostic } from '../../../core/internal/diagnostics';\nimport { readCellField, writeCellField } from '../../../core/internal/value-accessor';\nimport type {\n ColumnConfig,\n ColumnEditorContext,\n ColumnInternal,\n GridHost,\n RowElementInternal,\n} from '../../../core/types';\nimport { defaultEditorFor, getInputValue } from '../editors';\nimport type { EditingConfig } from '../types';\nimport {\n FOCUSABLE_EDITOR_SELECTOR,\n getEditorAncestor,\n incrementEditingCount,\n isSafePropertyKey,\n noopUpdateRow,\n resolveEditor,\n shouldPreventEditClose,\n wireEditorInputs,\n} from './helpers';\n\n// #region Types\n\n/**\n * Dependencies injected by the EditingPlugin so the extraction\n * can call back into plugin-owned state and methods.\n */\nexport interface EditorInjectionDeps<T> {\n /** Internal grid reference (also serves as HTMLElement). */\n grid: GridHost<T>;\n /** Whether the grid is in always-editing \"grid\" mode. */\n isGridMode: boolean;\n /** Plugin configuration. */\n config: EditingConfig;\n /** Set of cells currently in edit mode (\"rowIndex:colIndex\"). */\n editingCells: Set<string>;\n /** Value-change callbacks keyed by \"rowIndex:field\". */\n editorValueCallbacks: Map<string, (newValue: unknown) => void>;\n /** Returns `true` when an edit session is active (#activeEditRow !== -1). */\n isEditSessionActive: () => boolean;\n /** Commit a single cell value change. */\n commitCellValue: (rowIndex: number, column: ColumnConfig<T>, newValue: unknown, rowData: T) => void;\n /** Exit editing for a row (commit or revert). */\n exitRowEdit: (rowIndex: number, revert: boolean) => void;\n}\n\n// #endregion\n\n// #region Editor Injection\n\n/**\n * Inject an editor into a cell element.\n *\n * Handles the full editor lifecycle: creates the editor host, resolves\n * the editor spec (template / custom-element / factory / component),\n * wires commit/cancel callbacks, and registers value-change listeners.\n */\nexport function injectEditor<T>(\n deps: EditorInjectionDeps<T>,\n rowData: T,\n rowIndex: number,\n column: ColumnConfig<T>,\n colIndex: number,\n cell: HTMLElement,\n skipFocus: boolean,\n parentRowEl?: HTMLElement,\n): void {\n if (!column.editable) return;\n if (cell.classList.contains('editing')) return;\n\n const { grid, isGridMode, config, editingCells, editorValueCallbacks } = deps;\n\n // Get row ID for updateRow helper (may not exist)\n let rowId: string | undefined;\n try {\n rowId = grid.getRowId?.(rowData);\n } catch {\n // Row has no ID\n }\n\n // Create updateRow helper for cascade updates (noop if row has no ID)\n const updateRow: (changes: Partial<T>) => void = rowId\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (changes) => (grid as any).updateRow(rowId!, changes as Record<string, unknown>, 'cascade')\n : noopUpdateRow;\n\n const originalValue = isSafePropertyKey(column.field) ? readCellField(rowData, column.field) : undefined;\n\n cell.classList.add('editing');\n editingCells.add(`${rowIndex}:${colIndex}`);\n\n // Use explicit parentRowEl when cell is in a DocumentFragment (not yet in DOM),\n // otherwise fall back to cell.parentElement for cells already attached to a row.\n const rowEl = (parentRowEl ?? cell.parentElement) as RowElementInternal | null;\n if (rowEl) incrementEditingCount(rowEl);\n\n let editFinalized = false;\n const commit = (newValue: unknown) => {\n // In grid mode, always allow commits (we're always editing)\n // In row mode, only allow commits if we're in an active edit session\n if (editFinalized || (!isGridMode && !deps.isEditSessionActive())) return;\n // Resolve row and index fresh at commit time.\n // With a row ID we use _getRowEntry for O(1) lookup — this is resilient\n // against _rows being replaced (e.g. Angular directive effect).\n // Without a row ID we fall back to the captured rowData reference.\n // Using _rows[rowIndex] without an ID is unsafe: the index may be stale\n // after _rows replacement, which would commit to the WRONG row.\n const entry = rowId ? grid._getRowEntry(rowId) : undefined;\n const currentRowData = (entry?.row ?? rowData) as T;\n const currentIndex = entry?.index ?? rowIndex;\n deps.commitCellValue(currentIndex, column, newValue, currentRowData);\n };\n const cancel = () => {\n editFinalized = true;\n if (isSafePropertyKey(column.field)) {\n // Same ID-first / captured-rowData fallback as commit — see comment above.\n const entry = rowId ? grid._getRowEntry(rowId) : undefined;\n const currentRowData = (entry?.row ?? rowData) as T;\n writeCellField(currentRowData, column.field, originalValue);\n }\n };\n\n const editorHost = document.createElement('div');\n editorHost.className = 'tbw-editor-host';\n // Let the framework adapter (React/Vue/Angular) tear down any renderer\n // it mounted into this cell BEFORE we wipe the DOM. The `cell.innerHTML`\n // assignment below removes adapter-managed nodes synchronously without\n // notifying the framework — which leaves React's fiber tree pointing at\n // orphan DOM and throws `removeChild` on the next user-triggered commit\n // (issue #250). Calling `releaseCell` here unmounts cleanly while the\n // adapter's container is still attached to its remembered children.\n // Guard with `firstElementChild` so default-rendered cells (no\n // adapter-managed nodes) skip the no-op call — matches the wipe-guard\n // pattern in `core/internal/rows.ts`.\n if (cell.firstElementChild) grid.__frameworkAdapter?.releaseCell?.(cell);\n cell.innerHTML = '';\n cell.appendChild(editorHost);\n\n // Keydown handler for Enter/Escape\n editorHost.addEventListener('keydown', (e: KeyboardEvent) => {\n // Respect editor-level preventDefault: portal-based pickers (combobox,\n // autocomplete, calendar) call preventDefault on Enter to confirm an\n // option without exiting the row. Bubbling reaches editorHost with\n // defaultPrevented=true; honor that and skip the row-exit logic (#250).\n if (e.defaultPrevented) return;\n // ARIA-expanded fallback (#251): when the focused control declares\n // an open overlay via aria-expanded=\"true\" + aria-controls, defer\n // Enter to the overlay so combobox confirmation does not close the\n // row edit. Covers libraries like Downshift / Headless UI / MUI\n // Autocomplete that do not call preventDefault on confirm.\n // Only short-circuit Enter — Escape and other keys must still flow\n // through the normal handlers (Escape closes the overlay first via\n // its own listener, then dispatches up to cancel-edit if unhandled).\n if (e.key === 'Enter') {\n const ariaTarget = e.target as HTMLElement | null;\n if (\n ariaTarget &&\n ariaTarget.getAttribute?.('aria-expanded') === 'true' &&\n ariaTarget.hasAttribute?.('aria-controls')\n ) {\n return;\n }\n }\n if (e.key === 'Enter') {\n // Native <select> open-popup guard — applies in BOTH grid and row mode.\n // When Enter's target is a *descendant* of the editor (most notably an\n // <option> inside an open native <select> popup), do nothing: let the\n // browser commit the highlighted option and close the popup, which fires\n // `change` on the editor (committing via the change listener wired below).\n // Calling preventDefault / stopPropagation / exitRowEdit here would\n // destroy the open popup and discard the selection. A subsequent Enter\n // (popup closed → target IS the editor) then exits the row as usual.\n // Row mode previously lacked this guard, so keyboard selection in custom\n // <select> editors closed the row instead of picking the value (#427).\n const enterTarget = e.target as Element | null;\n const enterEditorAncestor = getEditorAncestor(enterTarget);\n if (enterEditorAncestor && enterEditorAncestor !== enterTarget) {\n return;\n }\n // In grid mode, Enter just commits without exiting\n if (isGridMode) {\n // Target IS the editor itself (SELECT with no popup open, or\n // INPUT/TEXTAREA): commit the current value. preventDefault\n // suppresses the browser opening the SELECT popup on Enter.\n // We deliberately do NOT stopPropagation — the event must\n // bubble so EditingPlugin can blur the editor and return\n // focus to the grid for cell navigation.\n e.preventDefault();\n const input = editorHost.querySelector('input,textarea,select') as\n HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null;\n if (input) {\n commit(getInputValue(input, column as ColumnConfig<unknown>, originalValue));\n }\n return;\n }\n if (shouldPreventEditClose(config, e)) return;\n e.stopPropagation();\n e.preventDefault();\n editFinalized = true;\n deps.exitRowEdit(rowIndex, false);\n }\n if (e.key === 'Escape') {\n // In grid mode, Escape doesn't exit edit mode\n if (isGridMode) {\n e.stopPropagation();\n e.preventDefault();\n return;\n }\n if (shouldPreventEditClose(config, e)) return;\n e.stopPropagation();\n e.preventDefault();\n cancel();\n deps.exitRowEdit(rowIndex, true);\n }\n });\n\n const colInternal = column as ColumnInternal<T>;\n const tplHolder = colInternal.__editorTemplate;\n // Resolve editor using priority chain: column → template → typeDefaults → adapter → built-in\n const editorSpec = resolveEditor(grid, colInternal) ?? defaultEditorFor(column);\n const value = originalValue;\n\n // Value-change callback registration.\n // Editors call onValueChange(cb) to receive pushes when the underlying row\n // is mutated externally (e.g., via updateRow from another cell's commit).\n // Multiple callbacks can be registered (user + auto-wire).\n const callbackKey = `${rowIndex}:${column.field}`;\n const callbacks: Array<(newValue: unknown) => void> = [];\n editorValueCallbacks.set(callbackKey, (newVal) => {\n for (const cb of callbacks) cb(newVal);\n });\n const onValueChange = (cb: (newValue: unknown) => void) => {\n callbacks.push(cb);\n };\n\n if (editorSpec === 'template' && tplHolder) {\n renderTemplateEditor(deps, editorHost, colInternal, rowData, originalValue, commit, cancel, skipFocus, rowIndex);\n // Auto-update built-in template editors when value changes externally.\n // Skip non-primitive values (arrays, objects) — framework adapters manage\n // those via the cell-cancel event. String() on arrays produces comma-separated junk.\n onValueChange((newVal) => {\n if (newVal != null && typeof newVal === 'object') return;\n const input = editorHost.querySelector<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(\n 'input,textarea,select',\n );\n if (input) {\n if (input instanceof HTMLInputElement && input.type === 'checkbox') {\n input.checked = !!newVal;\n } else {\n input.value = String(newVal ?? '');\n }\n }\n });\n } else if (typeof editorSpec === 'string') {\n const el = document.createElement(editorSpec) as HTMLElement & { value?: unknown };\n el.value = value;\n el.addEventListener('change', () => commit(el.value));\n // Auto-update custom element editors when value changes externally\n onValueChange((newVal) => {\n el.value = newVal;\n });\n editorHost.appendChild(el);\n if (!skipFocus) {\n queueMicrotask(() => {\n const focusable = editorHost.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n focusable?.focus({ preventScroll: true });\n });\n }\n } else if (typeof editorSpec === 'function') {\n const ctx: ColumnEditorContext<T> = {\n row: rowData,\n rowId: rowId ?? '',\n value,\n field: column.field,\n column,\n commit,\n cancel,\n updateRow,\n onValueChange,\n grid: deps.grid as ColumnEditorContext<T>['grid'],\n };\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const produced = (editorSpec as any)(ctx);\n if (typeof produced === 'string') {\n // NOT sanitized on purpose: sanitizeHTML strips `input`/`select`/\n // `textarea`/`button`, which is exactly what an editor is made of. The\n // string comes from an author-supplied editor factory (code, not row\n // data) — row values reach the DOM through the compiled-template path\n // below, which escapes interpolated values.\n // eslint-disable-next-line no-restricted-syntax\n editorHost.innerHTML = produced;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wireEditorInputs(editorHost, column as any, commit, originalValue);\n // Auto-update wired inputs when value changes externally\n onValueChange((newVal) => {\n const input = editorHost.querySelector<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(\n 'input,textarea,select',\n );\n if (input) {\n if (input instanceof HTMLInputElement && input.type === 'checkbox') {\n input.checked = !!newVal;\n } else {\n input.value = String(newVal ?? '');\n }\n }\n });\n } else if (produced instanceof Node) {\n editorHost.appendChild(produced);\n const isSimpleInput =\n produced instanceof HTMLInputElement ||\n produced instanceof HTMLSelectElement ||\n produced instanceof HTMLTextAreaElement;\n if (!isSimpleInput) {\n cell.setAttribute('data-editor-managed', '');\n } else {\n // Auto-update simple inputs returned by factory functions\n onValueChange((newVal) => {\n if (produced instanceof HTMLInputElement && produced.type === 'checkbox') {\n produced.checked = !!newVal;\n } else {\n (produced as HTMLInputElement).value = String(newVal ?? '');\n }\n });\n }\n } else if (!produced && editorHost.hasChildNodes()) {\n // Factory returned void but mounted content into the editor host\n // (e.g. Angular/React/Vue adapter component editor). Mark the cell\n // as externally managed so the native commit loop in #exitRowEdit\n // does not read raw input values from framework editor DOM.\n cell.setAttribute('data-editor-managed', '');\n }\n if (!skipFocus) {\n queueMicrotask(() => {\n const focusable = editorHost.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n focusable?.focus({ preventScroll: true });\n });\n }\n } else if (editorSpec && typeof editorSpec === 'object') {\n const placeholder = document.createElement('div');\n placeholder.setAttribute('data-external-editor', '');\n placeholder.setAttribute('data-field', column.field);\n editorHost.appendChild(placeholder);\n cell.setAttribute('data-editor-managed', '');\n const context: ColumnEditorContext<T> = {\n row: rowData,\n rowId: rowId ?? '',\n value,\n field: column.field,\n column,\n commit,\n cancel,\n updateRow,\n onValueChange,\n grid: deps.grid as ColumnEditorContext<T>['grid'],\n };\n if (editorSpec.mount) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n editorSpec.mount({ placeholder, context: context as any, spec: editorSpec });\n } catch (e) {\n warnDiagnostic(\n EDITOR_MOUNT_ERROR,\n `External editor mount error for column '${column.field}': ${e}`,\n deps.grid.id,\n );\n }\n } else {\n grid.dispatchEvent(\n new CustomEvent('mount-external-editor', { detail: { placeholder, spec: editorSpec, context } }),\n );\n }\n }\n\n nameEditorFromHeader(editorHost, column);\n}\n\n/**\n * Give the editor an accessible name taken from its column header.\n *\n * A screen reader announces the header when focus lands on a *gridcell*, but an\n * `<input>` inside that cell is a control in its own right and needs its own\n * name (SC 4.1.2 / SC 3.3.2) — otherwise it is announced as a bare \"edit text\".\n * Deferred a microtask so editors that mount asynchronously are covered, and\n * skipped entirely whenever the control already has a name of any kind.\n */\nfunction nameEditorFromHeader<T>(editorHost: HTMLElement, column: ColumnConfig<T>): void {\n const label = typeof column.header === 'string' ? column.header : column.field;\n if (!label) return;\n\n queueMicrotask(() => {\n const control = editorHost.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n if (!control) return;\n const named =\n control.hasAttribute('aria-label') ||\n control.hasAttribute('aria-labelledby') ||\n control.hasAttribute('title') ||\n (control.id && editorHost.querySelector(`label[for=\"${CSS.escape(control.id)}\"]`)) ||\n control.closest('label');\n if (!named) control.setAttribute('aria-label', label);\n });\n}\n\n// #endregion\n\n// #region Template Editor\n\n/**\n * Render a template-based editor inside an editor host element.\n */\nfunction renderTemplateEditor<T>(\n deps: Pick<EditorInjectionDeps<T>, 'config' | 'exitRowEdit'>,\n editorHost: HTMLElement,\n column: ColumnInternal<T>,\n rowData: T,\n originalValue: unknown,\n commit: (value: unknown) => void,\n cancel: () => void,\n skipFocus: boolean,\n rowIndex: number,\n): void {\n const tplHolder = column.__editorTemplate;\n if (!tplHolder) return;\n\n const clone = tplHolder.cloneNode(true) as HTMLElement;\n const compiledEditor = column.__compiledEditor;\n\n if (compiledEditor) {\n // NOT sanitized: editor markup is author light-DOM (`<template editor>`) and\n // contains form controls the sanitizer would strip. Row data interpolated\n // via `{{ }}` is HTML-escaped by the compiled template itself.\n // eslint-disable-next-line no-restricted-syntax\n clone.innerHTML = compiledEditor({\n row: rowData,\n value: originalValue,\n field: column.field,\n column,\n commit,\n cancel,\n });\n } else {\n clone.querySelectorAll<HTMLElement>('*').forEach((node) => {\n if (node.childNodes.length === 1 && node.firstChild?.nodeType === Node.TEXT_NODE) {\n node.textContent =\n node.textContent\n ?.replace(/{{\\s*value\\s*}}/g, originalValue == null ? '' : String(originalValue))\n .replace(/{{\\s*row\\.([a-zA-Z0-9_]+)\\s*}}/g, (_m, g: string) => {\n if (!isSafePropertyKey(g)) return '';\n const v = (rowData as Record<string, unknown>)[g];\n return v == null ? '' : String(v);\n }) || '';\n }\n });\n }\n\n const input = clone.querySelector<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(\n 'input,textarea,select',\n );\n if (input) {\n if (input instanceof HTMLInputElement && input.type === 'checkbox') {\n input.checked = !!originalValue;\n } else {\n input.value = String(originalValue ?? '');\n }\n\n let editFinalized = false;\n input.addEventListener('blur', () => {\n if (editFinalized) return;\n commit(getInputValue(input, column, originalValue));\n });\n input.addEventListener('keydown', (evt) => {\n const e = evt as KeyboardEvent;\n if (e.key === 'Enter') {\n if (shouldPreventEditClose(deps.config, e)) return;\n e.stopPropagation();\n e.preventDefault();\n editFinalized = true;\n commit(getInputValue(input, column, originalValue));\n deps.exitRowEdit(rowIndex, false);\n }\n if (e.key === 'Escape') {\n if (shouldPreventEditClose(deps.config, e)) return;\n e.stopPropagation();\n e.preventDefault();\n cancel();\n deps.exitRowEdit(rowIndex, true);\n }\n });\n if (input instanceof HTMLInputElement && input.type === 'checkbox') {\n input.addEventListener('change', () => commit(input.checked));\n }\n if (!skipFocus) {\n setTimeout(() => input.focus({ preventScroll: true }), 0);\n }\n }\n editorHost.appendChild(clone);\n}\n\n// #endregion\n","/**\n * Editing Plugin\n *\n * Provides complete editing functionality for tbw-grid.\n * This plugin is FULLY SELF-CONTAINED - the grid has ZERO editing knowledge.\n *\n * The plugin:\n * - Owns all editing state (active cell, snapshots, changed rows)\n * - Uses event distribution (onCellClick, onKeyDown) to handle edit lifecycle\n * - Uses afterRender() hook to inject editors into cells\n * - Uses processColumns() to augment columns with editing metadata\n * - Emits its own events (cell-commit, row-commit, changed-rows-reset)\n *\n * Without this plugin, the grid cannot edit. With this plugin, editing\n * is fully functional without any core changes.\n */\n\nimport { GridDataAttrs } from '../../core/constants';\nimport { announce, getA11yMessage } from '../../core/internal/aria';\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { compileTemplate } from '../../core/internal/sanitize';\nimport { invalidateAccessorCache, readCellField, writeCellField } from '../../core/internal/value-accessor';\nimport type {\n AfterCellRenderContext,\n AfterRowRenderContext,\n PluginManifest,\n PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport { BaseGridPlugin, type CellClickEvent, type GridElement } from '../../core/plugin/base-plugin';\nimport type { CellEditablePredicate, CommitCellValueContext } from '../../core/plugin/types';\nimport type {\n ColumnConfig,\n ColumnInternal,\n GridHost,\n InternalGrid,\n RowElementInternal,\n TypeDefault,\n UpdateSource,\n} from '../../core/types';\nimport styles from './editing.css?inline';\nimport { getInputValue } from './editors';\nimport { CellValidationManager } from './internal/cell-validation';\nimport { type BaselinesCapturedDetail, type DirtyChangeDetail, type DirtyRowEntry } from './internal/dirty-tracking';\nimport { DirtyTrackingManager } from './internal/dirty-tracking-manager';\nimport { type EditorInjectionDeps, injectEditor as injectEditorImpl } from './internal/editor-injection';\nimport {\n clearEditingState,\n FOCUSABLE_EDITOR_SELECTOR,\n getEditorAncestor,\n hasRowChanged,\n isInsideOpenAriaOverlay,\n isSafePropertyKey,\n noopUpdateRow,\n shouldPreventEditClose,\n} from './internal/helpers';\nimport type {\n BeforeEditCloseDetail,\n CellCancelDetail,\n CellCommitDetail,\n ChangedRowsResetDetail,\n EditCloseDetail,\n EditingConfig,\n EditOpenDetail,\n EditorParams,\n RowCommitDetail,\n} from './types';\n\n// ============================================================================\n// EditingPlugin\n// ============================================================================\n\n/**\n * Editing Plugin for tbw-grid\n *\n * Enables inline cell editing in the grid. Provides built-in editors for common data types\n * and supports custom editor functions for specialized input scenarios.\n *\n * ## Why Opt-In?\n *\n * Editing is delivered as a plugin rather than built into the core grid:\n *\n * - **Smaller bundle** — Apps that only display data don't pay for editing code\n * - **Clear intent** — Explicit plugin registration makes editing capability obvious\n * - **Runtime validation** — Using `editable: true` without the plugin throws a helpful error\n *\n * ## Installation\n *\n * ```ts\n * import { EditingPlugin } from '@toolbox-web/grid/plugins/editing';\n * ```\n *\n * ## Edit Triggers\n *\n * Configure how editing is triggered with the `editOn` option:\n *\n * | Value | Behavior |\n * |-------|----------|\n * | `'click'` | Single click enters edit mode (default) |\n * | `'dblclick'` | Double-click enters edit mode |\n *\n * ## Keyboard Shortcuts\n *\n * | Key | Action |\n * |-----|--------|\n * | `Enter` | Commit edit and move down |\n * | `Tab` | Commit edit and move right |\n * | `Escape` | Cancel edit, restore original value |\n * | `Arrow Keys` | Navigate between cells (when not editing) |\n *\n * @example Basic editing with double-click trigger\n * ```ts\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', editable: true },\n * { field: 'price', type: 'number', editable: true },\n * { field: 'active', type: 'boolean', editable: true },\n * ],\n * plugins: [new EditingPlugin({ editOn: 'dblclick' })],\n * };\n *\n * grid.on('cell-commit', ({ field, oldValue, newValue }) => {\n * console.log(`${field}: ${oldValue} → ${newValue}`);\n * });\n * ```\n *\n * @example Custom editor function\n * ```ts\n * columns: [\n * {\n * field: 'status',\n * editable: true,\n * editor: (ctx) => {\n * const select = document.createElement('select');\n * ['pending', 'active', 'completed'].forEach(opt => {\n * const option = document.createElement('option');\n * option.value = opt;\n * option.textContent = opt;\n * option.selected = ctx.value === opt;\n * select.appendChild(option);\n * });\n * select.addEventListener('change', () => ctx.commit(select.value));\n * return select;\n * },\n * },\n * ]\n * ```\n *\n * @see {@link EditingConfig} for configuration options\n * @see `ColumnEditorContext` for custom editor context\n * @see {@link EditingConfig} for interactive examples in the docs site\n * @since 0.4.0\n */\nexport class EditingPlugin<T = unknown> extends BaseGridPlugin<EditingConfig> {\n /**\n * Plugin manifest - declares owned properties for configuration validation.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n ownedProperties: [\n {\n property: 'editable',\n level: 'column',\n description: 'the \"editable\" column property',\n isUsed: (v) => v === true || typeof v === 'function',\n },\n {\n property: 'editor',\n level: 'column',\n description: 'the \"editor\" column property',\n },\n {\n property: 'editorParams',\n level: 'column',\n description: 'the \"editorParams\" column property',\n },\n {\n property: 'nullable',\n level: 'column',\n description: 'the \"nullable\" column property (allows null values)',\n },\n ],\n events: [\n {\n type: 'cell-edit-committed',\n description: 'Emitted when a cell edit is committed (for plugin-to-plugin coordination)',\n },\n ],\n queries: [\n {\n type: 'isEditing',\n description: 'Returns whether any cell is currently being edited',\n },\n {\n type: 'getCellEditableResolver',\n description:\n 'Returns a predicate (field, row) => boolean resolving per-cell editability (rowEditable gate + column.editable true/false/function), for consumers like clipboard paste',\n },\n {\n type: 'commitCellValue',\n description:\n 'Commits a single cell value coming from a core row mutation (updateRow/updateRows), running the full edit pipeline: cancelable cell-commit (validation/abortion), dirty tracking, history, and cascade. Returns true (applied), false (vetoed), or undefined (not handled).',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'editing';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<EditingConfig> {\n return {\n mode: 'row',\n editOn: 'click',\n };\n }\n\n /**\n * Whether the grid is in 'grid' mode (all cells always editable).\n */\n get #isGridMode(): boolean {\n return this.config.mode === 'grid';\n }\n\n /**\n * Resolve whether a given cell is editable.\n *\n * Resolution order:\n * 1. `gridConfig.rowEditable(row)` — row-level gate (if provided). Returns `false` → not editable.\n * 2. `column.editable` — `true`, `false`, or `(row) => boolean`.\n *\n * @returns `true` when the cell should be editable, `false` otherwise.\n */\n #isCellEditable(column: ColumnConfig<T>, row: T): boolean {\n // Row-level gate\n const rowEditable = this.#internalGrid.effectiveConfig?.rowEditable;\n if (rowEditable && !rowEditable(row as any)) return false;\n\n // Column-level check\n const { editable } = column;\n if (typeof editable === 'function') return editable(row);\n return editable === true;\n }\n\n /**\n * Check whether a column has ANY editability configured (static `true` or a\n * function). This is used for quick checks where no specific row is available\n * (e.g. \"does this row have any potentially-editable columns?\").\n */\n #hasEditableConfig(column: ColumnConfig<T>): boolean {\n return column.editable === true || typeof column.editable === 'function';\n }\n\n // #region Editing State (fully owned by plugin)\n\n /** Currently active edit row index, or -1 if not editing */\n #activeEditRow = -1;\n\n /** Row ID of the currently active edit row (stable across _rows replacement) */\n #activeEditRowId: string | undefined;\n\n /** Reference to the row object at edit-open time. Used as fallback in\n * #exitRowEdit when no row ID is available (prevents stale-index access). */\n #activeEditRowRef: T | undefined;\n\n /** Currently active edit column index, or -1 if not editing */\n #activeEditCol = -1;\n\n /** Snapshots of row data before editing started */\n #rowEditSnapshots = new Map<number, T>();\n\n /** Set of cells currently in edit mode: \"rowIndex:colIndex\" */\n #editingCells = new Set<string>();\n\n /**\n * Light-DOM elements whose declarative attributes have already been read.\n * The `editable` attribute (and `<tbw-grid-column-editor>` template) supply\n * the INITIAL state only — seeding once guarantees a later runtime/config\n * change to a falsy value is not re-applied on the next `processColumns`\n * pass (issue #272). Reset in `detach()` so a re-attached instance re-seeds.\n */\n #seededFromAttr = new WeakSet<HTMLElement>();\n\n /**\n * Value-change callbacks for active editors.\n * Keyed by \"rowIndex:field\" → callback that pushes updated values to the editor.\n * Populated during #injectEditor, cleaned up when editors are removed.\n */\n #editorValueCallbacks = new Map<string, (newValue: unknown) => void>();\n\n /** Flag to restore focus after next render (used when exiting edit mode) */\n #pendingFocusRestore = false;\n\n /** Row index pending animation after render, or -1 if none */\n #pendingRowAnimation = -1;\n\n /**\n * Cell validation manager — handles invalid-cell state tracking and DOM sync.\n * Initialized lazily in `attach()` since the sync callback needs grid access.\n */\n #validation!: CellValidationManager;\n\n /**\n * In grid mode, tracks whether an input field is currently focused.\n * When true: arrow keys work within input (edit mode).\n * When false: arrow keys navigate between cells (navigation mode).\n * Escape switches to navigation mode, Enter switches to edit mode.\n */\n #gridModeInputFocused = false;\n\n /**\n * In grid mode, when true, prevents inputs from auto-focusing.\n * This is set when Escape is pressed (navigation mode) and cleared\n * when Enter is pressed or user explicitly clicks an input.\n */\n #gridModeEditLocked = false;\n\n /**\n * When true, only a single cell is being edited (triggered by F2 or `beginCellEdit`).\n * Tab and Arrow keys commit and close the editor instead of navigating to adjacent cells.\n */\n #singleCellEdit = false;\n\n /**\n * In grid mode, snapshot of the focused cell's value when the editor first\n * receives focus. Used to revert on Escape (cell-level cancel).\n */\n #gridModeCellSnapshot: { rowIndex: number; colIndex: number; field: string; value: unknown } | null = null;\n\n // --- Dirty Tracking State (delegated to DirtyTrackingManager) ---\n\n /** Manages all dirty tracking state: baselines, changed/new/committed sets. */\n readonly #dirty = new DirtyTrackingManager<T>();\n\n /**\n * Cells currently mid-`cell-commit`, keyed `` `${rowId ?? rowIndex}\\0${field}` ``.\n * A `cell-commit` listener commonly cascades by calling `updateRow`, which\n * routes back through this commit pipeline synchronously. When such a nested\n * update targets a cell already in this set, `#commitCellValue` returns early\n * (the outer commit owns the single apply + `cell-edit-committed`), preventing\n * the infinite `updateRow → cell-commit → updateRow` recursion WITHOUT any\n * consumer-side re-entrancy guard and WITHOUT duplicating history or bypassing\n * a pending `preventDefault()`.\n */\n readonly #committingCells = new Set<string>();\n\n // --- Editor Injection Deps (cached for #injectEditor delegation) ---\n\n /** Dependency bag created once in `attach()` and reused by every `#injectEditor` call. */\n #editorDeps!: EditorInjectionDeps<T>;\n\n /**\n * Narrows the grid to its row type `T`. `GridElement` is intentionally\n * non-generic, so this accessor re-applies the plugin's own `T`.\n */\n get #internalGrid(): GridHost<T> {\n return this.grid;\n }\n\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n const signal = this.disconnectSignal;\n const internalGrid = this.#internalGrid;\n\n // Initialize cell validation manager with DOM sync callback\n this.#validation = new CellValidationManager((rowId, field, invalid) => {\n this.#syncInvalidCellAttribute(rowId, field, invalid);\n });\n\n // Initialize editor injection deps (cached for all #injectEditor calls)\n this.#editorDeps = {\n grid: internalGrid,\n isGridMode: this.#isGridMode,\n config: this.config,\n editingCells: this.#editingCells,\n editorValueCallbacks: this.#editorValueCallbacks,\n isEditSessionActive: () => this.#activeEditRow !== -1,\n commitCellValue: (ri, col, val, row) => this.#commitCellValue(ri, col, val, row),\n exitRowEdit: (ri, revert) => this.#exitRowEdit(ri, revert),\n };\n\n // Inject editing state and methods onto grid for backward compatibility\n this.#syncGridEditState();\n\n // Inject changedRows getter\n Object.defineProperty(grid, 'changedRows', {\n get: () => this.changedRows,\n configurable: true,\n });\n\n // Inject changedRowIds getter (new ID-based API)\n Object.defineProperty(grid, 'changedRowIds', {\n get: () => this.changedRowIds,\n configurable: true,\n });\n\n // Inject raw Set for O(1) lookup in the render hot path\n Object.defineProperty(grid, '_changedRowIdSet', {\n get: () => this.#dirty.changedRowIds,\n configurable: true,\n });\n\n // Inject resetChangedRows method\n (grid as any).resetChangedRows = (silent?: boolean) => this.resetChangedRows(silent);\n\n this.#attachRowModeListeners(signal, internalGrid);\n\n // In grid mode, request a full render to trigger afterCellRender hooks\n if (this.#isGridMode) {\n internalGrid._isGridEditMode = true;\n this.gridElement.classList.add('tbw-grid-mode');\n this.requestRender();\n this.#attachGridModeListeners(signal, internalGrid);\n }\n }\n\n /**\n * Row-mode editing wiring: document-level Escape/click-outside exit, the optional\n * focus trap, external `cell-change` push-down into open editors, and undo/redo\n * dirty re-evaluation. Registered unconditionally — each handler self-guards on\n * `#isGridMode` / its own config flag.\n */\n #attachRowModeListeners(signal: AbortSignal, internalGrid: GridHost<T>): void {\n // Document-level Escape to cancel editing (only in 'row' mode)\n document.addEventListener(\n 'keydown',\n (e: KeyboardEvent) => {\n // In grid mode, Escape doesn't exit edit mode\n if (this.#isGridMode) return;\n if (e.key === 'Escape' && this.#activeEditRow !== -1) {\n if (shouldPreventEditClose(this.config, e)) return;\n this.#exitRowEdit(this.#activeEditRow, true);\n }\n },\n { capture: true, signal },\n );\n\n // Click outside to commit editing (only in 'row' mode)\n // Use queueMicrotask to allow pending change events to fire first.\n // This is important for Angular/React editors where the (change) event\n // fires after mousedown but before mouseup/click.\n document.addEventListener(\n 'mousedown',\n (e: MouseEvent) => {\n // In grid mode, clicking outside doesn't exit edit mode\n if (this.#isGridMode) return;\n if (this.#activeEditRow === -1) return;\n const rowEl = internalGrid.findRenderedRowElement?.(this.#activeEditRow);\n if (!rowEl) return;\n const path = (e.composedPath && e.composedPath()) || [];\n if (path.includes(rowEl)) return;\n\n // Check if click is inside a registered external focus container\n // (e.g., overlays, datepickers, dropdowns at <body> level).\n // Only check targets OUTSIDE the grid — clicks on other rows inside\n // the grid should still commit the active edit row.\n const target = e.target as Node | null;\n if (target && !this.gridElement.contains(target) && this.grid.containsFocus?.(target)) {\n return;\n }\n\n // ARIA-expanded fallback (#251): when the click target lives inside\n // an overlay declared by an open combobox/listbox in the active edit\n // row (aria-expanded=\"true\" + aria-controls=<id>), treat it as part\n // of the editor. Covers Downshift / Headless UI / MUI Autocomplete\n // panels that opt out of registerExternalFocusContainer.\n if (target && !this.gridElement.contains(target)) {\n const rowEl = internalGrid.findRenderedRowElement?.(this.#activeEditRow);\n if (rowEl && isInsideOpenAriaOverlay(target, rowEl)) return;\n }\n\n if (shouldPreventEditClose(this.config, e)) return;\n\n // Delay exit to allow pending change/commit events to fire\n queueMicrotask(() => {\n if (this.#activeEditRow !== -1) {\n this.#exitRowEdit(this.#activeEditRow, false);\n }\n });\n },\n { signal },\n );\n\n // Focus trap: when enabled, prevent focus from leaving the grid\n // while a row is being edited. If focus moves outside the grid\n // (and its registered external containers), reclaim it.\n if (this.config.focusTrap) {\n this.gridElement.addEventListener(\n 'focusout',\n (e: FocusEvent) => {\n // Only trap in row mode when actively editing\n if (this.#isGridMode) return;\n if (this.#activeEditRow === -1) return;\n\n const related = e.relatedTarget as Node | null;\n // If focus is going to an external container, that's fine\n if (related && this.grid.containsFocus?.(related)) return;\n // If focus is going to another element inside the grid, allow it\n if (related && this.gridElement.contains(related)) return;\n\n // Focus left the grid entirely — reclaim it\n queueMicrotask(() => {\n // Re-check in case editing was committed in the meantime\n if (this.#activeEditRow === -1) return;\n this.#focusCurrentCellEditor();\n });\n },\n { signal },\n );\n }\n\n // Listen for external row mutations to push updated values to active editors.\n // When field A commits and sets field B via updateRow(), field B's editor\n // (if open) must reflect the new value.\n this.gridElement.addEventListener(\n 'cell-change',\n (e: Event) => {\n const detail = (e as CustomEvent).detail as {\n rowIndex: number;\n field: string;\n newValue: unknown;\n source: string;\n };\n // Only push updates from cascade/api sources — not from the editor's own commit\n if (detail.source === 'user') return;\n const key = `${detail.rowIndex}:${detail.field}`;\n const cb = this.#editorValueCallbacks.get(key);\n if (cb) cb(detail.newValue);\n },\n { signal },\n );\n\n // --- Dirty tracking: listen for undo/redo events to re-evaluate dirty state ---\n if (this.config.dirtyTracking) {\n const handleUndoRedo = (e: Event) => {\n const detail = (e as CustomEvent).detail as { action?: { rowIndex: number; field: string } };\n const action = detail?.action;\n if (!action) return;\n const row = this.rows[action.rowIndex] as T | undefined;\n if (!row) return;\n const rowId = this.#safeGetRowId(row);\n if (!rowId) return;\n const dirty = this.#dirty.isRowDirty(rowId, row);\n this.#emitDirtyChange(rowId, row, dirty ? 'modified' : 'pristine');\n };\n this.gridElement.addEventListener('undo', handleUndoRedo, { signal });\n this.gridElement.addEventListener('redo', handleUndoRedo, { signal });\n\n // Listen for row-inserted events to auto-mark new rows for dirty tracking\n this.on('row-inserted', (detail: { row: T; index: number }) => {\n const rowId = this.#safeGetRowId(detail.row);\n if (rowId != null) {\n this.markAsNew(String(rowId));\n }\n });\n }\n }\n\n /**\n * Grid-mode (\"spreadsheet\") editing wiring: focus/blur tracking that distinguishes\n * navigation mode from edit mode, Escape-to-navigation, and click-to-unlock.\n * Only registered when `editing.mode === 'grid'`.\n */\n #attachGridModeListeners(signal: AbortSignal, internalGrid: GridHost<T>): void {\n // Track focus/blur on inputs to maintain navigation vs edit mode state\n this.gridElement.addEventListener(\n 'focusin',\n (e: FocusEvent) => {\n const target = e.target as HTMLElement;\n // Ignore focus on the grid element itself — it has tabindex=0 so it\n // matches FOCUSABLE_EDITOR_SELECTOR, but blurring + re-focusing it\n // would cause infinite recursion.\n if (target === this.gridElement) return;\n if (target.matches(FOCUSABLE_EDITOR_SELECTOR)) {\n // If edit is locked (navigation mode), blur the input immediately\n if (this.#gridModeEditLocked) {\n target.blur();\n this.gridElement.focus();\n return;\n }\n\n // Snapshot cell value on initial focus or when moving to a different cell.\n // This allows Escape to revert the cell to its pre-edit value.\n const focusRow = internalGrid._focusRow;\n const focusCol = internalGrid._focusCol;\n const snap = this.#gridModeCellSnapshot;\n if (!snap || snap.rowIndex !== focusRow || snap.colIndex !== focusCol) {\n const column = internalGrid._visibleColumns?.[focusCol];\n const rowData = internalGrid._rows?.[focusRow];\n if (column?.field && rowData) {\n const field = column.field as string;\n this.#gridModeCellSnapshot = {\n rowIndex: focusRow,\n colIndex: focusCol,\n field,\n value: readCellField(rowData, field),\n };\n }\n }\n\n this.#gridModeInputFocused = true;\n }\n },\n { signal },\n );\n\n this.gridElement.addEventListener(\n 'focusout',\n (e: FocusEvent) => {\n const target = e.target as HTMLElement | null;\n const related = e.relatedTarget as HTMLElement | null;\n // Intra-editor focus moves MUST NOT flip the flag — the editor\n // is still logically focused. Cases observed in the wild:\n // - Native <select> opening: SELECT → child OPTION\n // - Native <select> popup ArrowDown: OPTION → sibling OPTION\n // - Framework editors moving focus to inner popup descendants\n // Detect via two ancestry checks: (a) `target` contains `related`\n // (parent-to-descendant), or (b) `related` lives inside an\n // editor element (input/select/textarea/contenteditable) — this\n // covers OPTION-to-OPTION and any other intra-editor traversal.\n // Exclude `gridElement` itself: it has tabindex=0 and so matches\n // FOCUSABLE_EDITOR_SELECTOR, but focus moving to the grid host\n // means we ARE leaving the editor — the explicit Escape/Enter\n // paths handle that by setting the flag to false themselves.\n if (target && related) {\n if (target.contains(related)) return;\n const relatedEditor = getEditorAncestor(related);\n if (relatedEditor && relatedEditor !== this.gridElement && this.gridElement.contains(relatedEditor)) {\n return;\n }\n }\n // Only clear if focus went outside grid (and external containers) or to a non-input element\n if (\n !related ||\n (!this.gridElement.contains(related) && !this.grid.containsFocus?.(related)) ||\n !related.matches(FOCUSABLE_EDITOR_SELECTOR)\n ) {\n this.#gridModeInputFocused = false;\n // Clear cell snapshot when leaving edit mode normally (not via Escape)\n this.#gridModeCellSnapshot = null;\n }\n },\n { signal },\n );\n\n // Handle Escape key directly on the grid element (capture phase)\n // This ensures we intercept Escape even when focus is inside an input\n this.gridElement.addEventListener(\n 'keydown',\n (e: KeyboardEvent) => {\n if (e.key === 'Escape' && this.#gridModeInputFocused) {\n // Check onBeforeEditClose to let overlays close first.\n if (shouldPreventEditClose(this.config, e)) {\n // Overlay is open — schedule deferred nav-mode transition\n // after the overlay tears down.\n queueMicrotask(() => {\n if (this.#gridModeInputFocused) {\n this.#enterGridModeNavigation();\n }\n });\n return;\n }\n this.#enterGridModeNavigation();\n e.preventDefault();\n e.stopPropagation();\n }\n },\n { capture: true, signal },\n );\n\n // Handle click on inputs - unlock edit mode when user explicitly clicks\n this.gridElement.addEventListener(\n 'mousedown',\n (e: MouseEvent) => {\n const target = e.target as HTMLElement;\n if (target.matches(FOCUSABLE_EDITOR_SELECTOR)) {\n this.#gridModeEditLocked = false; // User clicked input - allow edit\n }\n },\n { signal },\n );\n }\n\n /** @internal */\n override detach(): void {\n const internalGrid = this.#internalGrid;\n internalGrid._isGridEditMode = false;\n this.gridElement.classList.remove('tbw-grid-mode');\n this.#activeEditRow = -1;\n this.#activeEditRowId = undefined;\n this.#activeEditRowRef = undefined;\n this.#activeEditCol = -1;\n this.#rowEditSnapshots.clear();\n this.#dirty.clear();\n this.#editingCells.clear();\n this.#editorValueCallbacks.clear();\n this.#gridModeInputFocused = false;\n this.#gridModeEditLocked = false;\n this.#gridModeCellSnapshot = null;\n this.#singleCellEdit = false;\n this.#seededFromAttr = new WeakSet<HTMLElement>();\n super.detach();\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'isEditing') {\n // In grid mode, we're always editing\n return this.#isGridMode || this.#activeEditRow !== -1;\n }\n if (query.type === 'getCellEditableResolver') {\n // Return a predicate that applies the plugin's full per-cell editability\n // resolution (rowEditable gate + column.editable true/false/function).\n // Fields are mapped to columns once; consumers (e.g. clipboard paste)\n // then ask per cell without importing editing-owned config.\n const columns = (this.#internalGrid.effectiveConfig?.columns as ColumnConfig<T>[] | undefined) ?? [];\n const byField = new Map<string, ColumnConfig<T>>();\n for (const col of columns) byField.set(col.field, col);\n const resolver: CellEditablePredicate = (field, row) => {\n const col = byField.get(field);\n return col ? this.#isCellEditable(col, row as T) : false;\n };\n return resolver;\n }\n if (query.type === 'commitCellValue') {\n return this.#handleCommitCellValue(query.context as CommitCellValueContext);\n }\n return undefined;\n }\n\n /**\n * Answer the core `commitCellValue` query dispatched from `updateRow`/\n * `updateRows`. Routes the change through the full edit pipeline so\n * programmatic mutations participate in validation, dirty tracking, history,\n * and cascade — exactly like an interactive edit.\n *\n * @returns `true` when applied, `false` when a `cell-commit` handler vetoed\n * it (abortion), or `undefined` when the field/row can't be resolved (core\n * then applies the value directly).\n * @internal\n */\n #handleCommitCellValue(ctx: CommitCellValueContext): boolean | undefined {\n const internalGrid = this.#internalGrid;\n const columns = (internalGrid._visibleColumns as ColumnConfig<T>[] | undefined) ?? [];\n const column =\n columns.find((c) => c.field === ctx.field) ??\n (internalGrid._columns as ColumnConfig<T>[] | undefined)?.find((c) => c.field === ctx.field);\n const rowData =\n (ctx.row as T | undefined) ??\n (ctx.rowId != null ? internalGrid._getRowEntry(ctx.rowId)?.row : undefined) ??\n (internalGrid._rows?.[ctx.rowIndex] as T | undefined);\n\n if (ctx.source === 'sync') {\n // Declarative host sync (a framework adapter replacing its `rows` prop in\n // place). Authoritative external data, NOT a user edit: apply the value and\n // re-baseline the cell so the new value is the pristine truth — the row is\n // never marked dirty and no undo/redo history is recorded (and no cascade).\n // Handled before the column guard so non-column fields (dirty tracking\n // snapshots the whole row) are re-baselined too.\n if (!rowData || !isSafePropertyKey(ctx.field)) return undefined;\n writeCellField(rowData, ctx.field, ctx.newValue);\n invalidateAccessorCache(rowData as object);\n const rowId = this.#safeGetRowId(rowData);\n if (rowId && this.config.dirtyTracking) {\n this.#dirty.rebaselineCell(rowId, ctx.field, ctx.newValue);\n const stillDirty = this.#dirty.isRowDirty(rowId, rowData);\n if (!stillDirty) this.#dirty.changedRowIds.delete(rowId);\n this.#emitDirtyChange(rowId, rowData, stillDirty ? 'modified' : 'pristine');\n }\n return true;\n }\n\n if (!column || !rowData || !isSafePropertyKey(ctx.field)) return undefined; // core applies directly\n\n if (ctx.source === 'history') {\n // Undo/redo re-application: apply the value but DO NOT record a fresh\n // history entry or mark the row changed — the undo stack owns this change.\n // Recompute dirty so the row's changed flag reflects its baseline.\n writeCellField(rowData, ctx.field, ctx.newValue);\n invalidateAccessorCache(rowData as object);\n const rowId = this.#safeGetRowId(rowData);\n if (rowId && this.config.dirtyTracking) {\n const dirty = this.#dirty.isRowDirty(rowId, rowData);\n if (!dirty) this.#dirty.changedRowIds.delete(rowId);\n this.#emitDirtyChange(rowId, rowData, dirty ? 'modified' : 'pristine');\n }\n return true;\n }\n\n // Normal path: full commit pipeline (cancelable cell-commit for\n // validation/abortion, dirty tracking, history via cell-edit-committed,\n // cascade). #commitCellValue leaves the value unchanged when a handler\n // vetoes, so compare to detect abortion.\n this.#commitCellValue(ctx.rowIndex, column, ctx.newValue, rowData, ctx.source);\n return readCellField(rowData, ctx.field) === ctx.newValue;\n }\n\n // #endregion\n\n // #region Event Handlers (event distribution)\n\n /**\n * Handle cell clicks - start editing if configured for click mode.\n * Both click and dblclick events come through this handler.\n * Starts row-based editing (all editable cells in the row get editors).\n * @internal\n */\n override onCellClick(event: CellClickEvent): boolean | void {\n // In grid mode, all cells are already editable - no need to trigger row edit\n if (this.#isGridMode) return false;\n\n const internalGrid = this.#internalGrid;\n const editOn = this.config.editOn ?? internalGrid.effectiveConfig?.editOn;\n\n // Check if editing is disabled\n if (editOn === false || editOn === 'manual') return false;\n\n // Check if this is click or dblclick mode\n if (editOn !== 'click' && editOn !== 'dblclick') return false;\n\n // Check if the event type matches the edit mode\n const isDoubleClick = event.originalEvent.type === 'dblclick';\n if (editOn === 'click' && isDoubleClick) return false; // In click mode, only handle single clicks\n if (editOn === 'dblclick' && !isDoubleClick) return false; // In dblclick mode, only handle double clicks\n\n const { rowIndex } = event;\n\n // Check if any column in the row is potentially editable\n const hasEditableColumn = internalGrid._columns?.some((col) => this.#hasEditableConfig(col as ColumnConfig<T>));\n if (!hasEditableColumn) return false;\n\n // Row-level gate\n if (!this.#isRowEditable(internalGrid._rows[rowIndex] as T | undefined)) return false;\n\n // Start row-based editing (all editable cells get editors)\n event.originalEvent.stopPropagation();\n this.beginBulkEdit(rowIndex);\n return true; // Handled\n }\n\n /**\n * Handle keyboard events for edit lifecycle.\n * @internal\n */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n switch (event.key) {\n case 'Escape':\n return this.#onEscapeKey(event);\n case 'ArrowUp':\n case 'ArrowDown':\n case 'ArrowLeft':\n case 'ArrowRight':\n return this.#onArrowKey(event);\n case 'Tab':\n return this.#onTabKey(event);\n case ' ':\n case 'Spacebar':\n return this.#onSpaceKey(event);\n case 'Enter':\n // Modified Enter (Shift/Ctrl/Alt/Meta) is not ours — don't block it.\n if (event.shiftKey || event.ctrlKey || event.altKey || event.metaKey) return false;\n return this.#onEnterKey(event);\n case 'F2':\n return this.#onF2Key(event);\n default:\n // Don't block other keyboard events\n return false;\n }\n }\n\n /**\n * Escape: cancel the current edit (row mode) or leave edit mode (grid mode).\n *\n * NOTE: No `onBeforeEditClose` check here — the capture-phase handler is the\n * authoritative overlay guard. If the event reaches this bubble-phase handler,\n * either (a) the capture handler already bailed (overlay was open) and the\n * template handler (e.g. `select.close()`) addressed it, or (b) no overlay was\n * open. In both cases we should transition to navigation mode.\n */\n #onEscapeKey(event: KeyboardEvent): boolean {\n // In grid mode: revert cell, blur input, enter navigation mode.\n if (this.#isGridMode && this.#gridModeInputFocused) {\n this.#enterGridModeNavigation();\n // Update focus styling\n this.requestAfterRender();\n return true;\n }\n\n // In row mode: cancel edit\n if (this.#activeEditRow !== -1 && !this.#isGridMode) {\n if (shouldPreventEditClose(this.config, event)) return true;\n this.#exitRowEdit(this.#activeEditRow, true);\n return true;\n }\n\n return false;\n }\n\n /**\n * Arrow keys — decides whether the grid navigates or the editor keeps the key.\n *\n * `#gridModeInputFocused` is a cached flag, so `event.target` is used as a\n * fallback: a stale flag (e.g. between a native `<select>` popup opening and\n * our focusout/focusin guard updating it) must not hijack ArrowUp/Down away\n * from a focused editor. Uses `closest()` (not `matches()`) so descendants of\n * an editor — most notably `<option>` children of an open native `<select>`\n * popup — also count as \"keydown originating inside an editor\".\n */\n #onArrowKey(event: KeyboardEvent): boolean {\n const arrowEditorAncestor = getEditorAncestor(event.target);\n const targetIsEditor = !!arrowEditorAncestor && arrowEditorAncestor !== this.gridElement;\n const isVertical = event.key === 'ArrowUp' || event.key === 'ArrowDown';\n\n // Grid mode, no editor focused: let the grid's default navigation handle it.\n if (this.#isGridMode && !this.#gridModeInputFocused && !targetIsEditor) return false;\n\n // Grid mode with a focused editor: ArrowUp/Down belong to the editor\n // (e.g. ArrowDown opens autocomplete/datepicker overlays, ArrowUp/Down\n // navigates options). Handled: block grid navigation, let event reach editor.\n if (this.#isGridMode && (this.#gridModeInputFocused || targetIsEditor) && isVertical) return true;\n\n // Arrow Up/Down while a row is in edit mode (row mode): the editor owns\n // the key. The grid does NOT commit + jump to an adjacent row — the user\n // must explicitly leave edit mode (Enter / Escape / Tab / click) before\n // arrow keys resume cell navigation. Rationale:\n // - <input type=\"number\"> spinners must work natively\n // - <select> / native popups need ArrowUp/Down to traverse options\n // - <textarea> needs ArrowUp/Down to move the caret between lines\n // - Framework-adapter editors (Angular Material, MUI, etc.) commonly\n // bind ArrowUp/Down for autocomplete, datepicker, number-stepper,\n // and combobox interactions\n // Returning `true` blocks the core keyboard handler from running its\n // commit-and-navigate fallback (see `core/internal/keyboard.ts`'s\n // ArrowUp/Down switch case). The native event still reaches the focused\n // editor so it can consume it however it needs to.\n if (isVertical && this.#activeEditRow !== -1 && !this.#isGridMode) return true;\n\n return false;\n }\n\n /** Tab/Shift+Tab while editing: move to the next/previous editable cell. */\n #onTabKey(event: KeyboardEvent): boolean {\n if (this.#activeEditRow === -1 && !this.#isGridMode) return false;\n\n event.preventDefault();\n\n // In single-cell edit mode (F2), commit and close instead of navigating\n if (this.#singleCellEdit) {\n this.#exitRowEdit(this.#activeEditRow, false);\n return true;\n }\n\n this.#handleTabNavigation(!event.shiftKey);\n return true;\n }\n\n /** Space: toggle boolean cells (only when not editing — editors own their own space). */\n #onSpaceKey(event: KeyboardEvent): boolean {\n // If we're in row edit mode, let the event pass through to the editor (e.g., checkbox)\n if (this.#activeEditRow !== -1) return false;\n\n const internalGrid = this.#internalGrid;\n const focusRow = internalGrid._focusRow;\n const focusCol = internalGrid._focusCol;\n if (focusRow < 0 || focusCol < 0) return false;\n\n const column = internalGrid._visibleColumns[focusCol];\n const rowData = internalGrid._rows[focusRow];\n if (!column || !rowData || column.type !== 'boolean') return false;\n if (!this.#isCellEditable(column as ColumnConfig<T>, rowData as T)) return false;\n\n const field = column.field;\n // Space on a cell we cannot safely write - don't block keyboard navigation\n if (!isSafePropertyKey(field)) return false;\n\n this.#commitCellValue(focusRow, column, !readCellField(rowData, field), rowData);\n event.preventDefault();\n // Re-render to update the UI\n this.requestRender();\n return true;\n }\n\n /** Enter (unmodified): start row edit, commit, or enter edit mode in grid mode. */\n #onEnterKey(event: KeyboardEvent): boolean {\n // In grid mode when not editing: focus the current cell's input\n if (this.#isGridMode && !this.#gridModeInputFocused) {\n this.#focusCurrentCellEditor();\n return true;\n }\n\n if (this.#isGridMode && this.#gridModeInputFocused) return this.#onEnterWhileEditorFocused(event);\n\n if (this.#activeEditRow !== -1) {\n // ARIA-expanded fallback (#251): when the focused control declares\n // an open overlay via aria-expanded=\"true\" + aria-controls, defer\n // Enter to the overlay so combobox confirmation does not exit the\n // row. Mirrors the editor-injection.ts handler so the same guard\n // applies whether the editor host or the grid receives the event.\n const ariaTarget = event.target as HTMLElement | null;\n if (\n ariaTarget &&\n ariaTarget.getAttribute?.('aria-expanded') === 'true' &&\n ariaTarget.hasAttribute?.('aria-controls')\n ) {\n return false;\n }\n if (shouldPreventEditClose(this.config, event)) return true;\n // Already editing - let cell handlers deal with it\n return false;\n }\n\n return this.#beginRowEditFromEnter(event);\n }\n\n /**\n * Enter in grid mode while an editor (or its descendant — most notably an\n * `<option>` inside an open native `<select>` popup) has focus. Does NOT start\n * row-based editing or re-render. Two sub-cases:\n * - target is a **descendant** of an editor (popup option): let the browser's\n * native commit-and-close run untouched — calling `beginBulkEdit` /\n * re-rendering would destroy the open popup and abort the commit.\n * - target **is** the editor itself (focused SELECT after popup closed,\n * focused INPUT with no popup): commit the current value, blur the editor,\n * return focus to the grid so arrow keys resume cell navigation. Mirrors\n * Escape but accepts the value instead of reverting.\n */\n #onEnterWhileEditorFocused(event: KeyboardEvent): boolean {\n const enterEditorAncestor = getEditorAncestor(event.target);\n if (enterEditorAncestor && enterEditorAncestor !== event.target) {\n // Descendant — let native commit fire; do not interfere. Return true so\n // core's Enter handler (which would dispatch cell-activate) does not also\n // run. We don't call preventDefault, so the browser still commits the popup.\n return true;\n }\n // Editor itself — commit + blur + return to navigation mode.\n this.#gridModeCellSnapshot = null;\n const activeEl = document.activeElement as HTMLElement | null;\n if (activeEl && this.gridElement.contains(activeEl)) {\n activeEl.blur();\n this.gridElement.focus();\n }\n this.#gridModeInputFocused = false;\n this.#gridModeEditLocked = true;\n this.requestAfterRender();\n return true;\n }\n\n /**\n * Enter on a focused cell with no edit in progress: start row-based editing\n * (not just the focused cell), after giving consumers a cancelable\n * `cell-activate` event.\n */\n #beginRowEditFromEnter(event: KeyboardEvent): boolean {\n const internalGrid = this.#internalGrid;\n const editOn = this.config.editOn ?? internalGrid.effectiveConfig?.editOn;\n if (editOn === false || editOn === 'manual') return false;\n\n const focusRow = internalGrid._focusRow;\n const focusCol = internalGrid._focusCol;\n if (focusRow < 0) return false;\n\n // Check if ANY column in the row is potentially editable\n const hasEditableColumn = internalGrid._columns?.some((col) => this.#hasEditableConfig(col as ColumnConfig<T>));\n // Row-level gate. No editable columns - don't block keyboard navigation.\n const row = internalGrid._rows[focusRow];\n if (!hasEditableColumn || !this.#isRowEditable(row as T | undefined)) return false;\n\n // Emit cell-activate event BEFORE starting edit\n // This ensures consumers always get the activation event\n const column = internalGrid._visibleColumns[focusCol];\n const field = column?.field ?? '';\n const value = field && row ? readCellField(row, field) : undefined;\n const cellEl = this.gridElement.querySelector(`[data-row=\"${focusRow}\"][data-col=\"${focusCol}\"]`) as\n HTMLElement | undefined;\n\n const activateEvent = new CustomEvent('cell-activate', {\n cancelable: true,\n bubbles: true,\n detail: {\n rowIndex: focusRow,\n colIndex: focusCol,\n field,\n value,\n row,\n cellEl,\n trigger: 'keyboard' as const,\n originalEvent: event,\n },\n });\n this.gridElement.dispatchEvent(activateEvent);\n\n // If consumer canceled the activation, don't start editing\n if (activateEvent.defaultPrevented) {\n event.preventDefault();\n return true;\n }\n\n this.beginBulkEdit(focusRow);\n return true;\n }\n\n /** F2: begin single-cell edit on the focused cell. */\n #onF2Key(event: KeyboardEvent): boolean {\n if (this.#activeEditRow !== -1 || this.#isGridMode) return false;\n\n const internalGrid = this.#internalGrid;\n const editOn = this.config.editOn ?? internalGrid.effectiveConfig?.editOn;\n if (editOn === false) return false;\n\n const focusRow = internalGrid._focusRow;\n const focusCol = internalGrid._focusCol;\n if (focusRow < 0 || focusCol < 0) return false;\n\n const column = internalGrid._visibleColumns[focusCol];\n const rowData = internalGrid._rows[focusRow];\n if (!column || !rowData || !column.field) return false;\n if (!this.#isCellEditable(column as ColumnConfig<T>, rowData as T)) return false;\n\n event.preventDefault();\n this.beginCellEdit(focusRow, column.field);\n return true;\n }\n\n // #endregion\n\n // #region Render Hooks\n\n /**\n * Parse `data-*` attributes from a `<tbw-grid-type>` element into a camelCased map.\n */\n #readTypeParams(typeEl: HTMLElement): Record<string, unknown> {\n const params: Record<string, unknown> = {};\n for (const attr of Array.from(typeEl.attributes)) {\n if (!attr.name.startsWith('data-')) continue;\n const key = attr.name\n .slice(5)\n .replace(/-([a-z])/g, (_m, letter: string) => letter.toUpperCase())\n .trim();\n if (!key) continue;\n params[key] = attr.value;\n }\n return params;\n }\n\n /**\n * Seed type-level editor defaults from declarative `<tbw-grid-type>` light-DOM.\n *\n * This mirrors the column-level `<tbw-grid-column-editor>` behavior: editor\n * templates are editing-plugin-owned and only become active when the editing\n * plugin is imported.\n */\n #seedTypeEditorsFromLightDom(): void {\n const internalGrid = this.#internalGrid;\n const host = internalGrid._hostElement;\n if (!host) return;\n\n const effectiveConfig = internalGrid.effectiveConfig;\n if (!effectiveConfig) return;\n\n const typeElements = Array.from(host.children).filter((el) => el.tagName.toLowerCase() === 'tbw-grid-type');\n if (!typeElements.length) return;\n\n const adapter = internalGrid.__frameworkAdapter;\n const typeDefaults = (effectiveConfig.typeDefaults ??= {});\n\n for (let i = 0; i < typeElements.length; i++) {\n const typeEl = typeElements[i] as HTMLElement;\n const name = typeEl.getAttribute('name')?.trim();\n if (!name) continue;\n\n const existing = typeDefaults[name];\n // Programmatic (or already-seeded) editor always wins.\n if (existing?.editor) continue;\n\n const editorTpl = typeEl.querySelector('tbw-grid-column-editor') as HTMLElement | null;\n const editorTarget = (editorTpl ?? typeEl) as HTMLElement;\n\n let editor: TypeDefault<T>['editor'] | undefined = adapter?.canHandle?.(editorTarget)\n ? (adapter.createEditor?.(editorTarget) as TypeDefault<T>['editor'] | undefined)\n : undefined;\n\n if (!editor && editorTpl) {\n const params = this.#readTypeParams(typeEl);\n const compiled = compileTemplate(editorTpl.innerHTML);\n editor = ((ctx) =>\n compiled({\n row: ctx.row as T,\n value: ctx.value,\n field: ctx.field,\n column: ctx.column as ColumnInternal<T>,\n typeDefault: params,\n })) as TypeDefault<T>['editor'];\n }\n\n if (!editor) continue;\n\n typeDefaults[name] = { ...(existing ?? {}), editor };\n }\n }\n\n /**\n * Process columns to merge type-level editorParams with column-level and to\n * read editing-owned attributes from declarative `<tbw-grid-column>` markup.\n *\n * Column-level params take precedence over type-level. Editing-owned\n * attributes (`editable`, `<tbw-grid-column-editor>` template) are parsed\n * here from `col.__element` rather than in core, so the grid carries no\n * editing knowledge (issue #272).\n * @internal\n */\n override processColumns(columns: ColumnConfig<T>[]): ColumnConfig<T>[] {\n const internalGrid = this.#internalGrid;\n this.#seedTypeEditorsFromLightDom();\n const typeDefaults = (internalGrid as any).effectiveConfig?.typeDefaults;\n const adapter = internalGrid.__frameworkAdapter;\n const hasTypeDefaults = !!typeDefaults || !!adapter?.getTypeDefault;\n\n return columns.map((col) => {\n // Read editing-owned attributes from the originating light-DOM element.\n // Each element is seeded at most once: the attribute supplies the INITIAL\n // value only, so config and later runtime changes always win and are not\n // overridden by re-reading the attribute on subsequent passes (#272).\n const el = (col as ColumnInternal<T>).__element;\n if (el && !this.#seededFromAttr.has(el)) {\n this.#seededFromAttr.add(el);\n // `col.editable == null` lets a programmatic config value (including an\n // explicit `editable: false`) win over the attribute on this first pass.\n if (col.editable == null && el.hasAttribute('editable')) {\n col.editable = el.getAttribute('editable') !== 'false';\n }\n const internalCol = col as ColumnInternal<T>;\n if (!internalCol.__editorTemplate) {\n const editorTpl = el.querySelector('tbw-grid-column-editor');\n if (editorTpl) internalCol.__editorTemplate = editorTpl as HTMLElement;\n }\n }\n\n if (!col.type || !hasTypeDefaults) return col;\n\n // Get type-level editorParams\n let typeEditorParams: EditorParams | undefined;\n\n // Check grid-level typeDefaults first\n if (typeDefaults?.[col.type]?.editorParams) {\n typeEditorParams = typeDefaults[col.type].editorParams;\n }\n\n // Then check app-level (adapter) typeDefaults\n if (!typeEditorParams && adapter?.getTypeDefault) {\n const appDefault = adapter.getTypeDefault<T>(col.type, internalGrid._hostElement);\n if (appDefault?.editorParams) {\n typeEditorParams = appDefault.editorParams;\n }\n }\n\n // No type-level params to merge\n if (!typeEditorParams) return col;\n\n // Merge: type-level as base, column-level wins on conflicts\n return {\n ...col,\n editorParams: { ...typeEditorParams, ...col.editorParams },\n };\n });\n }\n\n /**\n * Stabilize the actively edited row across `rows` array replacements and\n * capture dirty tracking baselines.\n *\n * **Editing stability:** When the consumer reassigns `grid.rows` while\n * editing, the full pipeline (sort, filter, group) runs on the new data.\n * This hook finds the edited row in the new array by ID and swaps in the\n * in-progress row reference (`#activeEditRowRef`) so editors survive.\n *\n * **Dirty tracking baselines:** When `dirtyTracking` is enabled, captures\n * a `structuredClone` snapshot of each row on first appearance\n * (first-write-wins). This prevents Angular's feedback loop from\n * overwriting baselines.\n *\n * @internal Plugin API — part of the render pipeline\n */\n override processRows(rows: readonly T[]): T[] {\n const internalGrid = this.#internalGrid;\n\n // --- Dirty tracking: capture baselines (first-write-wins) ---\n if (this.config.dirtyTracking && internalGrid.getRowId) {\n this.#dirty.capture(rows, (r) => {\n try {\n return internalGrid.getRowId?.(r);\n } catch {\n return undefined;\n }\n });\n }\n\n // --- Editing stability: swap in the in-progress row ---\n if (this.#activeEditRow === -1 || this.#isGridMode) return rows as T[];\n\n const editRowId = this.#activeEditRowId;\n const editRowRef = this.#activeEditRowRef;\n\n // Without a stable row ID we cannot match across array replacements\n if (!editRowId || !editRowRef) return rows as T[];\n\n const result = [...rows] as T[];\n\n // Find the edited row's new position by ID\n let newIndex = -1;\n for (let i = 0; i < result.length; i++) {\n if (this.#safeGetRowId(result[i]) === editRowId) {\n newIndex = i;\n break;\n }\n }\n\n if (newIndex === -1) {\n // Row was deleted server-side — close the editor.\n // Cannot close synchronously during the processRows pipeline;\n // schedule for after the current render cycle completes.\n setTimeout(() => this.cancelActiveRowEdit(), 0);\n return result;\n }\n\n // Swap in the in-progress row data to preserve editor state\n result[newIndex] = editRowRef;\n\n // Update index-keyed state if the position changed (due to sort/filter)\n if (this.#activeEditRow !== newIndex) {\n this.#migrateEditRowIndex(this.#activeEditRow, newIndex);\n }\n\n return result;\n }\n\n /**\n * After render, reapply editors to cells in edit mode.\n * This handles virtualization - when a row scrolls back into view,\n * we need to re-inject the editor.\n * @internal\n */\n override afterRender(): void {\n const internalGrid = this.#internalGrid;\n\n // --- Editing stability: verify active edit row index ---\n // After processRows, subsequent plugins (filtering, grouping) may have\n // shifted row indices. Verify the index is still correct and fix if needed\n // before re-injecting editors.\n if (this.#activeEditRow !== -1 && this.#activeEditRowRef && !this.#isGridMode) {\n if (internalGrid._rows[this.#activeEditRow] !== this.#activeEditRowRef) {\n const newIndex = (internalGrid._rows as T[]).indexOf(this.#activeEditRowRef);\n if (newIndex !== -1) {\n this.#migrateEditRowIndex(this.#activeEditRow, newIndex);\n } else {\n // Row no longer in rendered set (filtered out or deleted)\n setTimeout(() => this.cancelActiveRowEdit(), 0);\n return;\n }\n }\n }\n\n // Restore focus after exiting edit mode\n if (this.#pendingFocusRestore) {\n this.#pendingFocusRestore = false;\n this.#restoreCellFocus(internalGrid);\n }\n\n // Animate the row after render completes (so the row element exists)\n if (this.#pendingRowAnimation !== -1) {\n const rowIndex = this.#pendingRowAnimation;\n this.#pendingRowAnimation = -1;\n internalGrid.animateRow?.(rowIndex, 'change');\n }\n\n // Emit baselines-captured event when new baselines were captured this cycle.\n // Emitted post-render so consumers can safely read grid.rows, query the DOM,\n // or call getOriginalRow() in their handler.\n const capturedCount = this.#dirty.drainCapturedFlag();\n if (capturedCount != null) {\n this.emit<BaselinesCapturedDetail>('baselines-captured', {\n count: capturedCount,\n });\n }\n\n // In 'grid' mode, editors are injected via afterCellRender hook during render\n if (this.#isGridMode) return;\n\n if (this.#editingCells.size === 0) return;\n\n // Re-inject editors for any editing cells that are visible\n for (const cellKey of this.#editingCells) {\n const [rowStr, colStr] = cellKey.split(':');\n const rowIndex = parseInt(rowStr, 10);\n const colIndex = parseInt(colStr, 10);\n\n const cellEl = this.#getCell(rowIndex, colIndex);\n if (!cellEl || cellEl.classList.contains('editing')) continue;\n\n // Cell is visible but not in editing mode - reinject editor\n const rowData = internalGrid._rows[rowIndex];\n const column = internalGrid._visibleColumns[colIndex];\n if (rowData && column) {\n this.#injectEditor(rowData, rowIndex, column, colIndex, cellEl, true);\n }\n }\n }\n\n /**\n * Hook called after each cell is rendered.\n * In grid mode, injects editors into editable cells during render (no DOM queries needed).\n * @internal\n */\n override afterCellRender(context: AfterCellRenderContext): void {\n const { row, rowIndex, column, colIndex, cellElement } = context;\n\n const editable = this.#isCellEditable(column as ColumnConfig<T>, row as T);\n\n // Set aria-readonly on non-editable cells so screen readers can distinguish\n if (!editable) {\n cellElement.setAttribute('aria-readonly', 'true');\n // In grid mode, tear down stale editors on cells that are no longer editable\n // (e.g., after virtualization recycles a row element for different row data)\n if (this.#isGridMode && cellElement.classList.contains('editing')) {\n cellElement.classList.remove('editing');\n const value = readCellField(row, (column as ColumnConfig<T>).field);\n cellElement.textContent = value == null ? '' : String(value);\n }\n } else {\n cellElement.removeAttribute('aria-readonly');\n }\n\n // Only inject editors in grid mode\n if (!this.#isGridMode) return;\n\n // Skip non-editable cells\n if (!editable) return;\n\n // Skip if already has editor\n if (cellElement.classList.contains('editing')) return;\n\n // Inject editor (don't track in editingCells - we're always editing in grid mode)\n // Pass rowElement so incrementEditingCount works even when cell is in a DocumentFragment\n this.#injectEditor(row as T, rowIndex, column as ColumnConfig<T>, colIndex, cellElement, true, context.rowElement);\n }\n\n /**\n * Apply dirty-tracking CSS classes to each rendered row.\n *\n * - `tbw-cell-dirty` on individual cells whose value differs from baseline\n * (applied on cell-commit, visible during editing)\n * - `tbw-row-dirty` on the row element only after the row edit session is\n * committed (edit-close without cancel)\n * - `tbw-row-new` when a row was inserted via `insertRow()` with no baseline\n *\n * Only active when `dirtyTracking: true`.\n *\n * @internal Plugin API\n */\n override afterRowRender(context: AfterRowRenderContext): void {\n if (!this.config.dirtyTracking) return;\n\n const internalGrid = this.#internalGrid;\n const rowId = internalGrid.getRowId?.(context.row as T);\n if (!rowId) return;\n\n const { isNew, isCommittedDirty, hasBaseline } = this.#dirty.getRowDirtyState(rowId, context.row as T);\n\n const el = context.rowElement;\n\n // Row-level classes (tbw-row-dirty only after row-commit AND data differs)\n el.classList.toggle('tbw-row-dirty', isCommittedDirty);\n el.classList.toggle('tbw-row-new', isNew);\n\n // Cell-level classes (tbw-cell-dirty on individual cells with changed values)\n // Only run the per-cell loop when the row has a baseline — avoids\n // querySelectorAll on the hot path for rows without dirty tracking state.\n if (hasBaseline) {\n const cells = el.querySelectorAll('.cell[data-field]');\n for (let i = 0; i < cells.length; i++) {\n const cell = cells[i] as HTMLElement;\n const field = cell.getAttribute('data-field');\n if (field) {\n cell.classList.toggle('tbw-cell-dirty', this.#dirty.isCellDirty(rowId, context.row as T, field));\n }\n }\n } else {\n // Clean up stale tbw-cell-dirty classes on recycled row elements\n // that previously displayed a dirty row but now show a pristine one.\n const dirtyCells = el.querySelectorAll('.tbw-cell-dirty');\n for (let i = 0; i < dirtyCells.length; i++) {\n dirtyCells[i].classList.remove('tbw-cell-dirty');\n }\n }\n }\n\n /**\n * On scroll render, reapply editors to recycled cells.\n * @internal\n */\n override onScrollRender(): void {\n this.afterRender();\n }\n\n // #endregion\n\n // #region Public API\n\n /**\n * Get all rows that have been modified.\n * Uses ID-based lookup for stability when rows are reordered.\n */\n get changedRows(): T[] {\n return this.#dirty.getChangedRows((id) => this.grid.getRow(id) as T | undefined);\n }\n\n /**\n * Get IDs of all modified rows.\n */\n get changedRowIds(): string[] {\n return this.#dirty.getChangedRowIds();\n }\n\n /**\n * Get the currently active edit row index, or -1 if not editing.\n */\n get activeEditRow(): number {\n return this.#activeEditRow;\n }\n\n /**\n * Get the currently active edit column index, or -1 if not editing.\n */\n get activeEditCol(): number {\n return this.#activeEditCol;\n }\n\n /**\n * Check if a specific row is currently being edited.\n */\n isRowEditing(rowIndex: number): boolean {\n return this.#activeEditRow === rowIndex;\n }\n\n /**\n * Check if a specific cell is currently being edited.\n */\n isCellEditing(rowIndex: number, colIndex: number): boolean {\n return this.#editingCells.has(`${rowIndex}:${colIndex}`);\n }\n\n /**\n * Check if a specific row has been modified.\n * @param rowIndex - Row index to check (will be converted to ID internally)\n */\n isRowChanged(rowIndex: number): boolean {\n const internalGrid = this.#internalGrid;\n const row = internalGrid._rows[rowIndex];\n if (!row) return false;\n try {\n const rowId = internalGrid.getRowId?.(row);\n return rowId ? this.#dirty.isRowChanged(rowId) : false;\n } catch {\n return false;\n }\n }\n\n /**\n * Check if a row with the given ID has been modified.\n * @param rowId - Row ID to check\n */\n isRowChangedById(rowId: string): boolean {\n return this.#dirty.isRowChanged(rowId);\n }\n\n // #region Dirty Tracking API (delegated to DirtyTrackingManager)\n\n /** Check if a row differs from its baseline. Requires `dirtyTracking: true`. */\n isDirty(rowId: string): boolean {\n if (!this.config.dirtyTracking) return false;\n if (this.#dirty.newRowIds.has(rowId)) return true;\n const row = this.grid.getRow(rowId) as T | undefined;\n if (!row) return false;\n return this.#dirty.isRowDirty(rowId, row);\n }\n\n /** Inverse of `isDirty`. */\n isPristine(rowId: string): boolean {\n return !this.isDirty(rowId);\n }\n\n /** Whether any row in the grid is dirty. */\n get dirty(): boolean {\n if (!this.config.dirtyTracking) return false;\n const internalGrid = this.#internalGrid;\n return this.#dirty.hasAnyDirty((rowId) => internalGrid._getRowEntry(rowId)?.row as T | undefined);\n }\n\n /** Whether all rows are pristine. */\n get pristine(): boolean {\n return !this.dirty;\n }\n\n /** Re-snapshot baseline from current data (call after a successful save). */\n markAsPristine(rowId: string): void {\n if (!this.config.dirtyTracking) return;\n const row = this.grid.getRow(rowId) as T | undefined;\n if (!row) return;\n this.#dirty.markPristine(rowId, row);\n // After mark-pristine, original === current — emit row as the canonical value.\n this.emit<DirtyChangeDetail<T>>('dirty-change', {\n rowId,\n row,\n original: row,\n type: 'pristine',\n });\n }\n\n /** Mark a row as new (auto-called by `insertRow()` when dirty tracking is on). */\n markAsNew(rowId: string): void {\n if (!this.config.dirtyTracking) return;\n this.#dirty.markNew(rowId);\n const row = this.grid.getRow(rowId) as T | undefined;\n // `original` is intentionally undefined for new rows — emit directly\n // rather than via #emitDirtyChange (which always derives original from\n // the baseline map).\n this.emit<DirtyChangeDetail<T>>('dirty-change', {\n rowId,\n row: row as T,\n original: undefined,\n type: 'new',\n });\n }\n\n /** Mark a row as dirty after an external mutation that bypassed the editing pipeline. */\n markAsDirty(rowId: string): void {\n if (!this.config.dirtyTracking) return;\n const row = this.grid.getRow(rowId) as T | undefined;\n if (!row) return;\n this.#dirty.markDirty(rowId);\n this.#emitDirtyChange(rowId, row, 'modified');\n }\n\n /** Mark all tracked rows as pristine (call after a batch save). */\n markAllPristine(): void {\n if (!this.config.dirtyTracking) return;\n const internalGrid = this.#internalGrid;\n this.#dirty.markAllPristine((rowId) => internalGrid._getRowEntry(rowId)?.row as T | undefined);\n }\n\n /** Get a deep clone of the original (baseline) row data. Returns `undefined` for new rows. */\n getOriginalRow(rowId: string): T | undefined {\n if (!this.config.dirtyTracking) return undefined;\n return this.#dirty.getOriginalRow(rowId);\n }\n\n /** Lightweight check for whether a baseline exists (no cloning). */\n hasBaseline(rowId: string): boolean {\n if (!this.config.dirtyTracking) return false;\n return this.#dirty.hasBaseline(rowId);\n }\n\n /** Get all dirty rows with their original and current data. */\n getDirtyRows(): DirtyRowEntry<T>[] {\n if (!this.config.dirtyTracking) return [];\n const internalGrid = this.#internalGrid;\n return this.#dirty.getDirtyRows((rowId) => internalGrid._getRowEntry(rowId)?.row as T | undefined);\n }\n\n /**\n * Get IDs of all dirty rows.\n */\n get dirtyRowIds(): string[] {\n if (!this.config.dirtyTracking) return [];\n const internalGrid = this.#internalGrid;\n return this.#dirty.getDirtyRowIds((rowId) => internalGrid._getRowEntry(rowId)?.row as T | undefined);\n }\n\n /**\n * Revert a row to its baseline values (mutates the current row in-place).\n * Triggers a re-render.\n *\n * @param rowId - Row ID (from `getRowId`)\n */\n revertRow(rowId: string): void {\n if (!this.config.dirtyTracking) return;\n const row = this.grid.getRow(rowId) as T | undefined;\n if (!row) return;\n if (this.#dirty.revertRow(rowId, row)) {\n this.#emitDirtyChange(rowId, row, 'reverted');\n this.requestRender();\n }\n }\n\n /**\n * Revert all dirty rows to their baseline values and re-render.\n */\n revertAll(): void {\n if (!this.config.dirtyTracking) return;\n const internalGrid = this.#internalGrid;\n this.#dirty.revertAll((rowId) => internalGrid._getRowEntry(rowId)?.row as T | undefined);\n this.requestRender();\n }\n\n // #endregion\n\n // #region Cell Validation (delegated to CellValidationManager)\n\n /**\n * Mark a cell as invalid with an optional validation message.\n * Invalid cells are marked with a `data-invalid` attribute for styling.\n *\n * @param rowId - The row ID (from getRowId)\n * @param field - The field name\n * @param message - Optional validation message (for tooltips or display)\n *\n * @example\n * ```typescript\n * // In cell-commit handler:\n * grid.on('cell-commit', (detail, e) => {\n * if (detail.field === 'email' && !isValidEmail(detail.value)) {\n * detail.setInvalid('Invalid email format');\n * }\n * });\n *\n * // Or programmatically:\n * editingPlugin.setInvalid('row-123', 'email', 'Invalid email format');\n * ```\n */\n setInvalid(rowId: string, field: string, message = ''): void {\n this.#validation.setInvalid(rowId, field, message);\n }\n\n /** Clear the invalid state for a specific cell. */\n clearInvalid(rowId: string, field: string): void {\n this.#validation.clearInvalid(rowId, field);\n }\n\n /** Clear all invalid cells for a specific row. */\n clearRowInvalid(rowId: string): void {\n this.#validation.clearRowInvalid(rowId);\n }\n\n /** Clear all invalid cell states across all rows. */\n clearAllInvalid(): void {\n this.#validation.clearAllInvalid();\n }\n\n /** Check if a specific cell is marked as invalid. */\n isCellInvalid(rowId: string, field: string): boolean {\n return this.#validation.isCellInvalid(rowId, field);\n }\n\n /** Get the validation message for an invalid cell. */\n getInvalidMessage(rowId: string, field: string): string | undefined {\n return this.#validation.getInvalidMessage(rowId, field);\n }\n\n /** Check if a row has any invalid cells. */\n hasInvalidCells(rowId: string): boolean {\n return this.#validation.hasInvalidCells(rowId);\n }\n\n /** Get all invalid fields for a row. */\n getInvalidFields(rowId: string): Map<string, string> {\n return this.#validation.getInvalidFields(rowId);\n }\n\n // #endregion\n\n /**\n * Reset all change tracking.\n * @param silent - If true, suppresses the `changed-rows-reset` event\n * @fires changed-rows-reset - Emitted when tracking is reset (unless silent)\n */\n resetChangedRows(silent?: boolean): void {\n const rows = this.changedRows;\n const ids = this.changedRowIds;\n this.#dirty.changedRowIds.clear();\n this.#dirty.committedDirtyRowIds.clear();\n this.#syncGridEditState();\n\n if (!silent) {\n this.emit<ChangedRowsResetDetail<T>>('changed-rows-reset', { rows, ids });\n }\n\n // Clear visual indicators\n const internalGrid = this.#internalGrid;\n internalGrid._rowPool?.forEach((r) => r.classList.remove('changed'));\n }\n\n /**\n * Programmatically begin editing a cell.\n * @param rowIndex - Index of the row to edit\n * @param field - Field name of the column to edit\n * @fires cell-commit - Emitted when the cell value is committed (on blur or Enter)\n */\n beginCellEdit(rowIndex: number, field: string): void {\n const internalGrid = this.#internalGrid;\n const colIndex = internalGrid._visibleColumns.findIndex((c) => c.field === field);\n if (colIndex === -1) return;\n\n const column = internalGrid._visibleColumns[colIndex];\n const rowData = internalGrid._rows[rowIndex];\n if (!column || !rowData || !this.#isCellEditable(column as ColumnConfig<T>, rowData as T)) return;\n\n const cellEl = this.#getCell(rowIndex, colIndex);\n if (!cellEl) return;\n\n this.#singleCellEdit = true;\n this.#beginCellEdit(rowIndex, colIndex, cellEl);\n }\n\n /**\n * Programmatically begin editing all editable cells in a row.\n * @param rowIndex - Index of the row to edit\n * @fires cell-commit - Emitted for each cell value that is committed\n * @fires row-commit - Emitted when focus leaves the row\n */\n beginBulkEdit(rowIndex: number): void {\n const internalGrid = this.#internalGrid;\n const editOn = this.config.editOn ?? internalGrid.effectiveConfig?.editOn;\n if (editOn === false) return;\n\n const hasEditableColumn = internalGrid._columns?.some((col) => this.#hasEditableConfig(col as ColumnConfig<T>));\n if (!hasEditableColumn) return;\n\n const rowEl = internalGrid.findRenderedRowElement?.(rowIndex);\n if (!rowEl) return;\n\n // Row-level gate\n const rowData = internalGrid._rows[rowIndex];\n if (!this.#isRowEditable(rowData as T | undefined)) return;\n\n // Bulk edit clears single-cell mode\n this.#singleCellEdit = false;\n\n // Start row edit\n this.#startRowEdit(rowIndex, rowData);\n\n // Enter edit mode on all editable cells\n Array.from(rowEl.children).forEach((cell, i) => {\n const col = internalGrid._visibleColumns[i];\n if (col && this.#isCellEditable(col as ColumnConfig<T>, rowData as T)) {\n const cellEl = cell as HTMLElement;\n if (!cellEl.classList.contains('editing')) {\n this.#injectEditor(rowData, rowIndex, col, i, cellEl, true);\n }\n }\n });\n\n // Focus the first editable cell\n setTimeout(() => {\n let targetCell = rowEl.querySelector(`.cell[data-col=\"${internalGrid._focusCol}\"]`);\n if (!targetCell?.classList.contains('editing')) {\n targetCell = rowEl.querySelector('.cell.editing');\n }\n if (targetCell?.classList.contains('editing')) {\n const editor = (targetCell as HTMLElement).querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n try {\n editor?.focus({ preventScroll: true });\n } catch {\n /* empty */\n }\n }\n }, 0);\n }\n\n /**\n * Commit the currently active row edit.\n * @fires row-commit - Emitted after the row edit is committed\n */\n commitActiveRowEdit(): void {\n if (this.#activeEditRow !== -1) {\n this.#exitRowEdit(this.#activeEditRow, false);\n }\n }\n\n /**\n * Cancel the currently active row edit.\n */\n cancelActiveRowEdit(): void {\n if (this.#activeEditRow !== -1) {\n this.#exitRowEdit(this.#activeEditRow, true);\n }\n }\n\n // #endregion\n\n // #region Internal Methods\n\n // --- Small private helpers (centralised to keep call sites uniform) ---\n\n /**\n * Safely resolve a row's ID via the configured `getRowId`. Returns\n * `undefined` when no ID can be derived (no `getRowId` callback, or it\n * threw — e.g. row has no key).\n */\n #safeGetRowId(row: T | undefined | null): string | undefined {\n if (!row) return undefined;\n try {\n return this.#internalGrid.getRowId?.(row);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Resolve a rendered cell element by row + column index. Returns `null`\n * when the row is not currently rendered or the cell is missing.\n */\n #getCell(rowIndex: number, colIndex: number): HTMLElement | null {\n const rowEl = this.#internalGrid.findRenderedRowElement?.(rowIndex);\n return (rowEl?.querySelector(`.cell[data-col=\"${colIndex}\"]`) as HTMLElement | null) ?? null;\n }\n\n /**\n * Row-level editability gate. Returns `false` only when\n * `gridConfig.rowEditable` is configured AND vetoes the row. Rows without\n * data return `true` (defer to the column-level check).\n */\n #isRowEditable(rowData: T | undefined): boolean {\n if (!rowData) return true;\n const rowEditable = this.#internalGrid.effectiveConfig?.rowEditable;\n if (!rowEditable) return true;\n return rowEditable(rowData as any) !== false;\n }\n\n /**\n * Emit a `dirty-change` event with the canonical `{ rowId, row, original, type }`\n * shape. Centralises baseline lookup so every emit site uses the same\n * source of truth.\n */\n #emitDirtyChange(rowId: string, row: T | undefined, type: DirtyChangeDetail<T>['type']): void {\n this.emit<DirtyChangeDetail<T>>('dirty-change', {\n rowId,\n row: row as T,\n original: this.#dirty.getOriginalRow(rowId),\n type,\n });\n }\n\n /**\n * Grid-mode \"Escape → navigation mode\" transition: revert the cell from\n * the focus snapshot, blur the active editor, return focus to the grid,\n * and flip the navigation/lock flags. Used by the capture-phase Escape\n * handler (both deferred and sync branches) and the bubble-phase Escape\n * handler in `onKeyDown`.\n */\n #enterGridModeNavigation(): void {\n this.#revertGridModeCellEdit();\n const activeEl = document.activeElement as HTMLElement | null;\n if (activeEl && this.gridElement.contains(activeEl)) {\n activeEl.blur();\n this.gridElement.focus();\n }\n this.#gridModeInputFocused = false;\n this.#gridModeEditLocked = true;\n }\n\n /**\n * Restore a row to its snapshot values and clear all per-row dirty\n * bookkeeping. Called both from the explicit-revert path and from the\n * `row-commit` cancellation path in `#exitRowEdit`.\n */\n #revertRowFromSnapshot(rowId: string | undefined, current: T, snapshot: T | undefined): void {\n if (!snapshot) return;\n Object.keys(snapshot as object).forEach((k) => {\n (current as Record<string, unknown>)[k] = (snapshot as Record<string, unknown>)[k];\n });\n if (rowId) {\n this.#dirty.changedRowIds.delete(rowId);\n this.#dirty.committedDirtyRowIds.delete(rowId);\n this.clearRowInvalid(rowId);\n }\n }\n\n /**\n * Sync the data-invalid attribute on a cell element.\n * Used as the DOM callback for CellValidationManager.\n */\n #syncInvalidCellAttribute(rowId: string, field: string, invalid: boolean): void {\n const internalGrid = this.#internalGrid;\n const colIndex = internalGrid._visibleColumns?.findIndex((c) => c.field === field);\n if (colIndex === -1 || colIndex === undefined) return;\n\n // Find the row element by rowId\n const rows = internalGrid._rows;\n const rowIndex = rows?.findIndex((r) => this.#safeGetRowId(r as T) === rowId);\n if (rowIndex === -1 || rowIndex === undefined) return;\n\n const cellEl = this.#getCell(rowIndex, colIndex);\n if (!cellEl) return;\n\n if (invalid) {\n cellEl.setAttribute('data-invalid', 'true');\n // `data-invalid` is styling only; `aria-invalid` is what actually reaches a\n // screen reader (SC 3.3.1 Error Identification).\n cellEl.setAttribute('aria-invalid', 'true');\n const message = this.#validation.getInvalidMessage(rowId, field);\n if (message) {\n cellEl.setAttribute('title', message);\n // Hand the title over: core would otherwise reclaim it as its own\n // truncation tooltip on the next hover and overwrite the message.\n cellEl.removeAttribute(GridDataAttrs.TRUNCATED);\n }\n } else {\n cellEl.removeAttribute('data-invalid');\n cellEl.removeAttribute('aria-invalid');\n cellEl.removeAttribute('title');\n }\n }\n\n /**\n * Migrate all index-keyed editing state when the active edit row moves to\n * a different position in `_rows` (e.g. after sort, filter, or new data push).\n *\n * Updates: `#activeEditRow`, `#editingCells`, `#rowEditSnapshots`,\n * `#editorValueCallbacks`, and syncs `_activeEditRows` on the grid.\n */\n #migrateEditRowIndex(oldIndex: number, newIndex: number): void {\n this.#activeEditRow = newIndex;\n\n // Migrate #editingCells keys (\"rowIndex:colIndex\")\n const migratedCells = new Set<string>();\n const prefix = `${oldIndex}:`;\n for (const cellKey of this.#editingCells) {\n if (cellKey.startsWith(prefix)) {\n migratedCells.add(`${newIndex}:${cellKey.substring(prefix.length)}`);\n } else {\n migratedCells.add(cellKey);\n }\n }\n this.#editingCells.clear();\n for (const key of migratedCells) {\n this.#editingCells.add(key);\n }\n\n // Migrate #rowEditSnapshots key\n const snapshot = this.#rowEditSnapshots.get(oldIndex);\n if (snapshot !== undefined) {\n this.#rowEditSnapshots.delete(oldIndex);\n this.#rowEditSnapshots.set(newIndex, snapshot);\n }\n\n // Migrate #editorValueCallbacks keys (\"rowIndex:field\")\n const updates: [string, (newValue: unknown) => void][] = [];\n for (const [key, cb] of this.#editorValueCallbacks) {\n if (key.startsWith(prefix)) {\n updates.push([`${newIndex}:${key.substring(prefix.length)}`, cb]);\n this.#editorValueCallbacks.delete(key);\n }\n }\n for (const [key, cb] of updates) {\n this.#editorValueCallbacks.set(key, cb);\n }\n\n // Sync the grid's rendering state so rows.ts checks the correct index\n this.#syncGridEditState();\n }\n\n /**\n * Begin editing a single cell.\n */\n #beginCellEdit(rowIndex: number, colIndex: number, cellEl: HTMLElement): void {\n const internalGrid = this.#internalGrid;\n const rowData = internalGrid._rows[rowIndex];\n const column = internalGrid._visibleColumns[colIndex];\n\n if (!rowData || !column || !this.#isCellEditable(column as ColumnConfig<T>, rowData as T)) return;\n if (cellEl.classList.contains('editing')) return;\n\n // Start row edit if not already\n if (this.#activeEditRow !== rowIndex) {\n this.#startRowEdit(rowIndex, rowData);\n }\n\n this.#activeEditCol = colIndex;\n this.#injectEditor(rowData, rowIndex, column, colIndex, cellEl, false);\n }\n\n /**\n * Revert the focused cell's value from the snapshot taken when the editor\n * first received focus, then emit a `cell-cancel` event so framework\n * adapters (e.g., GridFormArray) can revert their FormControls.\n *\n * Called by the grid-mode Escape handlers (both capture and bubble phase).\n */\n #revertGridModeCellEdit(): void {\n const snapshot = this.#gridModeCellSnapshot;\n if (!snapshot) return;\n\n const internalGrid = this.#internalGrid;\n const rowData = internalGrid._rows?.[snapshot.rowIndex];\n if (rowData) {\n writeCellField(rowData, snapshot.field, snapshot.value);\n }\n\n // Push the reverted value to the editor's input element so that the\n // subsequent blur-commit (triggered by activeEl.blur()) reads the\n // reverted value instead of the user's typed text. This makes the\n // blur-commit a no-op (oldValue === newValue) and prevents it from\n // overwriting the revert.\n const callbackKey = `${snapshot.rowIndex}:${snapshot.field}`;\n const cb = this.#editorValueCallbacks.get(callbackKey);\n if (cb) cb(snapshot.value);\n\n // Notify framework adapters to revert FormControls\n this.emit<CellCancelDetail>('cell-cancel', {\n rowIndex: snapshot.rowIndex,\n colIndex: snapshot.colIndex,\n field: snapshot.field,\n previousValue: snapshot.value,\n });\n\n // After reverting, clean up changedRowIds so the built-in `.changed` class\n // toggle in rows.ts doesn't fight with consumer's rowClass callback.\n // changedRowIds.add() is unconditional during commit, so cleanup must also\n // be unconditional — otherwise the Set retains stale IDs when dirtyTracking\n // is disabled and the built-in toggle re-adds `.changed` on every render.\n if (rowData) {\n const rowId = this.#safeGetRowId(rowData as T);\n if (rowId) {\n if (this.config.dirtyTracking) {\n // With dirty tracking, only remove if the row has no other dirty cells\n if (!this.#dirty.isRowDirty(rowId, rowData as T)) {\n this.#dirty.changedRowIds.delete(rowId);\n this.#emitDirtyChange(rowId, rowData as T, 'reverted');\n }\n } else {\n // Without dirty tracking there's no baseline to compare, so always\n // remove — the consumer manages their own change state via rowClass.\n this.#dirty.changedRowIds.delete(rowId);\n }\n }\n }\n\n // Always re-render after revert so rowClass callbacks re-evaluate\n // (e.g., consumer may toggle a 'changed' class based on local state\n // updated in response to the cell-cancel event above).\n this.requestRender();\n\n this.#gridModeCellSnapshot = null;\n }\n\n /**\n * Focus the editor input in the currently focused cell (grid mode only).\n * Used when pressing Enter to enter edit mode from navigation mode.\n */\n #focusCurrentCellEditor(): void {\n const internalGrid = this.#internalGrid;\n const focusRow = internalGrid._focusRow;\n const focusCol = internalGrid._focusCol;\n\n if (focusRow < 0 || focusCol < 0) return;\n\n const cellEl = this.#getCell(focusRow, focusCol);\n\n if (cellEl?.classList.contains('editing')) {\n const editor = cellEl.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n if (editor) {\n this.#gridModeEditLocked = false; // Unlock edit mode - user pressed Enter\n editor.focus();\n this.#gridModeInputFocused = true;\n // Select all text in text inputs for quick replacement\n if (editor instanceof HTMLInputElement && (editor.type === 'text' || editor.type === 'number')) {\n editor.select();\n }\n }\n }\n }\n\n /**\n * Handle Tab/Shift+Tab navigation while editing.\n * Moves to next/previous editable cell, staying in edit mode.\n * Wraps to next/previous row when reaching row boundaries.\n */\n #handleTabNavigation(forward: boolean): void {\n const internalGrid = this.#internalGrid;\n const rows = internalGrid._rows;\n // In grid mode, use focusRow since there's no active edit row\n const currentRow = this.#isGridMode ? internalGrid._focusRow : this.#activeEditRow;\n const currentRowData = rows[currentRow] as T;\n\n // Get editable column indices for the CURRENT row\n const editableCols = internalGrid._visibleColumns\n .map((c, i) => (currentRowData && this.#isCellEditable(c as ColumnConfig<T>, currentRowData) ? i : -1))\n .filter((i) => i >= 0);\n if (editableCols.length === 0) return;\n\n const currentIdx = editableCols.indexOf(internalGrid._focusCol);\n const nextIdx = currentIdx + (forward ? 1 : -1);\n\n // Can move within same row?\n if (nextIdx >= 0 && nextIdx < editableCols.length) {\n internalGrid._focusCol = editableCols[nextIdx];\n const cellEl = this.#getCell(currentRow, editableCols[nextIdx]);\n if (cellEl?.classList.contains('editing')) {\n const editor = cellEl.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n editor?.focus({ preventScroll: true });\n }\n ensureCellVisible(internalGrid, { forceHorizontalScroll: true });\n return;\n }\n\n // Can move to adjacent row?\n const nextRow = currentRow + (forward ? 1 : -1);\n if (nextRow >= 0 && nextRow < rows.length) {\n const nextRowData = rows[nextRow] as T;\n // Compute editable columns for the next row\n const nextEditableCols = internalGrid._visibleColumns\n .map((c, i) => (nextRowData && this.#isCellEditable(c as ColumnConfig<T>, nextRowData) ? i : -1))\n .filter((i) => i >= 0);\n if (nextEditableCols.length === 0) return; // Next row has no editable cells\n\n // In grid mode, just move focus (all rows are always editable)\n if (this.#isGridMode) {\n internalGrid._focusRow = nextRow;\n internalGrid._focusCol = forward ? nextEditableCols[0] : nextEditableCols[nextEditableCols.length - 1];\n ensureCellVisible(internalGrid, { forceHorizontalScroll: true });\n // Focus the editor in the new cell after render\n this.requestAfterRender();\n setTimeout(() => {\n const cellEl = this.#getCell(nextRow, internalGrid._focusCol);\n if (cellEl?.classList.contains('editing')) {\n const editor = cellEl.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n editor?.focus({ preventScroll: true });\n }\n }, 0);\n } else {\n // In row mode, commit current row and enter next row\n this.#exitRowEdit(currentRow, false);\n internalGrid._focusRow = nextRow;\n internalGrid._focusCol = forward ? nextEditableCols[0] : nextEditableCols[nextEditableCols.length - 1];\n this.beginBulkEdit(nextRow);\n ensureCellVisible(internalGrid, { forceHorizontalScroll: true });\n }\n }\n // else: at boundary - stay put\n }\n\n /**\n * Sync the internal grid state with the plugin's editing state.\n */\n #syncGridEditState(): void {\n const internalGrid = this.#internalGrid;\n internalGrid._activeEditRows = this.#activeEditRow;\n internalGrid._rowEditSnapshots = this.#rowEditSnapshots;\n }\n\n /**\n * Snapshot original row data and mark as editing.\n */\n #startRowEdit(rowIndex: number, rowData: T): void {\n if (this.#activeEditRow !== rowIndex) {\n // Commit the previous row before starting a new one\n if (this.#activeEditRow !== -1) {\n this.#exitRowEdit(this.#activeEditRow, false);\n }\n this.#rowEditSnapshots.set(rowIndex, { ...rowData });\n this.#activeEditRow = rowIndex;\n this.#activeEditRowRef = rowData;\n\n // Store stable row ID for resilience against _rows replacement during editing\n this.#activeEditRowId = this.#safeGetRowId(rowData);\n\n this.#syncGridEditState();\n\n // Broadcast edit-open so consumers (DOM listeners) AND other plugins\n // (notably SelectionPlugin via the plugin event bus) stay in sync with\n // the row currently being edited. Issue #284.\n // Row mode only — in grid mode every row is perpetually editable.\n if (!this.#isGridMode) {\n this.broadcast<EditOpenDetail<T>>('edit-open', {\n rowIndex,\n rowId: this.#activeEditRowId ?? '',\n row: rowData,\n });\n announce(this.gridElement, getA11yMessage(this.gridElement, 'editingStarted', rowIndex));\n }\n }\n }\n\n /**\n * Exit editing for a row.\n */\n #exitRowEdit(rowIndex: number, revert: boolean): void {\n if (this.#activeEditRow !== rowIndex) return;\n\n const internalGrid = this.#internalGrid;\n const snapshot = this.#rowEditSnapshots.get(rowIndex);\n const rowEl = internalGrid.findRenderedRowElement?.(rowIndex);\n const { rowId, current } = this.#resolveEditedRow(rowIndex);\n\n // Collect and commit values from active editors before re-rendering\n if (!revert && rowEl && current) {\n this.#commitActiveEditors(rowEl, rowIndex, current);\n }\n\n // Flush managed editors (framework adapters) before clearing state.\n // At this point the commit() callback is still active, so editors can\n // synchronously commit their pending values in response to this event.\n if (!revert && !this.#isGridMode && current) {\n this.emit<BeforeEditCloseDetail<T>>('before-edit-close', {\n rowIndex,\n rowId: rowId ?? '',\n row: current,\n });\n }\n\n // Revert if requested\n if (revert && current) {\n this.#revertRowFromSnapshot(rowId, current, snapshot);\n } else if (!revert && current) {\n this.#finalizeRowCommit(rowIndex, rowId, current, snapshot);\n }\n\n this.#clearRowEditState(rowIndex);\n\n // Mark that focus should be restored after the upcoming render completes.\n // This must be set BEFORE refreshVirtualWindow because it calls afterRender()\n // synchronously, which reads this flag.\n this.#pendingFocusRestore = true;\n\n // Re-render the row to remove editors\n if (rowEl) {\n this.#teardownRowEditors(rowEl, internalGrid);\n } else {\n // Row not visible - restore focus immediately (no render will happen)\n this.#restoreCellFocus(internalGrid);\n this.#pendingFocusRestore = false;\n }\n\n // Broadcast edit-close (row mode only, fires for both commit and revert)\n // so consumers AND other plugins receive it. Issue #284.\n if (!this.#isGridMode && current) {\n this.broadcast<EditCloseDetail<T>>('edit-close', {\n rowIndex,\n rowId: rowId ?? '',\n row: current,\n reverted: revert,\n });\n if (!revert) {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'editingCommitted', rowIndex));\n }\n }\n }\n\n /**\n * Resolve the row being edited using the stored row ID.\n *\n * The `_rows` array may have been replaced (e.g. Angular pushing new rows via\n * directive effect) since editing started, so `_rows[rowIndex]` could point to\n * a completely different row — the ID map is always up to date. Without an ID\n * we fall back to the row reference stored at edit-open (`#activeEditRowRef`),\n * which is safer than the possibly-stale `_rows[rowIndex]`.\n */\n #resolveEditedRow(rowIndex: number): { rowId: string | undefined; current: T | undefined } {\n const internalGrid = this.#internalGrid;\n let rowId = this.#activeEditRowId;\n const entry = rowId ? internalGrid._getRowEntry(rowId) : undefined;\n const current = entry?.row ?? this.#activeEditRowRef ?? internalGrid._rows[rowIndex];\n\n if (!rowId && current) {\n rowId = this.#safeGetRowId(current);\n }\n return { rowId, current };\n }\n\n /**\n * Read pending values out of every native editor in the row and commit the\n * ones that actually changed.\n */\n #commitActiveEditors(rowEl: HTMLElement, rowIndex: number, current: T): void {\n const internalGrid = this.#internalGrid;\n rowEl.querySelectorAll('.cell.editing').forEach((cell) => {\n const colIndex = Number((cell as HTMLElement).getAttribute('data-col'));\n if (isNaN(colIndex)) return;\n const col = internalGrid._visibleColumns[colIndex];\n if (!col) return;\n\n // Skip cells with externally-managed editors (framework adapters like Angular/React/Vue).\n // These editors handle their own commits via the commit() callback - we should NOT\n // try to read values from their DOM inputs (which may contain formatted display values).\n if ((cell as HTMLElement).hasAttribute('data-editor-managed')) return;\n\n const input = cell.querySelector('input,textarea,select') as\n HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null;\n if (!input) return;\n\n const field = col.field;\n const originalValue = readCellField(current, field) as T[keyof T];\n const val = getInputValue(input, col, originalValue);\n if (originalValue !== val) {\n this.#commitCellValue(rowIndex, col, val, current);\n }\n });\n }\n\n /**\n * Emit the cancelable `row-commit` event and apply its outcome — revert on\n * `preventDefault()`, otherwise refresh committed-dirty tracking and queue the\n * change animation.\n */\n #finalizeRowCommit(rowIndex: number, rowId: string | undefined, current: T, snapshot: T | undefined): void {\n // Compare snapshot vs current to detect if changes were made during THIS edit session\n const changedThisSession = hasRowChanged(snapshot, current);\n\n // Check if this row has any cumulative changes (via ID tracking)\n // Fall back to session-based detection when no row ID is available\n const changed = rowId ? this.#dirty.changedRowIds.has(rowId) : changedThisSession;\n\n const cancelled = this.emitCancelable<RowCommitDetail<T>>('row-commit', {\n rowIndex,\n rowId: rowId ?? '',\n row: current,\n oldValue: snapshot,\n newValue: current,\n changed,\n changedRows: this.changedRows,\n changedRowIds: this.changedRowIds,\n });\n\n // If consumer called preventDefault(), revert the row\n if (cancelled) {\n if (snapshot) this.#revertRowFromSnapshot(rowId, current, snapshot);\n return;\n }\n\n // Mark row as committed-dirty if it has actual changes vs baseline\n if (rowId && this.config.dirtyTracking) {\n if (this.#dirty.isRowDirty(rowId, current)) {\n this.#dirty.committedDirtyRowIds.add(rowId);\n } else {\n this.#dirty.committedDirtyRowIds.delete(rowId);\n }\n }\n\n if (changedThisSession && this.isAnimationEnabled) {\n // Animate the row only if changes were made during this edit session\n // (deferred to afterRender so the row element exists after re-render)\n this.#pendingRowAnimation = rowIndex;\n }\n }\n\n /**\n * Clear all per-row editing bookkeeping.\n *\n * The `#editingCells` / `#editorValueCallbacks` keys use the rowIndex captured\n * at edit-open time. Even if `_rows` was replaced and the row moved to a\n * different index, the keys still match what was inserted during this session.\n */\n #clearRowEditState(rowIndex: number): void {\n this.#rowEditSnapshots.delete(rowIndex);\n this.#activeEditRow = -1;\n this.#activeEditRowId = undefined;\n this.#activeEditRowRef = undefined;\n this.#activeEditCol = -1;\n this.#singleCellEdit = false;\n this.#syncGridEditState();\n\n for (const cellKey of this.#editingCells) {\n if (cellKey.startsWith(`${rowIndex}:`)) {\n this.#editingCells.delete(cellKey);\n }\n }\n for (const callbackKey of this.#editorValueCallbacks.keys()) {\n if (callbackKey.startsWith(`${rowIndex}:`)) {\n this.#editorValueCallbacks.delete(callbackKey);\n }\n }\n }\n\n /**\n * Release framework editor components, drop the editing state from the cells\n * and re-render the row so the display values come back.\n */\n #teardownRowEditors(rowEl: HTMLElement, internalGrid: InternalGrid<T>): void {\n // Release framework editor components (Angular/React/Vue) BEFORE clearing\n // editing state. This ensures releaseCell runs while the editor DOM is\n // still inside each cell, so the adapter can find and destroy ComponentRefs.\n // Without this, overlay editors (BaseOverlayEditor) leak panels on <body>\n // with active MutationObservers that react to cell-focus class changes.\n const adapter = internalGrid.__frameworkAdapter;\n const editingCells = rowEl.querySelectorAll('.cell.editing');\n if (adapter?.releaseCell) {\n editingCells.forEach((cell) => {\n adapter.releaseCell!(cell as HTMLElement);\n });\n }\n\n // Remove editing class and re-render cells\n editingCells.forEach((cell) => {\n cell.classList.remove('editing');\n clearEditingState(cell.parentElement as RowElementInternal);\n });\n\n // Refresh the virtual window to restore cell content WITHOUT rebuilding\n // the row model. requestRender() would trigger processRows (ROWS phase)\n // which re-sorts — causing the edited row to jump to a new position and\n // disappear from view. refreshVirtualWindow re-renders visible cells from\n // the current _rows order, keeping the row in place until the user\n // explicitly sorts again or new data arrives.\n internalGrid.refreshVirtualWindow(true);\n }\n\n /**\n * Commit a single cell value change.\n * Uses ID-based change tracking for stability when rows are reordered.\n */\n #commitCellValue(\n rowIndex: number,\n column: ColumnConfig<T>,\n newValue: unknown,\n rowData: T,\n source: UpdateSource = 'user',\n ): void {\n const field = column.field;\n if (!isSafePropertyKey(field)) return;\n const oldValue = readCellField(rowData, field);\n if (oldValue === newValue) return;\n\n const internalGrid = this.#internalGrid;\n\n // Get row ID for change tracking (may not exist if getRowId not configured)\n const rowId = this.#safeGetRowId(rowData);\n\n const firstTime = rowId ? !this.#dirty.changedRowIds.has(rowId) : true;\n\n // Create updateRow helper for cascade updates (noop if row has no ID)\n const updateRow: (changes: Partial<T>) => void = rowId\n ? (changes) => this.grid.updateRow(rowId!, changes as Record<string, unknown>, 'cascade')\n : noopUpdateRow;\n\n // Track whether setInvalid was called during event handling\n let invalidWasSet = false;\n\n // Create setInvalid callback for validation (noop if row has no ID)\n const setInvalid = rowId\n ? (message?: string) => {\n invalidWasSet = true;\n this.setInvalid(rowId!, field, message ?? '');\n }\n : () => {}; // eslint-disable-line @typescript-eslint/no-empty-function\n\n // Emit cancelable event BEFORE applying the value.\n //\n // Re-entrancy guard: a `cell-commit` listener commonly cascades by calling\n // `detail.updateRow()` / `grid.updateRow()` (which route back through this\n // commit pipeline) or forces a row re-render the same way. If that nested\n // update targets the SAME cell that is still mid-commit, re-emitting\n // `cell-commit` would recurse until the call stack overflows\n // (`RangeError: Maximum call stack size exceeded`).\n //\n // When we detect a re-entrant commit of a cell already in flight we RETURN\n // EARLY rather than re-applying: the OUTER commit still owns this cell and\n // will apply the value + emit `cell-edit-committed` exactly once when its\n // own emit returns. Re-applying here would instead (a) fire a duplicate\n // `cell-edit-committed` → a phantom UndoRedo history entry, and (b) sneak\n // the value in even when the outer listener called `preventDefault()`,\n // bypassing the cancelable-commit contract. Cascades to OTHER cells still\n // emit normally, and the set is keyed per (row, field) so distinct fields\n // can never form an unbounded chain.\n const commitKey = `${rowId ?? rowIndex}\\u0000${field}`;\n if (this.#committingCells.has(commitKey)) return;\n\n let cancelled = false;\n this.#committingCells.add(commitKey);\n try {\n cancelled = this.emitCancelable<CellCommitDetail<T>>('cell-commit', {\n row: rowData,\n rowId: rowId ?? '',\n field,\n oldValue,\n value: newValue,\n source,\n rowIndex,\n changedRows: this.changedRows,\n changedRowIds: this.changedRowIds,\n firstTimeForRow: firstTime,\n updateRow,\n setInvalid,\n });\n } finally {\n this.#committingCells.delete(commitKey);\n }\n\n // If consumer called preventDefault(), abort the commit\n if (cancelled) return;\n\n // Clear any previous invalid state for this cell ONLY if setInvalid wasn't called\n // (if setInvalid was called, the handler wants it to remain invalid)\n if (rowId && !invalidWasSet && this.isCellInvalid(rowId, field)) {\n this.clearInvalid(rowId, field);\n }\n\n // Apply the value and mark row as changed.\n // Whole-row invalidation (not per-`field`): `field` here is this column's\n // own key, but OTHER columns' `valueAccessor`s may derive from it while\n // being cached under their own `column.field`. Per-field invalidation would\n // refresh only this column and leave those dependent columns stale.\n writeCellField(rowData, field, newValue);\n invalidateAccessorCache(rowData as object);\n if (rowId) {\n this.#dirty.changedRowIds.add(rowId);\n }\n this.#syncGridEditState();\n\n // Emit dirty-change event if dirty tracking is enabled\n if (this.config.dirtyTracking && rowId) {\n const dirty = this.#dirty.isRowDirty(rowId, rowData);\n this.#emitDirtyChange(rowId, rowData, dirty ? 'modified' : 'pristine');\n }\n\n // Notify other plugins (e.g., UndoRedoPlugin) about the committed edit\n this.emitPluginEvent('cell-edit-committed', {\n rowIndex,\n field,\n oldValue,\n newValue,\n });\n\n // Mark the row visually as changed (animation happens when row edit closes)\n const rowEl = internalGrid.findRenderedRowElement?.(rowIndex);\n if (rowEl) {\n rowEl.classList.add('changed');\n }\n }\n\n /**\n * Inject an editor into a cell.\n * Delegates to the extracted `editor-injection` module.\n */\n #injectEditor(\n rowData: T,\n rowIndex: number,\n column: ColumnConfig<T>,\n colIndex: number,\n cell: HTMLElement,\n skipFocus: boolean,\n parentRowEl?: HTMLElement,\n ): void {\n injectEditorImpl(this.#editorDeps, rowData, rowIndex, column, colIndex, cell, skipFocus, parentRowEl);\n }\n\n /**\n * Restore focus to cell after exiting edit mode.\n */\n #restoreCellFocus(internalGrid: InternalGrid<T>): void {\n queueMicrotask(() => {\n try {\n const rowIdx = internalGrid._focusRow;\n const colIdx = internalGrid._focusCol;\n const rowEl = internalGrid.findRenderedRowElement?.(rowIdx);\n if (rowEl) {\n Array.from(internalGrid._bodyEl.querySelectorAll('.cell-focus')).forEach((el) =>\n el.classList.remove('cell-focus'),\n );\n const cell = rowEl.querySelector(`.cell[data-row=\"${rowIdx}\"][data-col=\"${colIdx}\"]`) as HTMLElement | null;\n if (cell) {\n cell.classList.add('cell-focus');\n cell.setAttribute('aria-selected', 'true');\n if (!cell.hasAttribute('tabindex')) cell.setAttribute('tabindex', '-1');\n cell.focus({ preventScroll: true });\n }\n }\n } catch {\n /* empty */\n }\n });\n }\n\n // #endregion\n}\n"],"mappings":"sEAoBA,IAgBa,EAsBF,UAmDE,EAWA,qBCzGA,EAAsC,CACjD,YAAA,CAAc,EAAQ,IAAc,aAAa,MAAW,IAC5D,YAAA,IAAmB,eACnB,cAAgB,GAAW,qBAAqB,IAChD,cAAgB,GAAW,uBAAuB,IAClD,kBAAA,IAAyB,sBACzB,cAAA,CAAgB,EAAM,IAAU,SAAS,eAAkB,SAC3D,eAAiB,GAAS,SAAS,cACnC,iBAAmB,GAAU,GAAG,kBAChC,cAAA,IAAqB,kBACrB,UAAY,GAAa,cAAc,EAAW,IAClD,eAAiB,GAAU,UAAU,aACrC,uBAAyB,GAAU,GAAG,qBACtC,uBAAA,IAA8B,2BAC9B,qBAAuB,GACV,WAAX,EACI,iDACA,iDACN,eAAiB,GAAa,eAAe,EAAW,IACxD,iBAAmB,GAAa,OAAO,EAAW,UAClD,WAAa,GAAU,GAAG,iBAqBf,EAA0C,CACrD,OAAQ,IACR,SAAU,IACV,QAAS,IACT,SAAU,IACV,SAAU,IACV,aAAc,IACd,WAAY,KACZ,UAAW,IACX,OAAQ,GACR,aAAc,GACd,MAAO,OC6IT,SAAgB,EAAS,EAAqB,GAG5C,IAAK,EAAQ,OAKb,IAAoC,KAHlC,oBAAqB,EAChB,EAA0D,qBAC3D,IACM,MAAM,cAAyB,OAE3C,MAAM,EAAK,EAAO,gBAAgB,gBAC7B,IAEL,EAAG,YAAc,GAI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