@toolbox-web/grid 3.9.2 → 3.10.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.
Files changed (123) hide show
  1. package/all.js +1 -1
  2. package/all.js.map +1 -1
  3. package/index.js +1 -1
  4. package/index.js.map +1 -1
  5. package/lib/core/types.d.ts +6 -3
  6. package/lib/features/clipboard.js.map +1 -1
  7. package/lib/features/column-virtualization.js.map +1 -1
  8. package/lib/features/context-menu.js.map +1 -1
  9. package/lib/features/editing.js.map +1 -1
  10. package/lib/features/export.js.map +1 -1
  11. package/lib/features/filtering.js.map +1 -1
  12. package/lib/features/grouping-columns.js.map +1 -1
  13. package/lib/features/grouping-rows.js.map +1 -1
  14. package/lib/features/master-detail.js.map +1 -1
  15. package/lib/features/multi-sort.js.map +1 -1
  16. package/lib/features/pinned-columns.js.map +1 -1
  17. package/lib/features/pinned-rows.js.map +1 -1
  18. package/lib/features/pivot.js.map +1 -1
  19. package/lib/features/print.js.map +1 -1
  20. package/lib/features/registry.js +1 -1
  21. package/lib/features/registry.js.map +1 -1
  22. package/lib/features/reorder-columns.js.map +1 -1
  23. package/lib/features/responsive.js.map +1 -1
  24. package/lib/features/row-drag-drop.js.map +1 -1
  25. package/lib/features/selection.js.map +1 -1
  26. package/lib/features/server-side.js.map +1 -1
  27. package/lib/features/shell.js.map +1 -1
  28. package/lib/features/sticky-rows.js.map +1 -1
  29. package/lib/features/tooltip.js.map +1 -1
  30. package/lib/features/tree.js.map +1 -1
  31. package/lib/features/undo-redo.js.map +1 -1
  32. package/lib/features/visibility.js.map +1 -1
  33. package/lib/plugins/clipboard/index.js.map +1 -1
  34. package/lib/plugins/column-virtualization/index.js.map +1 -1
  35. package/lib/plugins/context-menu/index.js.map +1 -1
  36. package/lib/plugins/editing/editors.d.ts +15 -0
  37. package/lib/plugins/editing/index.js +1 -1
  38. package/lib/plugins/editing/index.js.map +1 -1
  39. package/lib/plugins/editing/internal/helpers.d.ts +23 -0
  40. package/lib/plugins/editing/types.d.ts +16 -1
  41. package/lib/plugins/export/index.js +1 -1
  42. package/lib/plugins/export/index.js.map +1 -1
  43. package/lib/plugins/filtering/filter-model.d.ts +20 -1
  44. package/lib/plugins/filtering/filter-panel-default.d.ts +15 -1
  45. package/lib/plugins/filtering/index.d.ts +1 -1
  46. package/lib/plugins/filtering/index.js +1 -1
  47. package/lib/plugins/filtering/index.js.map +1 -1
  48. package/lib/plugins/filtering/types.d.ts +58 -3
  49. package/lib/plugins/grouping-columns/index.js.map +1 -1
  50. package/lib/plugins/grouping-rows/index.js +1 -1
  51. package/lib/plugins/grouping-rows/index.js.map +1 -1
  52. package/lib/plugins/hierarchy/index.js.map +1 -1
  53. package/lib/plugins/master-detail/index.js +1 -1
  54. package/lib/plugins/master-detail/index.js.map +1 -1
  55. package/lib/plugins/master-detail/master-detail-plugin.d.ts +6 -1
  56. package/lib/plugins/multi-sort/index.js.map +1 -1
  57. package/lib/plugins/pinned-columns/index.js.map +1 -1
  58. package/lib/plugins/pinned-rows/index.js.map +1 -1
  59. package/lib/plugins/pivot/index.js +1 -1
  60. package/lib/plugins/pivot/index.js.map +1 -1
  61. package/lib/plugins/pivot/pivot-plugin.d.ts +2 -0
  62. package/lib/plugins/pivot/types.d.ts +2 -0
  63. package/lib/plugins/print/index.js.map +1 -1
  64. package/lib/plugins/reorder-columns/index.js.map +1 -1
  65. package/lib/plugins/responsive/index.js.map +1 -1
  66. package/lib/plugins/row-drag-drop/index.js.map +1 -1
  67. package/lib/plugins/selection/index.js +1 -1
  68. package/lib/plugins/selection/index.js.map +1 -1
  69. package/lib/plugins/server-side/index.js.map +1 -1
  70. package/lib/plugins/shared/form-field-target.d.ts +10 -0
  71. package/lib/plugins/shared/format-value.d.ts +12 -0
  72. package/lib/plugins/shared/structural-toggle.d.ts +14 -0
  73. package/lib/plugins/shell/index.js.map +1 -1
  74. package/lib/plugins/sticky-rows/index.js.map +1 -1
  75. package/lib/plugins/tooltip/index.js.map +1 -1
  76. package/lib/plugins/tree/index.js +1 -1
  77. package/lib/plugins/tree/index.js.map +1 -1
  78. package/lib/plugins/undo-redo/index.d.ts +1 -1
  79. package/lib/plugins/undo-redo/index.js +1 -1
  80. package/lib/plugins/undo-redo/index.js.map +1 -1
  81. package/lib/plugins/undo-redo/types.d.ts +20 -2
  82. package/lib/plugins/undo-redo/undo-redo-plugin.d.ts +8 -0
  83. package/lib/plugins/visibility/index.js.map +1 -1
  84. package/package.json +1 -1
  85. package/umd/grid.all.umd.js +1 -1
  86. package/umd/grid.all.umd.js.map +1 -1
  87. package/umd/grid.umd.js +1 -1
  88. package/umd/grid.umd.js.map +1 -1
  89. package/umd/plugins/clipboard.umd.js.map +1 -1
  90. package/umd/plugins/column-virtualization.umd.js.map +1 -1
  91. package/umd/plugins/context-menu.umd.js.map +1 -1
  92. package/umd/plugins/editing.umd.js +1 -1
  93. package/umd/plugins/editing.umd.js.map +1 -1
  94. package/umd/plugins/export.umd.js +1 -1
  95. package/umd/plugins/export.umd.js.map +1 -1
  96. package/umd/plugins/filtering.umd.js +1 -1
  97. package/umd/plugins/filtering.umd.js.map +1 -1
  98. package/umd/plugins/grouping-columns.umd.js.map +1 -1
  99. package/umd/plugins/grouping-rows.umd.js +1 -1
  100. package/umd/plugins/grouping-rows.umd.js.map +1 -1
  101. package/umd/plugins/hierarchy.umd.js.map +1 -1
  102. package/umd/plugins/master-detail.umd.js +1 -1
  103. package/umd/plugins/master-detail.umd.js.map +1 -1
  104. package/umd/plugins/multi-sort.umd.js.map +1 -1
  105. package/umd/plugins/pinned-columns.umd.js.map +1 -1
  106. package/umd/plugins/pinned-rows.umd.js.map +1 -1
  107. package/umd/plugins/pivot.umd.js +1 -1
  108. package/umd/plugins/pivot.umd.js.map +1 -1
  109. package/umd/plugins/print.umd.js.map +1 -1
  110. package/umd/plugins/reorder-columns.umd.js.map +1 -1
  111. package/umd/plugins/responsive.umd.js.map +1 -1
  112. package/umd/plugins/row-drag-drop.umd.js.map +1 -1
  113. package/umd/plugins/selection.umd.js +1 -1
  114. package/umd/plugins/selection.umd.js.map +1 -1
  115. package/umd/plugins/server-side.umd.js.map +1 -1
  116. package/umd/plugins/shell.umd.js.map +1 -1
  117. package/umd/plugins/sticky-rows.umd.js.map +1 -1
  118. package/umd/plugins/tooltip.umd.js.map +1 -1
  119. package/umd/plugins/tree.umd.js +1 -1
  120. package/umd/plugins/tree.umd.js.map +1 -1
  121. package/umd/plugins/undo-redo.umd.js +1 -1
  122. package/umd/plugins/undo-redo.umd.js.map +1 -1
  123. package/umd/plugins/visibility.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/internal/aria.ts","../../../../../../libs/grid/src/lib/core/internal/utils.ts","../../../../../../libs/grid/src/lib/core/plugin/expander-column.ts","../../../../../../libs/grid/src/lib/plugins/shared/drag-alternative-menu.ts","../../../../../../libs/grid/src/lib/plugins/selection/column-selection.ts","../../../../../../libs/grid/src/lib/plugins/selection/range-selection.ts","../../../../../../libs/grid/src/lib/plugins/selection/selection.css?inline","../../../../../../libs/grid/src/lib/plugins/selection/touch-selection.ts","../../../../../../libs/grid/src/lib/plugins/selection/selection-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 * 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<Required<A11yMessages>[K]>\n): string {\n type MessageFn = (...a: Parameters<Required<A11yMessages>[K]>) => 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 MessageFn | undefined;\n if (customFn) return customFn(...args);\n return (DEFAULT_A11Y_MESSAGES[key] as MessageFn)(...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 ? '&#x1F5F9;' : '&#9744;'}</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 * Shared Expander Column Utilities\n *\n * Provides a fixed expander column for plugins that need expand/collapse icons\n * (MasterDetail, Tree, RowGrouping). The column is:\n * - Always first in the grid\n * - Cannot be reordered (lockPosition: true)\n * - Has no header (empty string)\n * - Has no right border (borderless styling)\n * - Narrow width (just fits the icon)\n */\n\nimport type { ColumnConfig } from '../types';\n\n/** Special field name for the expander column */\nexport const EXPANDER_COLUMN_FIELD = '__tbw_expander';\n\n/** Default width for the expander column (pixels) */\nexport const EXPANDER_COLUMN_WIDTH = 32;\n\n/**\n * Marker interface for expander column renderers.\n * Used to detect if expander column is already present.\n */\nexport interface ExpanderColumnRenderer {\n (ctx: any): HTMLElement;\n __expanderColumn?: true;\n /** Plugin name that created this expander */\n __expanderPlugin?: string;\n}\n\n/**\n * Check if a column is an expander column.\n */\nexport function isExpanderColumn(column: ColumnConfig): boolean {\n return column.field === EXPANDER_COLUMN_FIELD;\n}\n\n/**\n * Check if a column is a utility column (excluded from selection, clipboard, etc.).\n * Utility columns are non-data columns like expander columns.\n */\nexport function isUtilityColumn(column: ColumnConfig): boolean {\n return column.utility === true;\n}\n\n/**\n * Find an existing expander column in the column array.\n */\nexport function findExpanderColumn(columns: readonly ColumnConfig[]): ColumnConfig | undefined {\n return columns.find(isExpanderColumn);\n}\n\n/**\n * Create the base expander column config.\n * Plugins should add their own renderer to customize the expand icon behavior.\n *\n * @param pluginName - Name of the plugin creating the expander (for debugging)\n * @returns Base column config for the expander column\n */\nexport function createExpanderColumnConfig(pluginName: string): ColumnConfig {\n return {\n field: EXPANDER_COLUMN_FIELD as any,\n header: '', // No header text - visually merges with next column\n width: EXPANDER_COLUMN_WIDTH,\n resizable: false,\n sortable: false,\n filterable: false, // No filter button for expander column\n lockPosition: true,\n utility: true, // Marks this as a utility column (excluded from selection, clipboard, etc.)\n meta: {\n expanderColumn: true,\n expanderPlugin: pluginName,\n },\n };\n}\n","/**\n * Generic click-only action menu — the shared building block for WCAG 2.2\n * SC 2.5.7 \"Dragging Movements\" alternatives in plugins.\n *\n * Every drag affordance in the grid needs a path that works with plain clicks\n * or taps. A keyboard equivalent is **not** enough: SC 2.5.7 is specifically\n * about pointer input, and the W3C Understanding text calls out \"a pop-up menu\n * after tap\" as a conforming alternative. This module is that pop-up.\n *\n * Lives under `plugins/shared/` on purpose: each plugin bundle is built\n * self-contained, so this code is duplicated into the plugins that use it and\n * never lands in the core `index.js` budget.\n *\n * @since 3.6.0\n * @internal\n */\n\n/** Gap between the anchor element and the menu, in px. */\nconst ANCHOR_GAP_PX = 6;\n\n/** Runtime check — happy-dom and older browsers may lack the Popover API. */\nfunction supportsPopover(): boolean {\n return typeof HTMLElement.prototype?.showPopover === 'function';\n}\n\nlet hoverlessQuery: MediaQueryList | null | undefined;\n\n/** Whether the primary pointer cannot hover (touch, most switch devices). */\nfunction isHoverless(): boolean {\n if (hoverlessQuery === undefined) hoverlessQuery = globalThis.matchMedia?.('(hover: none)') ?? null;\n return hoverlessQuery?.matches ?? false;\n}\n\n/**\n * Whether a plugin should also expose its drag alternative as a dedicated\n * inline control, on top of the menu that is always available.\n *\n * Hover-less pointers get one unconditionally — a control revealed on hover is\n * unreachable when nothing can hover, and long-press is the wrong fallback for\n * the tremor and low-dexterity users SC 2.5.7 exists for.\n *\n * Driven by `a11y.dragAlternatives` on the grid config.\n */\nexport function prefersInlineDragAlternative(grid: {\n effectiveConfig?: { a11y?: { dragAlternatives?: 'menu' | 'inline' } };\n}): boolean {\n return grid.effectiveConfig?.a11y?.dragAlternatives === 'inline' || isHoverless();\n}\n\n/** One clickable entry in the menu. */\nexport interface DragAlternativeAction {\n /** Visible text, also the accessible name. */\n label: string;\n /** Render the entry but refuse the click (e.g. \"Move up\" on the first row). */\n disabled?: boolean;\n /** Invoked on click; the menu closes first so focus handling is predictable. */\n run(): void;\n}\n\nexport interface DragAlternativeMenu {\n /**\n * Show `actions` anchored to `anchor`, with `label` as the group's accessible\n * name. Mounted inside the anchor's grid host so it inherits theme tokens.\n */\n open(anchor: HTMLElement, label: string, actions: readonly DragAlternativeAction[]): void;\n /** Hide the menu. Safe to call when already closed. */\n close(): void;\n /** Remove the element and every document-level listener. */\n dispose(): void;\n /** The menu element, or `null` before the first {@link DragAlternativeMenu.open}. */\n readonly element: HTMLElement | null;\n}\n\n/**\n * Create a menu instance.\n *\n * @param id - DOM id for the menu element, unique per owning plugin.\n * @param className - Root class name, so each plugin can style its own menu.\n */\nexport function createDragAlternativeMenu(id: string, className: string): DragAlternativeMenu {\n let root: HTMLDivElement | null = null;\n let opened = false;\n let disposed = false;\n const abort = new AbortController();\n\n function close(): void {\n if (!opened || !root) return;\n opened = false;\n if (supportsPopover()) root.hidePopover();\n root.hidden = true;\n }\n\n function build(): HTMLDivElement {\n const el = document.createElement('div');\n el.id = id;\n el.className = className;\n el.setAttribute('popover', 'manual');\n el.setAttribute('role', 'group');\n // Without the Popover API there is no UA `display: none`, so hide it here.\n el.hidden = true;\n // Tabbing past either end dismisses instead of stranding the user — the\n // menu has no visible trigger to tab back to. A null `relatedTarget` (click\n // focus in Firefox/Safari, focus leaving the document) is ignored.\n el.addEventListener(\n 'focusout',\n (e) => {\n const next = (e as FocusEvent).relatedTarget;\n if (next instanceof Node && !el.contains(next)) close();\n },\n { signal: abort.signal },\n );\n return el;\n }\n\n /**\n * Position against the anchor in viewport coordinates. The menu lives in the\n * top layer, so its containing block is the viewport regardless of where the\n * anchor sits in the DOM.\n */\n function place(anchor: HTMLElement): void {\n if (!root) return;\n const a = anchor.getBoundingClientRect();\n const box = root.getBoundingClientRect();\n const left = Math.max(4, Math.min(a.left, window.innerWidth - box.width - 4));\n const below = a.bottom + ANCHOR_GAP_PX;\n const top = below + box.height <= window.innerHeight ? below : Math.max(4, a.top - ANCHOR_GAP_PX - box.height);\n root.style.left = `${Math.round(left)}px`;\n root.style.top = `${Math.round(top)}px`;\n }\n\n // Any pointer press outside the menu dismisses it. Capture phase so the press\n // that lands on a grid cell still reaches its own handler afterwards.\n document.addEventListener(\n 'pointerdown',\n (e) => {\n if (opened && root && !e.composedPath().includes(root)) close();\n },\n { capture: true, signal: abort.signal },\n );\n document.addEventListener(\n 'keydown',\n (e) => {\n if ((e as KeyboardEvent).key === 'Escape') close();\n },\n { capture: true, signal: abort.signal },\n );\n\n return {\n get element() {\n return root;\n },\n open(anchor, label, actions) {\n if (disposed || actions.length === 0) return;\n if (!root) root = build();\n // Mount inside the grid host (light DOM) so theme custom properties and\n // `color-scheme` cascade in; the top layer keeps it out of overflow.\n const host = anchor.closest<HTMLElement>('tbw-grid, [data-tbw-grid]') ?? document.body;\n if (root.parentNode !== host) host.appendChild(root);\n root.setAttribute('aria-label', label);\n root.replaceChildren();\n for (const action of actions) {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = `${className}-item`;\n btn.textContent = action.label;\n btn.disabled = action.disabled === true;\n btn.addEventListener('click', () => {\n close();\n action.run();\n });\n root.appendChild(btn);\n }\n root.hidden = false;\n if (!opened && supportsPopover()) root.showPopover();\n opened = true;\n place(anchor);\n root.querySelector<HTMLButtonElement>('button:not([disabled])')?.focus();\n },\n close,\n dispose() {\n disposed = true;\n close();\n abort.abort();\n root?.remove();\n root = null;\n },\n };\n}\n","/**\n * Column Selection Core Logic\n *\n * Pure functions for column selection: mode normalization, range expansion\n * across visible columns, and Ctrl+Shift+Arrow extension math. All grid-DOM\n * interaction lives in `SelectionPlugin.ts` — this module is dependency-free\n * and trivially unit-testable.\n *\n * @since 2.8.0\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { SelectionMode } from './types';\n\n// #region Mode normalization\n\n/**\n * Normalized representation of `SelectionConfig.mode`. Splits the user-supplied\n * mode (single string OR array) into:\n *\n * - `primary`: the in-row axis (`'cell' | 'row' | 'range'`) — drives existing\n * click/drag/keyboard behavior. When the user configured column-only, this is\n * `'column'` and the in-row hooks treat it as inert.\n * - `columnEnabled`: whether the column axis is also active. Drives Ctrl+Click\n * on header, Ctrl+Space on focused cell, and the column-selection render pass.\n * - `bothAxes`: shorthand for \"column AND a non-column axis are configured\" —\n * this is the only state where the row↔column mutual-exclusion logic kicks in.\n */\nexport interface NormalizedModeConfig {\n primary: SelectionMode;\n columnEnabled: boolean;\n bothAxes: boolean;\n}\n\n/**\n * Normalize the user-supplied `mode` and validate it.\n *\n * Allowed shapes:\n * - Single: `'cell' | 'row' | 'column' | 'range'`\n * - Array: `['column', X]` or `[X, 'column']` where X is `'cell' | 'row' | 'range'`\n * - Single-element arrays are treated as the contained string for ergonomics.\n *\n * Throws on:\n * - Empty array\n * - Arrays of 3+ items\n * - Arrays without `'column'` (the only purpose of an array is to enable the\n * column axis alongside an in-row axis — `['row', 'cell']` etc. don't compose)\n * - Duplicate entries\n * - Unknown mode strings\n */\nexport function normalizeMode(mode: SelectionMode | SelectionMode[]): NormalizedModeConfig {\n const validModes: ReadonlySet<string> = new Set(['cell', 'row', 'column', 'range']);\n\n if (typeof mode === 'string') {\n if (!validModes.has(mode)) {\n throw new Error(\n `[SelectionPlugin] Invalid selection mode: \"${mode}\". Expected one of: 'cell' | 'row' | 'column' | 'range'.`,\n );\n }\n return {\n primary: mode,\n columnEnabled: mode === 'column',\n bothAxes: false,\n };\n }\n\n if (!Array.isArray(mode)) {\n throw new Error(`[SelectionPlugin] Invalid selection mode: expected string or array, got ${typeof mode}.`);\n }\n\n if (mode.length === 0) {\n throw new Error(`[SelectionPlugin] Invalid selection mode: array must contain at least one mode.`);\n }\n\n for (const m of mode) {\n if (!validModes.has(m)) {\n throw new Error(\n `[SelectionPlugin] Invalid selection mode in array: \"${m}\". Expected one of: 'cell' | 'row' | 'column' | 'range'.`,\n );\n }\n }\n\n // Reject duplicates\n if (new Set(mode).size !== mode.length) {\n throw new Error(`[SelectionPlugin] Invalid selection mode: array contains duplicate entries (${mode.join(', ')}).`);\n }\n\n // Single-element array → treat as plain string\n if (mode.length === 1) {\n return normalizeMode(mode[0]);\n }\n\n if (mode.length > 2) {\n throw new Error(\n `[SelectionPlugin] Invalid selection mode: arrays of more than 2 modes are not supported. Got [${mode.join(', ')}].`,\n );\n }\n\n // 2-element array: must contain 'column' + one of 'cell' | 'row' | 'range'\n const hasColumn = mode.includes('column');\n if (!hasColumn) {\n throw new Error(\n `[SelectionPlugin] Invalid selection mode: [${mode.join(', ')}]. ` +\n `Two-mode arrays must include 'column' (the only valid combinations are ['row','column'], ['cell','column'], ['range','column']). ` +\n `Other in-row modes don't compose meaningfully.`,\n );\n }\n\n const other = mode.find((m) => m !== 'column') as SelectionMode;\n if (other === 'column') {\n // Both entries are 'column' — already caught by duplicate check, but defend\n throw new Error(`[SelectionPlugin] Invalid selection mode: [${mode.join(', ')}].`);\n }\n\n return {\n primary: other,\n columnEnabled: true,\n bothAxes: true,\n };\n}\n\n// #endregion\n\n// #region Field/index helpers\n\n/**\n * Build the ordered list of selectable column fields from the grid's visible\n * columns. Utility columns (checkbox, expander, drag handle) are excluded —\n * they exist to support grid behavior, not to be selected.\n */\nexport function selectableColumnFields(visibleColumns: readonly ColumnConfig[]): string[] {\n const fields: string[] = [];\n for (const col of visibleColumns) {\n if ((col as { utility?: boolean }).utility === true) continue;\n if (typeof col.field === 'string' && col.field.length > 0) {\n fields.push(col.field);\n }\n }\n return fields;\n}\n\n/** Find the index of `field` within the selectable-fields list. -1 if not present. */\nexport function indexOfField(field: string, fields: readonly string[]): number {\n return fields.indexOf(field);\n}\n\n/**\n * Compute the inclusive field range from `anchor` to `target` along the\n * visible-column order. Returns the fields between the two (inclusive),\n * regardless of which one is to the left. Empty if either is missing.\n */\nexport function fieldsBetween(anchor: string, target: string, fields: readonly string[]): string[] {\n const a = indexOfField(anchor, fields);\n const b = indexOfField(target, fields);\n if (a === -1 || b === -1) return [];\n const start = Math.min(a, b);\n const end = Math.max(a, b);\n return fields.slice(start, end + 1);\n}\n\n// #endregion\n\n// #region Keyboard extension (Ctrl+Shift+Arrow)\n\n/**\n * Compute the new \"head\" field after pressing `ArrowLeft` or `ArrowRight`\n * during column-axis keyboard extension. `head` is the most recently focused\n * column edge (the one that moves); `anchor` stays put.\n *\n * Returns the new head field, or `null` if the move would go out of bounds\n * (caller should leave selection unchanged).\n */\nexport function computeKeyboardExtension(\n head: string | null,\n fields: readonly string[],\n direction: 'left' | 'right',\n): string | null {\n if (fields.length === 0) return null;\n if (head === null) return null;\n const headIdx = indexOfField(head, fields);\n if (headIdx < 0) return null;\n const next = direction === 'left' ? Math.max(0, headIdx - 1) : Math.min(fields.length - 1, headIdx + 1);\n if (next === headIdx) return null;\n return fields[next];\n}\n\n// #endregion\n","/**\n * Cell Range Selection Core Logic\n *\n * Pure functions for cell range selection operations.\n */\n\nimport type { InternalCellRange, CellRange } from './types';\n\n/**\n * Normalize a range so startRow/startCol are always <= endRow/endCol.\n * This handles cases where user drags from bottom-right to top-left.\n *\n * @param range - The range to normalize\n * @returns Normalized range with start <= end for both dimensions\n */\nexport function normalizeRange(range: InternalCellRange): InternalCellRange {\n return {\n startRow: Math.min(range.startRow, range.endRow),\n startCol: Math.min(range.startCol, range.endCol),\n endRow: Math.max(range.startRow, range.endRow),\n endCol: Math.max(range.startCol, range.endCol),\n };\n}\n\n/**\n * Convert an internal range to the public event format.\n *\n * @param range - The internal range to convert\n * @returns Public CellRange format with from/to coordinates\n */\nexport function toPublicRange(range: InternalCellRange): CellRange {\n const normalized = normalizeRange(range);\n return {\n from: { row: normalized.startRow, col: normalized.startCol },\n to: { row: normalized.endRow, col: normalized.endCol },\n };\n}\n\n/**\n * Convert multiple internal ranges to public format.\n *\n * @param ranges - Array of internal ranges\n * @returns Array of public CellRange format\n */\nexport function toPublicRanges(ranges: InternalCellRange[]): CellRange[] {\n return ranges.map(toPublicRange);\n}\n\n/**\n * Check if a cell is within a specific range.\n *\n * @param row - The row index to check\n * @param col - The column index to check\n * @param range - The range to check against\n * @returns True if the cell is within the range\n */\nexport function isCellInRange(row: number, col: number, range: InternalCellRange): boolean {\n const normalized = normalizeRange(range);\n return (\n row >= normalized.startRow && row <= normalized.endRow && col >= normalized.startCol && col <= normalized.endCol\n );\n}\n\n/**\n * Check if a cell is within any of the provided ranges.\n *\n * @param row - The row index to check\n * @param col - The column index to check\n * @param ranges - Array of ranges to check against\n * @returns True if the cell is within any range\n */\nexport function isCellInAnyRange(row: number, col: number, ranges: InternalCellRange[]): boolean {\n return ranges.some((range) => isCellInRange(row, col, range));\n}\n\n/**\n * Get all cells within a range as an array of {row, col} objects.\n *\n * @param range - The range to enumerate\n * @returns Array of all cell coordinates in the range\n */\nexport function getCellsInRange(range: InternalCellRange): Array<{ row: number; col: number }> {\n const cells: Array<{ row: number; col: number }> = [];\n const normalized = normalizeRange(range);\n\n for (let row = normalized.startRow; row <= normalized.endRow; row++) {\n for (let col = normalized.startCol; col <= normalized.endCol; col++) {\n cells.push({ row, col });\n }\n }\n\n return cells;\n}\n\n/**\n * Get all unique cells across multiple ranges.\n * Deduplicates cells that appear in overlapping ranges.\n *\n * @param ranges - Array of ranges to enumerate\n * @returns Array of unique cell coordinates\n */\nexport function getAllCellsInRanges(ranges: InternalCellRange[]): Array<{ row: number; col: number }> {\n const cellMap = new Map<string, { row: number; col: number }>();\n\n for (const range of ranges) {\n for (const cell of getCellsInRange(range)) {\n cellMap.set(`${cell.row},${cell.col}`, cell);\n }\n }\n\n return [...cellMap.values()];\n}\n\n/**\n * Merge overlapping or adjacent ranges into fewer ranges.\n * Simple implementation - returns ranges as-is for now.\n * More complex merging logic can be added later for optimization.\n *\n * @param ranges - Array of ranges to merge\n * @returns Merged array of ranges\n */\nexport function mergeRanges(ranges: InternalCellRange[]): InternalCellRange[] {\n // Simple implementation - more complex merging can be added later\n return ranges;\n}\n\n/**\n * Create a range from an anchor cell to a current cell position.\n * The range is not normalized - it preserves the direction of selection.\n *\n * @param anchor - The anchor cell (where selection started)\n * @param current - The current cell (where selection ends)\n * @returns An InternalCellRange from anchor to current\n */\nexport function createRangeFromAnchor(\n anchor: { row: number; col: number },\n current: { row: number; col: number }\n): InternalCellRange {\n return {\n startRow: anchor.row,\n startCol: anchor.col,\n endRow: current.row,\n endCol: current.col,\n };\n}\n\n/**\n * Calculate the number of cells in a range.\n *\n * @param range - The range to measure\n * @returns Total number of cells in the range\n */\nexport function getRangeCellCount(range: InternalCellRange): number {\n const normalized = normalizeRange(range);\n const rowCount = normalized.endRow - normalized.startRow + 1;\n const colCount = normalized.endCol - normalized.startCol + 1;\n return rowCount * colCount;\n}\n\n/**\n * Check if two ranges are equal (same boundaries).\n *\n * @param a - First range\n * @param b - Second range\n * @returns True if ranges have same boundaries after normalization\n */\nexport function rangesEqual(a: InternalCellRange, b: InternalCellRange): boolean {\n const normA = normalizeRange(a);\n const normB = normalizeRange(b);\n return (\n normA.startRow === normB.startRow &&\n normA.startCol === normB.startCol &&\n normA.endRow === normB.endRow &&\n normA.endCol === normB.endCol\n );\n}\n\n/**\n * Check if a range is a single cell (1x1).\n *\n * @param range - The range to check\n * @returns True if the range is exactly one cell\n */\nexport function isSingleCell(range: InternalCellRange): boolean {\n const normalized = normalizeRange(range);\n return normalized.startRow === normalized.endRow && normalized.startCol === normalized.endCol;\n}\n","/**\n * Selection Plugin Styles\n *\n * Scoped to tbw-grid using CSS nesting for light DOM compatibility.\n */\n@layer tbw-plugins {\n tbw-grid {\n /* Prevent text selection during range drag */\n &.selecting .data-grid-row > .cell {\n user-select: none;\n }\n\n /* Prevent text selection when any selection exists */\n &:has(.selection) {\n user-select: none;\n /* Disable cell-focus outline in row mode - row is the focus unit.\n Also disable row-focus outline - selection plugin uses ::after borders instead. */\n &[data-selection-mode='row'] .cell-focus,\n &[data-selection-mode='row'] .row-focus,\n &[data-selection-mode='range'] .cell-focus {\n outline: none;\n }\n }\n\n /* Row selection - use accent color for row focus (only when grid is focused) */\n .data-grid-row.row-focus {\n background-color: var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%));\n /* Replace outline with per-side pseudo-element borders that can collapse */\n outline: none;\n position: relative;\n\n &::after {\n content: '';\n position: absolute;\n inset: 0;\n pointer-events: none;\n border-width: 0;\n border-style: var(--tbw-selection-border-style, var(--tbw-border-style));\n border-color: var(--tbw-range-border-color, var(--tbw-color-accent));\n border-top-width: var(--tbw-selection-border-width, var(--tbw-border-width));\n border-bottom-width: var(--tbw-selection-border-width, var(--tbw-border-width));\n /* Must paint above sticky cells (.sticky-left/.sticky-right have\n z-index: 25 in core/styles/base.css) so the selection border is\n continuous across pinned columns. The border ::after has\n pointer-events: none, so it doesn't interfere with cell content. */\n z-index: 26;\n }\n\n /* Collapse borders between adjacent selected rows */\n + .data-grid-row.row-focus::after {\n border-top-width: 0;\n }\n &:has(+ .data-grid-row.row-focus)::after {\n border-bottom-width: 0;\n }\n\n /* Sticky cells (.sticky-left/.sticky-right) have an opaque\n background-color to hide unpinned content scrolling beneath them\n (see core/styles/rows.css). That opaque layer also hides the\n row-focus background-color set above. Re-paint sticky cells with\n the focus tint layered over panel-bg so the selection tint is\n visible across pinned columns. The selection BORDER is handled by\n the row's ::after with z-index above the sticky cells — no need\n to redraw it here. */\n > .cell.sticky-left,\n > .cell.sticky-right {\n background:\n linear-gradient(var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0),\n var(--tbw-color-panel-bg);\n }\n }\n\n /* Non-selectable selected rows use the row-alt background as the muted\n indicator — keep sticky cells in sync so pinned columns don't flash\n the accent tint on rows that aren't actually selectable. */\n .data-grid-row.row-focus[data-selectable='false'] {\n > .cell.sticky-left,\n > .cell.sticky-right {\n background: var(--tbw-color-row-alt);\n }\n }\n\n /* Selection cell styles - for range mode */\n .data-grid-row > .cell.selected {\n background-color: var(--tbw-range-selection-bg);\n position: relative;\n\n /* Pseudo-element draws the selection range border inside the cell's\n padding box. Uses inset: 0 to stay within overflow: hidden bounds.\n The cell's own borders (row divider, column border) remain visible\n outside the selection border — this is intentional and consistent\n across all themes regardless of border width or visibility. */\n &::after {\n content: '';\n position: absolute;\n inset: 0;\n pointer-events: none;\n border: 0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);\n z-index: 1;\n }\n\n &.top::after {\n border-top-width: var(--tbw-selection-border-width, var(--tbw-border-width));\n }\n &.bottom::after {\n border-bottom-width: var(--tbw-selection-border-width, var(--tbw-border-width));\n }\n &.first::after {\n border-left-width: var(--tbw-selection-border-width, var(--tbw-border-width));\n }\n &.last::after {\n border-right-width: var(--tbw-selection-border-width, var(--tbw-border-width));\n }\n }\n\n /* Non-selectable row styling (row mode).\n The row is dimmed to signal \"not selectable\", but its *data* is still\n content the user has to read, so the exception WCAG 1.4.3 grants inactive\n UI components does not apply. 0.6 pushed the text to 4.24:1 on white;\n 0.65 is the lowest value that clears AA (5.02:1). */\n .data-grid-row[data-selectable='false'] {\n cursor: not-allowed;\n opacity: var(--tbw-selection-disabled-opacity, 0.65);\n\n /* Muted selection indicator */\n &.row-focus {\n background-color: var(--tbw-color-row-alt);\n }\n }\n\n /* Non-selectable cell styling (cell/range mode) */\n .data-grid-row > .cell[data-selectable='false'] {\n cursor: not-allowed;\n opacity: var(--tbw-selection-disabled-opacity, 0.65);\n\n /* Prevent selection highlight on non-selectable cells */\n &.selected {\n background-color: var(--tbw-selection-warning-bg, rgba(from var(--tbw-color-error) r g b / 50%));\n }\n }\n\n /* Selection summary in header */\n .tbw-selection-summary {\n font-size: var(--tbw-font-size-sm, 0.8125rem);\n color: var(--tbw-color-fg-muted);\n white-space: nowrap;\n }\n\n /* Checkbox column styles */\n .data-grid-row > .cell[data-field='__tbw_checkbox'],\n .header-row > .cell[data-field='__tbw_checkbox'] {\n text-align: center;\n cursor: pointer;\n padding: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n /* Row checkboxes are visual indicators - clicks pass through to cell */\n .tbw-select-row-checkbox {\n pointer-events: none;\n margin: 0;\n cursor: pointer;\n }\n\n /* Header select-all checkbox container */\n .tbw-checkbox-header {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100%;\n cursor: pointer;\n }\n\n .tbw-select-all-checkbox {\n margin: 0;\n cursor: pointer;\n }\n\n /* SC 2.5.8: the row checkbox is not itself a target — the row click selects,\n so the whole cell accepts the pointer. Select-all has its own handler, and\n gets a cell-sized target from the `<label>` wrapper instead of a 24px box.\n Coarse pointers still grow the boxes, which is a comfort choice. */\n @media (pointer: coarse) {\n .tbw-select-row-checkbox,\n .tbw-select-all-checkbox {\n min-width: var(--tbw-touch-target-min, 24px);\n min-height: var(--tbw-touch-target-min, 24px);\n }\n }\n\n /* ---- Column-axis selection ----------------------------------------- */\n /* Background tint for selected columns. Applied to the matching header\n cell and every data cell whose data-col resolves to a selected field.\n The tint uses --tbw-column-selection-bg (overridable) defaulting to\n a 12 % accent overlay — visually distinct from row-focus but uses the\n same palette so themes stay coherent. */\n .header-row > .cell.column-selected,\n .data-grid-row > .cell.column-selected {\n background:\n linear-gradient(var(--tbw-column-selection-bg, rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0),\n var(--tbw-color-panel-bg);\n }\n\n /* Pinned columns repaint with sticky background; layer the column tint\n on top of the panel-bg fill so the indicator survives pinning. */\n .data-grid-row > .cell.column-selected.sticky-left,\n .data-grid-row > .cell.column-selected.sticky-right,\n .header-row > .cell.column-selected.sticky-left,\n .header-row > .cell.column-selected.sticky-right {\n background:\n linear-gradient(var(--tbw-column-selection-bg, rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0),\n var(--tbw-color-panel-bg);\n }\n\n /* ========== Touch selection mode (#304) ========== */\n\n /* Sticky action bar shown while touch selection mode is active. Rendered\n only on coarse-pointer devices, so the sizing targets a finger. */\n .tbw-selection-toolbar {\n position: sticky;\n top: 0;\n z-index: 30;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n padding: 4px 8px;\n background: var(--tbw-color-panel-bg);\n border-bottom: 1px solid var(--tbw-color-border);\n font-size: 13px;\n }\n\n .tbw-selection-toolbar-count {\n font-weight: 600;\n white-space: nowrap;\n }\n\n .tbw-selection-toolbar-actions {\n display: flex;\n align-items: center;\n gap: 4px;\n }\n\n /* `--tbw-touch-target-min` is owned by the touch-target sub-issue (#305);\n the literal fallback keeps this file readable on its own. */\n .tbw-selection-toolbar-btn {\n min-height: var(--tbw-touch-target-min, 24px);\n padding: 0 10px;\n border: 0;\n /* Themes set radii for much larger surfaces (Material uses 12px), which\n turns a 24px control into a lozenge. */\n border-radius: min(var(--tbw-border-radius, 4px), 6px);\n background: transparent;\n color: inherit;\n font: inherit;\n cursor: pointer;\n\n &:hover,\n &:focus-visible {\n background: var(--tbw-color-row-hover, light-dark(#f0f0f0, #2a2a2a));\n }\n\n &[data-action='done'] {\n font-weight: 600;\n color: var(--tbw-color-accent-text, var(--tbw-color-accent));\n }\n }\n\n /* Draggable corner dots on an active cell range (iOS Numbers idiom).\n Additive — a mouse user gets them too. The visible dot is smaller than\n the hit area, and `touch-action` is off because the drag runs on pointer\n capture. */\n .tbw-range-handle {\n position: absolute;\n z-index: 25;\n width: var(--tbw-touch-target-min, 24px);\n height: var(--tbw-touch-target-min, 24px);\n translate: -50% -50%;\n background: radial-gradient(circle, var(--tbw-color-accent) 0 5px, transparent 5px);\n cursor: crosshair;\n touch-action: none;\n\n &[hidden] {\n display: none;\n }\n\n &.dragging {\n scale: 1.3;\n }\n\n /* Tapped rather than dragged: the handle is waiting for the cell that\n will receive this corner (WCAG 2.2 SC 2.5.7). */\n &.armed {\n scale: 1.3;\n outline: 2px solid var(--tbw-color-accent);\n outline-offset: -4px;\n border-radius: 50%;\n }\n }\n }\n} /* End @layer tbw-plugins */\n","/**\n * Touch selection mode — long-press to enter, tap to toggle, tap \"Done\" to exit.\n *\n * This module owns the *presentation* half of the touch selection idiom\n * (#304): the selection-mode toolbar and the cell-range corner handles.\n * The state machine itself lives in `SelectionPlugin`, which drives these two\n * classes from its `afterRender()` hook.\n *\n * @module\n * @since 3.5.0\n */\n\nimport { startPointerDrag } from '../../core/internal/pointer-drag';\n\n// #region Types\n\n/**\n * What happens to the selection when touch selection mode is exited.\n *\n * - `'transient'` (default) — leaving selection mode clears the selection, the\n * Gmail / Google Photos behaviour. The mode *is* the selection.\n * - `'sticky'` — the selection survives, so a subsequent tap-to-toggle round\n * can start from what was already selected.\n *\n * @since 3.5.0\n */\nexport type TouchSelectionMode = 'sticky' | 'transient';\n\n/** Callbacks the toolbar invokes; all are supplied by `SelectionPlugin`. */\nexport interface SelectionToolbarCallbacks {\n /** \"Select all\" pressed. */\n selectAll(): void;\n /** \"Clear\" pressed. */\n clear(): void;\n /** \"Done\" pressed — exit selection mode. */\n done(): void;\n /** \"More…\" pressed. Receives the button so a menu can be anchored to it. */\n more(anchor: HTMLElement): void;\n}\n\n/** A normalized rectangle in (row, visible-column) space. */\nexport interface RangeRect {\n startRow: number;\n startCol: number;\n endRow: number;\n endCol: number;\n}\n\n/** Which corner of the range rectangle a handle controls. */\nexport type RangeCorner = 'start' | 'end';\n\n/** Callbacks the corner handles invoke while being dragged. */\nexport interface RangeHandleCallbacks {\n /** Resolve the cell under a viewport coordinate, or `null` if there is none. */\n cellAt(clientX: number, clientY: number): { row: number; col: number } | null;\n /** The dragged corner moved to a new cell. */\n resize(corner: RangeCorner, row: number, col: number): void;\n /** The drag finished (pointerup) or was aborted (Escape / pointercancel). */\n commit(): void;\n /**\n * The handle was pressed and released without moving — a tap, not a drag.\n * The non-dragging path required by WCAG 2.2 SC 2.5.7: the plugin arms this\n * corner and the next cell tap places it.\n */\n arm(corner: RangeCorner): void;\n}\n\n// #endregion\n\n// #region Selection-mode toolbar\n\n/** CSS class of the toolbar root. Also used by `selection.css`. */\nconst TOOLBAR_CLASS = 'tbw-selection-toolbar';\n\n/**\n * The sticky \"N selected · Select all · Clear · More… · Done\" bar shown while\n * touch selection mode is active.\n *\n * Mounted lazily on first {@link SelectionToolbar.show} and torn down by\n * {@link SelectionToolbar.destroy}. Buttons are `type=\"button\"` so the bar can\n * safely live inside a host form.\n */\nexport class SelectionToolbar {\n #root: HTMLElement | null = null;\n #count: HTMLElement | null = null;\n #more: HTMLButtonElement | null = null;\n #callbacks: SelectionToolbarCallbacks | null = null;\n\n /** True while the toolbar is in the DOM. */\n get mounted(): boolean {\n return this.#root !== null;\n }\n\n /** The toolbar root element, or `null` when not mounted. Test seam. */\n get element(): HTMLElement | null {\n return this.#root;\n }\n\n /**\n * Mount (if needed) and update the toolbar.\n *\n * @param container Element the toolbar is prepended to — normally `.tbw-grid-root`.\n * @param selectedCount Number of selected items, rendered as \"N selected\".\n * @param showMore Whether the \"More…\" overflow button is rendered. Only true\n * when a `ContextMenuPlugin` is registered, so touch users keep parity with\n * the right-click menu.\n */\n show(container: HTMLElement, selectedCount: number, showMore: boolean, callbacks: SelectionToolbarCallbacks): void {\n this.#callbacks = callbacks;\n if (!this.#root) this.#mount(container);\n if (this.#count) {\n this.#count.textContent = `${selectedCount} selected`;\n }\n this.#root?.setAttribute('data-selected-count', String(selectedCount));\n if (this.#more) this.#more.hidden = !showMore;\n }\n\n /** Remove the toolbar from the DOM. Safe to call when not mounted. */\n destroy(): void {\n this.#root?.remove();\n this.#root = null;\n this.#count = null;\n this.#more = null;\n this.#callbacks = null;\n }\n\n #mount(container: HTMLElement): void {\n const root = container.ownerDocument.createElement('div');\n root.className = TOOLBAR_CLASS;\n root.setAttribute('role', 'toolbar');\n root.setAttribute('aria-label', 'Selection');\n\n const count = container.ownerDocument.createElement('span');\n count.className = `${TOOLBAR_CLASS}-count`;\n count.setAttribute('aria-live', 'polite');\n root.appendChild(count);\n\n const actions = container.ownerDocument.createElement('div');\n actions.className = `${TOOLBAR_CLASS}-actions`;\n root.appendChild(actions);\n\n actions.appendChild(this.#button(container, 'select-all', 'Select all', () => this.#callbacks?.selectAll()));\n actions.appendChild(this.#button(container, 'clear', 'Clear', () => this.#callbacks?.clear()));\n const more = this.#button(container, 'more', 'More…', (btn) => this.#callbacks?.more(btn));\n more.setAttribute('aria-haspopup', 'menu');\n actions.appendChild(more);\n actions.appendChild(this.#button(container, 'done', 'Done', () => this.#callbacks?.done()));\n\n container.prepend(root);\n this.#root = root;\n this.#count = count;\n this.#more = more;\n }\n\n #button(\n container: HTMLElement,\n action: string,\n label: string,\n onClick: (btn: HTMLButtonElement) => void,\n ): HTMLButtonElement {\n const btn = container.ownerDocument.createElement('button');\n btn.type = 'button';\n btn.className = `${TOOLBAR_CLASS}-btn`;\n btn.dataset.action = action;\n btn.textContent = label;\n btn.addEventListener('click', (e) => {\n e.preventDefault();\n e.stopPropagation();\n onClick(btn);\n });\n return btn;\n }\n}\n\n// #endregion\n\n// #region Cell-range corner handles\n\n/** CSS class of a corner handle. Also used by `selection.css`. */\nconst HANDLE_CLASS = 'tbw-range-handle';\n\n/**\n * The two draggable dots at the top-left and bottom-right corners of an active\n * cell range (the iOS Numbers / Google Sheets idiom).\n *\n * They are additive rather than touch-only: a mouse user can drag them too.\n * Whether they are rendered at all is decided by `SelectionPlugin`, which only\n * asks for them when the range was started by a coarse pointer.\n * Positioning is recomputed on every render because the grid recycles row DOM\n * during virtualization, so a handle's anchor cell may not exist at all after\n * a scroll — in that case the handle is simply hidden.\n */\nexport class RangeCornerHandles {\n #start: HTMLElement | null = null;\n #end: HTMLElement | null = null;\n #callbacks: RangeHandleCallbacks | null = null;\n #armed: RangeCorner | null = null;\n\n /**\n * Render (or hide) the handles for `rect`.\n *\n * @param container Positioned ancestor the handles are absolutely placed in.\n * @param rect The normalized range, or `null` to hide the handles.\n * @param cellFor Resolves the DOM cell for a (row, col) pair, or `undefined`\n * when that cell is outside the rendered window.\n */\n render(\n container: HTMLElement,\n rect: RangeRect | null,\n cellFor: (row: number, col: number) => HTMLElement | null,\n callbacks: RangeHandleCallbacks,\n ): void {\n this.#callbacks = callbacks;\n if (!rect) {\n this.#hide();\n return;\n }\n\n this.#start ??= this.#createHandle(container, 'start');\n this.#end ??= this.#createHandle(container, 'end');\n\n this.#place(container, this.#start, cellFor(rect.startRow, rect.startCol), 'start');\n this.#place(container, this.#end, cellFor(rect.endRow, rect.endCol), 'end');\n this.setArmed(this.#armed);\n }\n\n /**\n * Mark one corner as waiting for the tap that will place it, or clear the\n * marking with `null`. Purely presentational — the plugin owns the state.\n */\n setArmed(corner: RangeCorner | null): void {\n this.#armed = corner;\n for (const [handle, name] of [\n [this.#start, 'start'],\n [this.#end, 'end'],\n ] as const) {\n if (!handle) continue;\n const on = corner === name;\n handle.classList.toggle('armed', on);\n handle.setAttribute('aria-pressed', String(on));\n }\n }\n\n /** Remove both handles from the DOM. Safe to call when not rendered. */\n destroy(): void {\n this.#start?.remove();\n this.#end?.remove();\n this.#start = null;\n this.#end = null;\n this.#callbacks = null;\n this.#armed = null;\n }\n\n #hide(): void {\n if (this.#start) this.#start.hidden = true;\n if (this.#end) this.#end.hidden = true;\n }\n\n #place(container: HTMLElement, handle: HTMLElement | null, cell: HTMLElement | null, corner: RangeCorner): void {\n if (!handle) return;\n if (!cell) {\n handle.hidden = true;\n return;\n }\n handle.hidden = false;\n // getBoundingClientRect is unavailable/zeroed in some test environments;\n // the handle still renders (and is assertable) with a zero offset.\n const cellRect = cell.getBoundingClientRect?.();\n const hostRect = container.getBoundingClientRect?.();\n if (!cellRect || !hostRect) return;\n const x = corner === 'start' ? cellRect.left - hostRect.left : cellRect.right - hostRect.left;\n const y = corner === 'start' ? cellRect.top - hostRect.top : cellRect.bottom - hostRect.top;\n handle.style.left = `${x}px`;\n handle.style.top = `${y}px`;\n }\n\n #createHandle(container: HTMLElement, corner: RangeCorner): HTMLElement {\n const el = container.ownerDocument.createElement('div');\n el.className = `${HANDLE_CLASS} ${HANDLE_CLASS}-${corner}`;\n el.dataset.corner = corner;\n // A real button, not decoration: it is tappable as well as draggable, so it\n // needs a name and a pressed state for the armed (tap-to-place) mode.\n el.setAttribute('role', 'button');\n el.setAttribute('tabindex', '-1');\n el.setAttribute('aria-pressed', 'false');\n el.setAttribute(\n 'aria-label',\n corner === 'start'\n ? 'Selection start corner — drag, or activate to place it with a tap'\n : 'Selection end corner — drag, or activate to place it with a tap',\n );\n el.addEventListener('pointerdown', (e) => this.#onPointerDown(e as PointerEvent, el, corner));\n container.appendChild(el);\n return el;\n }\n\n #onPointerDown(e: PointerEvent, handle: HTMLElement, corner: RangeCorner): void {\n if (e.button !== 0 && e.pointerType === 'mouse') return;\n e.preventDefault();\n e.stopPropagation();\n const callbacks = this.#callbacks;\n if (!callbacks) return;\n\n handle.classList.add('dragging');\n // `startPointerDrag` promotes immediately with these options, so `onMove`\n // firing at least once is the only reliable signal that this was a drag.\n let moved = false;\n const finish = (): void => {\n handle.classList.remove('dragging');\n callbacks.commit();\n };\n startPointerDrag(e, handle, {\n onMove: (moveEvent) => {\n moved = true;\n const target = callbacks.cellAt(moveEvent.clientX, moveEvent.clientY);\n if (target) callbacks.resize(corner, target.row, target.col);\n },\n onEnd: () => {\n handle.classList.remove('dragging');\n if (moved) callbacks.commit();\n else callbacks.arm(corner);\n },\n // An aborted drag still leaves the range wherever the last move put it,\n // so the plugin must re-render — but it is never a tap.\n onCancel: finish,\n });\n }\n}\n\n// #endregion\n","/**\n * Selection Plugin (Class-based)\n *\n * Provides selection functionality for tbw-grid.\n * Supports three modes:\n * - 'cell': Single cell selection (default). No border, just focus highlight.\n * - 'row': Row selection. Clicking a cell selects the entire row.\n * - 'range': Range selection. Shift+click or drag to select rectangular cell ranges.\n */\n\nimport { GridClasses } from '../../core/constants';\nimport { announce, getA11yMessage } from '../../core/internal/aria';\nimport { getPrimaryPointer } from '../../core/internal/pointer-modality';\nimport { clearCellFocus, getRowIndexFromCell } from '../../core/internal/utils';\nimport type { GridElement, HeaderClickEvent, PluginManifest, PluginQuery } from '../../core/plugin/base-plugin';\nimport { BaseGridPlugin, CellClickEvent, CellMouseEvent } from '../../core/plugin/base-plugin';\nimport { isExpanderColumn, isUtilityColumn } from '../../core/plugin/expander-column';\nimport type { ColumnConfig } from '../../core/types';\nimport type { ContextMenuParams, HeaderContextMenuItem } from '../context-menu/types';\nimport {\n createDragAlternativeMenu,\n type DragAlternativeAction,\n type DragAlternativeMenu,\n} from '../shared/drag-alternative-menu';\nimport {\n computeKeyboardExtension,\n fieldsBetween,\n normalizeMode,\n selectableColumnFields,\n type NormalizedModeConfig,\n} from './column-selection';\nimport {\n createRangeFromAnchor,\n getAllCellsInRanges,\n isCellInAnyRange,\n normalizeRange,\n rangesEqual,\n toPublicRanges,\n} from './range-selection';\nimport styles from './selection.css?inline';\nimport { RangeCornerHandles, SelectionToolbar, type RangeCorner, type RangeRect } from './touch-selection';\nimport type {\n CellRange,\n InternalCellRange,\n SelectionAxis,\n SelectionChangeDetail,\n SelectionConfig,\n SelectionMode,\n SelectionResult,\n} from './types';\n\n/**\n * Resolve the primary in-row mode from a config that may be a single string\n * or an array. Used by `configRules` (which run before `attach()` populates\n * the cached normalized mode). Falls back to `'cell'` on invalid input —\n * `attach()` will throw the proper error message later.\n */\nfunction primaryModeOf(mode: SelectionMode | SelectionMode[] | undefined): SelectionMode {\n if (typeof mode === 'string') return mode;\n if (Array.isArray(mode)) {\n const other = mode.find((m) => m !== 'column');\n if (other) return other;\n if (mode.includes('column')) return 'column';\n }\n return 'cell';\n}\n\n/** Special field name for the selection checkbox column */\nconst CHECKBOX_COLUMN_FIELD = '__tbw_checkbox';\n\n/**\n * Order band for the range-extension item contributed to the context menu.\n * `insertGroupSeparators` groups by the tens digit, so 60 keeps it in its own\n * group below column move (50-53).\n */\nconst EXTEND_ITEM_ORDER = 60;\n\n/** Keys that move grid focus — selection reacts to these in cell/range mode. */\nfunction isFormField(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) return false;\n const tag = target.tagName;\n return tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA' || target.isContentEditable;\n}\n\nconst NAV_KEYS: readonly string[] = [\n 'ArrowUp',\n 'ArrowDown',\n 'ArrowLeft',\n 'ArrowRight',\n 'Tab',\n 'Home',\n 'End',\n 'PageUp',\n 'PageDown',\n];\n\n/**\n * Build the selection change event detail for the current state.\n *\n * `axis` decides which axis \"won\" — when both row and column are populated\n * (which can only happen in transient states inside mutual-exclusion handling),\n * `axis` is the source of truth for which one to report.\n */\nfunction buildSelectionEvent(\n configuredMode: SelectionMode | SelectionMode[],\n axis: SelectionAxis,\n primary: SelectionMode,\n state: {\n selectedCell: { row: number; col: number } | null;\n selected: Set<number>;\n ranges: InternalCellRange[];\n selectedColumns: Set<string>;\n },\n colCount: number,\n visibleColumnFieldsInOrder: readonly string[],\n): SelectionChangeDetail {\n // Column axis active → ignore in-row state, report column field names in\n // visible-column order. WHY: `Set` insertion order reflects toggle history\n // (so the same selection emits different orderings depending on how the\n // user reached it), which makes `selection-change.detail.selectedColumns`\n // non-deterministic for consumers. Filtering the visible field list keeps\n // the event detail stable and consistent with `getSelectedColumns()`.\n if (axis === 'column' && state.selectedColumns.size > 0) {\n return {\n mode: configuredMode,\n activeAxis: 'column',\n ranges: [],\n selectedColumns: visibleColumnFieldsInOrder.filter((f) => state.selectedColumns.has(f)),\n };\n }\n\n if (primary === 'cell' && state.selectedCell) {\n return {\n mode: configuredMode,\n activeAxis: 'cell',\n ranges: [\n {\n from: { row: state.selectedCell.row, col: state.selectedCell.col },\n to: { row: state.selectedCell.row, col: state.selectedCell.col },\n },\n ],\n selectedColumns: [],\n };\n }\n\n if (primary === 'row' && state.selected.size > 0) {\n // Sort rows and merge contiguous indices into minimal ranges\n const sorted = [...state.selected].sort((a, b) => a - b);\n const ranges: CellRange[] = [];\n let start = sorted[0];\n let end = start;\n for (let i = 1; i < sorted.length; i++) {\n if (sorted[i] === end + 1) {\n end = sorted[i];\n } else {\n ranges.push({ from: { row: start, col: 0 }, to: { row: end, col: colCount - 1 } });\n start = sorted[i];\n end = start;\n }\n }\n ranges.push({ from: { row: start, col: 0 }, to: { row: end, col: colCount - 1 } });\n return { mode: configuredMode, activeAxis: 'row', ranges, selectedColumns: [] };\n }\n\n if (primary === 'range' && state.ranges.length > 0) {\n return {\n mode: configuredMode,\n activeAxis: 'range',\n ranges: toPublicRanges(state.ranges),\n selectedColumns: [],\n };\n }\n\n return { mode: configuredMode, activeAxis: 'none', ranges: [], selectedColumns: [] };\n}\n\n/**\n * Selection Plugin for tbw-grid\n *\n * Adds cell, row, and range selection capabilities to the grid with full keyboard support.\n * Whether you need simple cell highlighting or complex multi-range selections, this plugin has you covered.\n *\n * ## Installation\n *\n * ```ts\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n * ```\n *\n * ## Selection Modes\n *\n * Configure the plugin with one of three modes via {@link SelectionConfig}:\n *\n * - **`'cell'`** - Single cell selection (default). Click cells to select individually.\n * - **`'row'`** - Full row selection. Click anywhere in a row to select the entire row.\n * - **`'range'`** - Rectangular selection. Click and drag or Shift+Click to select ranges.\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Arrow Keys` | Move selection |\n * | `Shift + Arrow` | Extend selection (range mode) |\n * | `Ctrl/Cmd + Click` | Toggle selection (multi-select) |\n * | `Shift + Click` | Extend to clicked cell/row |\n * | `Ctrl/Cmd + A` | Select all (range mode) |\n * | `Escape` | Clear selection |\n *\n * > **Note:** When `multiSelect: false`, Ctrl/Shift modifiers are ignored —\n * > clicks always select a single item.\n *\n * ## CSS Custom Properties\n *\n * | Property | Description |\n * |----------|-------------|\n * | `--tbw-focus-background` | Focused row background |\n * | `--tbw-range-selection-bg` | Range selection fill |\n * | `--tbw-range-border-color` | Range selection border |\n *\n * @example Basic row selection\n * ```ts\n * grid.gridConfig = {\n * columns: [...],\n * plugins: [new SelectionPlugin({ mode: 'row' })],\n * };\n * ```\n *\n * @example Range selection with event handling\n * ```ts\n * grid.gridConfig = {\n * plugins: [new SelectionPlugin({ mode: 'range' })],\n * };\n *\n * grid.on('selection-change', ({ mode, ranges }) => {\n * console.log(`Selected ${ranges.length} ranges in ${mode} mode`);\n * });\n * ```\n *\n * @example Programmatic selection control\n * ```ts\n * const plugin = grid.getPluginByName('selection');\n *\n * // Get current selection\n * const selection = plugin.getSelection();\n * console.log(selection.ranges);\n *\n * // Set selection programmatically\n * plugin.setRanges([{ from: { row: 0, col: 0 }, to: { row: 5, col: 3 } }]);\n *\n * // Clear all selection\n * plugin.clearSelection();\n * ```\n *\n * @see {@link SelectionMode} for detailed mode descriptions\n * @see {@link SelectionConfig} for configuration options\n * @see {@link SelectionResult} for the selection result structure\n * @see {@link SelectionConfig} for interactive examples in the docs site\n * @since 0.1.1\n */\nexport class SelectionPlugin extends BaseGridPlugin<SelectionConfig> {\n /**\n * Plugin manifest - declares queries and configuration validation rules.\n * @internal\n */\n static override readonly manifest: PluginManifest<SelectionConfig> = {\n hookPriority: {\n // Inject the checkbox before pinned-columns reorders and applies sticky offsets.\n processColumns: -20,\n },\n queries: [\n { type: 'getSelection', description: 'Get the current selection state' },\n { type: 'selectRows', description: 'Select specific rows by index (row mode only)' },\n {\n type: 'getSelectedRowIndices',\n description: 'Get sorted array of row indices touched by the current selection (works in all modes)',\n },\n { type: 'getSelectedRows', description: 'Get actual row objects for the current selection (works in all modes)' },\n { type: 'getSelectedColumns', description: 'Get field names of selected columns (column mode only)' },\n { type: 'selectColumns', description: 'Select specific columns by field name (column mode only)' },\n {\n type: 'selectContextMenuTarget',\n description:\n 'Move the selection to the cell a context menu was invoked on unless it is already selected; returns getSelectedRowIndices()',\n },\n {\n type: 'getContextMenuItems',\n description: 'Contribute the non-dragging range-extension action (WCAG 2.2 SC 2.5.7)',\n },\n ],\n configRules: [\n {\n id: 'selection/range-dblclick',\n severity: 'warn',\n message:\n `\"triggerOn: 'dblclick'\" has no effect when mode is \"range\".\\n` +\n ` → Range selection uses drag interaction (mousedown → mousemove), not click events.\\n` +\n ` → The \"triggerOn\" option only affects \"cell\" and \"row\" selection modes.`,\n check: (config) => primaryModeOf(config.mode) === 'range' && config.triggerOn === 'dblclick',\n },\n {\n id: 'selection/column-checkbox',\n severity: 'warn',\n message:\n `\"checkbox: true\" only renders in row mode.\\n` +\n ` → Column selection has no checkbox UI; activate columns via Ctrl+Click on a header or Ctrl+Space on a focused cell.`,\n check: (config) => !!config.checkbox && primaryModeOf(config.mode) !== 'row',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'selection';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<SelectionConfig> {\n return {\n mode: 'cell',\n triggerOn: 'click',\n enabled: true,\n multiSelect: true,\n touchMode: 'transient',\n };\n }\n\n // #region Touch Selection State (#304)\n\n /**\n * True while touch selection mode is active — long-press entered it, plain\n * taps now toggle instead of replacing, and the selection toolbar is shown.\n *\n * Read-only for consumers; drive it with {@link exitTouchSelection}.\n *\n * @since 3.5.0\n */\n get touchSelectionActive(): boolean {\n return this.#touchActive;\n }\n\n #touchActive = false;\n /**\n * Whether the *current* range was started by a finger/stylus. Gates the\n * corner handles: on desktop they would sit inside other ranges (multi-range\n * is mouse-only) and get in the way of normal drag-selection.\n */\n #rangeFromCoarsePointer = false;\n readonly #toolbar = new SelectionToolbar();\n readonly #cornerHandles = new RangeCornerHandles();\n\n // #endregion\n\n // #region Non-dragging range alternatives (WCAG 2.2 SC 2.5.7)\n\n /** Corner waiting for the tap that will place it, set by tapping its handle. */\n #armedCorner: RangeCorner | null = null;\n /**\n * Last cell the user deliberately anchored with a *primary* interaction.\n * Kept separate from {@link cellAnchor} because opening a context menu outside\n * the range re-anchors that one so the menu targets the invoked cell (see\n * `#selectContextMenuTarget`) — which would leave \"Extend selection to here\"\n * with nothing to extend from.\n */\n #extendAnchor: { row: number; col: number } | null = null;\n #extendMenu: DragAlternativeMenu | null = null;\n\n // #endregion\n\n // #region Internal State\n /** Row selection state (row mode) */\n private selected = new Set<number>();\n private lastSelected: number | null = null;\n private anchor: number | null = null;\n\n /** Range selection state (range mode) */\n private ranges: InternalCellRange[] = [];\n private activeRange: InternalCellRange | null = null;\n private cellAnchor: { row: number; col: number } | null = null;\n private isDragging = false;\n\n /** Pending keyboard navigation update (processed in afterRender) */\n private pendingKeyboardUpdate: { shiftKey: boolean } | null = null;\n\n /** Pending row-mode keyboard update (processed in afterRender) */\n private pendingRowKeyUpdate: { shiftKey: boolean } | null = null;\n\n /** Cell selection state (cell mode) */\n private selectedCell: { row: number; col: number } | null = null;\n\n /**\n * Column selection state (column mode / `['row','column']` array mode).\n * Stored as field-name strings so selection survives column pinning,\n * reordering, and virtualization recycling.\n */\n private selectedColumns = new Set<string>();\n /** Anchor column for Ctrl+Shift+click range extension. */\n private columnAnchor: string | null = null;\n /** Head column for Ctrl+Shift+Arrow keyboard extension. */\n private columnHead: string | null = null;\n /** Which axis last won. Drives `SelectionChangeDetail.activeAxis` and mutual exclusion. */\n private activeAxis: SelectionAxis = 'none';\n\n /**\n * Normalized mode config, computed once in `attach()`. All mode checks in this\n * plugin go through `this.#mode` rather than `this.config.mode` so the\n * single-string vs. array distinction is resolved in exactly one place.\n */\n #mode: NormalizedModeConfig = { primary: 'cell', columnEnabled: false, bothAxes: false };\n\n /** Last synced focus row — used to detect when grid focus moves so selection follows */\n private lastSyncedFocusRow = -1;\n /** Last synced focus col (cell mode) */\n private lastSyncedFocusCol = -1;\n\n /** Debounce timer for selection announcements */\n private announceTimer: ReturnType<typeof setTimeout> | null = null;\n /** Set by Shift/Ctrl+Space so the next announcement names the rows/columns selected. */\n #pendingSpanAnnouncement: { axis: 'row' | 'column'; count: number } | null = null;\n /** Range built by Shift/Ctrl+Space; Shift+Arrow keeps its spanned axis full while it is still `activeRange`. */\n #spanRange: { axis: 'row' | 'column'; range: InternalCellRange } | null = null;\n\n /** True when selection was explicitly set (click/keyboard) — prevents #syncSelectionToFocus from overwriting */\n private explicitSelection = false;\n\n // #endregion\n\n // #region Private Helpers - Selection Enabled Check\n\n /**\n * Check if selection is enabled at the grid level.\n * Grid-wide `selectable: false` or plugin's `enabled: false` disables all selection.\n */\n private isSelectionEnabled(): boolean {\n // Check plugin config first\n if (this.config.enabled === false) return false;\n // Check grid-level config\n return this.grid.effectiveConfig?.selectable !== false;\n }\n\n // #endregion\n\n // #region Private Helpers - Selectability\n\n /**\n * Check if a row/cell is selectable.\n * Returns true if selectable, false if not.\n */\n private checkSelectable(rowIndex: number, colIndex?: number): boolean {\n const { isSelectable } = this.config;\n if (!isSelectable) return true; // No callback = all selectable\n\n const row = this.rows[rowIndex];\n if (!row) return false;\n\n // colIndex is a visible-column index (from data-col), so use visibleColumns\n const column = colIndex !== undefined ? this.visibleColumns[colIndex] : undefined;\n return isSelectable(row, rowIndex, column, colIndex);\n }\n\n /**\n * Check if an entire row is selectable (for row mode).\n */\n private isRowSelectable(rowIndex: number): boolean {\n return this.checkSelectable(rowIndex);\n }\n\n /**\n * Check if a cell is selectable (for cell/range modes).\n */\n private isCellSelectable(rowIndex: number, colIndex: number): boolean {\n return this.checkSelectable(rowIndex, colIndex);\n }\n\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Resolve the user-supplied mode (string OR array) into a single normalized\n // shape. Throws on invalid combinations (e.g. ['row', 'cell']).\n this.#mode = normalizeMode(this.config.mode);\n\n // Subscribe to events that invalidate selection\n // When rows change due to filtering/grouping/tree/sort operations, selection indices become invalid\n this.on('filter-change', () => this.clearSelectionSilent());\n this.on('group-toggle', () => this.clearSelectionSilent());\n this.on('tree-expand', () => this.clearSelectionSilent());\n this.on('sort-change', () => this.clearSelectionSilent());\n\n // Auto-select the row currently being edited so consumers of getSelectedRows()\n // / selectedRows() always see the row the user is actually working with.\n // Issue #284: editing and selection were independent, so a row could be in\n // edit mode while selectedRows() returned a stale (or different) row.\n // Only meaningful in row mode — cell mode tracks single-cell focus, range\n // mode is for bulk selection. We listen to `edit-open` (broadcast by\n // EditingPlugin) — `edit-close` is intentionally ignored so existing\n // selections are preserved when the user finishes editing.\n this.on<{ rowIndex: number; row: unknown }>('edit-open', ({ rowIndex, row }) => {\n if (!this.isSelectionEnabled()) return;\n if (row == null || rowIndex < 0) return;\n if (this.#mode.primary !== 'row') return;\n if (!this.isRowSelectable(rowIndex)) return;\n if (this.selected.has(rowIndex)) return;\n // multiSelect: false → replace; otherwise add to existing set so\n // multi-selection is preserved when the user enters edit on one row.\n if (this.config.multiSelect === false) {\n this.selected.clear();\n }\n this.selected.add(rowIndex);\n this.lastSelected = rowIndex;\n this.anchor = rowIndex;\n this.explicitSelection = true;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n });\n\n // Source-row collection replaced from outside (host swapped `[rows]`).\n // `data-change` also fires for in-place cell edits, so gate on sourceRowCount\n // changing — the only signal that the source collection actually grew/shrank.\n // Without this, stored row indices resolve against a different array and\n // getSelectedRows() silently returns the wrong rows.\n let lastSourceRowCount = -1;\n grid.addEventListener(\n 'data-change',\n ((event: CustomEvent<{ sourceRowCount: number }>) => {\n const { sourceRowCount } = event.detail;\n const hasSelection = this.selected.size > 0 || this.ranges.length > 0 || this.selectedCell !== null;\n if (lastSourceRowCount !== -1 && sourceRowCount !== lastSourceRowCount && hasSelection) {\n this.clearSelectionSilent();\n }\n lastSourceRowCount = sourceRowCount;\n }) as EventListener,\n { signal: this.disconnectSignal },\n );\n\n // SC 2.5.7 fallback: without a ContextMenuPlugin there is no menu to\n // contribute \"Extend selection to here\" to, so host a bare one. Delegated\n // rather than per-cell — cells are recycled on every render.\n grid.addEventListener(\n 'contextmenu',\n ((event: MouseEvent) => {\n if (this.#contextMenuPlugin()) return; // the real menu owns this gesture\n const cell = (event.target as Element | null)?.closest?.<HTMLElement>('.cell[data-row][data-col]');\n if (!cell) return;\n const row = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const col = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n const actions = this.#extendActions(row, col);\n if (!actions) return;\n event.preventDefault();\n this.#openExtendMenu(cell, actions);\n }) as EventListener,\n { signal: this.disconnectSignal },\n );\n }\n\n /**\n * Handle queries from other plugins.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'getSelection') {\n return this.getSelection();\n }\n if (query.type === 'getSelectedRowIndices') {\n return this.getSelectedRowIndices();\n }\n if (query.type === 'getSelectedRows') {\n return this.getSelectedRows();\n }\n if (query.type === 'selectRows') {\n this.selectRows(query.context as number[]);\n return true;\n }\n if (query.type === 'getSelectedColumns') {\n return this.getSelectedColumns();\n }\n if (query.type === 'selectColumns') {\n const fields = query.context as string[];\n this.#setColumnSelection(fields);\n return true;\n }\n if (query.type === 'selectContextMenuTarget') {\n const { rowIndex, colIndex } = query.context as { rowIndex: number; colIndex: number };\n this.#selectContextMenuTarget(rowIndex, colIndex);\n return this.getSelectedRowIndices();\n }\n if (query.type === 'getContextMenuItems') {\n const params = query.context as ContextMenuParams | undefined;\n if (!params || params.isHeader) return undefined;\n const actions = this.#extendActions(params.rowIndex, params.columnIndex);\n if (!actions) return undefined;\n return actions.map((action, i): HeaderContextMenuItem => ({\n id: `selection-extend-${i}`,\n label: action.label,\n disabled: action.disabled,\n action: () => action.run(),\n order: EXTEND_ITEM_ORDER + i,\n }));\n }\n return undefined;\n }\n\n /** @internal */\n override detach(): void {\n // Clear aria-multiselectable that we set on the role=grid element.\n // Other lifecycle teardown happens below.\n const rowsBodyEl = this.gridElement?.querySelector('.rows-body');\n rowsBodyEl?.removeAttribute('aria-multiselectable');\n\n this.#toolbar.destroy();\n this.#cornerHandles.destroy();\n this.#extendMenu?.dispose();\n this.#extendMenu = null;\n this.#armedCorner = null;\n this.#extendAnchor = null;\n this.#touchActive = false;\n\n this.selected.clear();\n this.ranges = [];\n this.activeRange = null;\n this.cellAnchor = null;\n this.isDragging = false;\n this.selectedCell = null;\n this.selectedColumns.clear();\n this.columnAnchor = null;\n this.columnHead = null;\n this.activeAxis = 'none';\n this.pendingKeyboardUpdate = null;\n this.pendingRowKeyUpdate = null;\n this.lastSyncedFocusRow = -1;\n this.lastSyncedFocusCol = -1;\n // Cancel the debounced screen-reader announcement so it can't fire after\n // teardown (the callback reaches `announce()` → `requestAnimationFrame`,\n // which is undefined once the host/DOM env is gone — surfaces as an\n // \"Unhandled Error: requestAnimationFrame is not defined\" in tests).\n if (this.announceTimer) {\n clearTimeout(this.announceTimer);\n this.announceTimer = null;\n }\n }\n\n /**\n * Clear selection without emitting an event.\n * Used when selection is invalidated by external changes (filtering, grouping, etc.)\n *\n * Column selection is intentionally PRESERVED here — it tracks field names,\n * not row indices, so it stays valid across filter/sort/group changes. Use\n * {@link clearSelection} (public) or {@link #clearAllAxesSilent} for a full wipe.\n */\n private clearSelectionSilent(): void {\n this.selected.clear();\n this.ranges = [];\n this.activeRange = null;\n this.cellAnchor = null;\n this.selectedCell = null;\n this.lastSelected = null;\n this.anchor = null;\n this.lastSyncedFocusRow = -1;\n this.lastSyncedFocusCol = -1;\n if (this.activeAxis !== 'column') {\n this.activeAxis = 'none';\n }\n this.requestAfterRender();\n }\n\n // #endregion\n\n // #region Touch Selection Mode (#304)\n\n /**\n * True when a press originated from a finger or stylus.\n *\n * Prefers the per-event `pointerType` over the `(pointer: coarse)` media\n * query so that a hybrid device (e.g. a Surface with both a touchscreen and\n * a mouse) keeps mouse chords working while touch gets the long-press idiom.\n */\n #isCoarseEvent(e: MouseEvent): boolean {\n const pointerType = (e as PointerEvent).pointerType;\n if (pointerType === 'touch' || pointerType === 'pen') return true;\n if (pointerType === 'mouse') return false;\n return getPrimaryPointer() === 'coarse';\n }\n\n /**\n * Enter touch selection mode, seeding it with `rowIndex`.\n *\n * Long-pressing a row while already in the mode range-extends from the\n * anchor instead — that branch is handled by the caller.\n */\n #enterTouchSelection(rowIndex: number): boolean {\n if (!this.isRowSelectable(rowIndex)) return false;\n this.#touchActive = true;\n this.selected.clear();\n this.selected.add(rowIndex);\n this.anchor = rowIndex;\n this.lastSelected = rowIndex;\n this.explicitSelection = true;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return true;\n }\n\n /**\n * Leave touch selection mode.\n *\n * With the default `touchMode: 'transient'` this also clears the selection —\n * the mode *is* the selection, as in Gmail. With `touchMode: 'sticky'` the\n * selection survives so a later round can build on it.\n *\n * No-op when the mode is not active.\n *\n * @since 3.5.0\n */\n exitTouchSelection(): void {\n if (!this.#touchActive) return;\n this.#touchActive = false;\n if ((this.config.touchMode ?? 'transient') === 'transient') {\n this.selected.clear();\n this.anchor = null;\n this.lastSelected = null;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n }\n this.requestAfterRender();\n }\n\n /** Range-extend from the touch anchor to `rowIndex` (second long-press). */\n #extendTouchSelection(rowIndex: number): void {\n const anchor = this.anchor ?? rowIndex;\n const start = Math.min(anchor, rowIndex);\n const end = Math.max(anchor, rowIndex);\n for (let i = start; i <= end; i++) {\n if (this.isRowSelectable(i)) this.selected.add(i);\n }\n this.lastSelected = rowIndex;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /** The `ContextMenuPlugin` instance, when one is registered. */\n #contextMenuPlugin(): { showMenu(x: number, y: number, params: Record<string, unknown>): void } | undefined {\n const plugin = this.grid?.getPluginByName?.('contextMenu') ?? this.grid?.getPluginByName?.('context-menu');\n const candidate = plugin as { showMenu?: unknown } | undefined;\n return typeof candidate?.showMenu === 'function'\n ? (candidate as { showMenu(x: number, y: number, params: Record<string, unknown>): void })\n : undefined;\n }\n\n /** Resolve the rendered cell element for a (row, visible-col) pair. */\n #cellFor(row: number, col: number): HTMLElement | null {\n return this.gridElement?.querySelector<HTMLElement>(`.cell[data-row=\"${row}\"][data-col=\"${col}\"]`) ?? null;\n }\n\n /** Resolve the (row, col) of the cell under a viewport coordinate. */\n #cellAtPoint(clientX: number, clientY: number): { row: number; col: number } | null {\n const host = this.gridElement;\n const doc = host?.ownerDocument;\n const el = doc?.elementFromPoint?.(clientX, clientY);\n const cell = (el as Element | null)?.closest?.('.cell[data-row][data-col]');\n // `elementFromPoint` is document-wide: when several grids share a page the\n // drag can wander over a *different* grid's cells. Only accept cells that\n // belong to this grid instance.\n if (!cell || !host?.contains?.(cell)) return null;\n const row = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const col = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n return row >= 0 && col >= 0 ? { row, col } : null;\n }\n\n /** Move one corner of the active range while its handle is dragged. */\n #resizeRangeCorner(corner: RangeCorner, row: number, col: number): void {\n const current = this.ranges[this.ranges.length - 1];\n if (!current) return;\n const normalized = normalizeRange(current);\n const anchor =\n corner === 'start'\n ? { row: normalized.endRow, col: normalized.endCol }\n : { row: normalized.startRow, col: normalized.startCol };\n const next = createRangeFromAnchor(anchor, { row, col });\n if (rangesEqual(current, next)) return;\n this.ranges[this.ranges.length - 1] = next;\n this.activeRange = next;\n this.cellAnchor = anchor;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n // #endregion\n // #region Non-dragging range alternatives (WCAG 2.2 SC 2.5.7)\n\n /**\n * The single-pointer alternative to paint-dragging a range: click the first\n * cell as usual, then open the context menu on the opposite corner and pick\n * \"Extend selection to here\".\n *\n * Returns `null` — not an empty array — when the action does not apply, so\n * the plugin contributes nothing rather than a dead entry.\n */\n #extendActions(rowIndex: number, colIndex: number): DragAlternativeAction[] | null {\n if (this.#mode.primary !== 'range') return null;\n if (!this.isSelectionEnabled()) return null;\n if (rowIndex < 0 || colIndex < 0) return null;\n if (!this.isCellSelectable(rowIndex, colIndex)) return null;\n const anchor = this.#extendAnchor;\n if (!anchor) return null;\n if (anchor.row === rowIndex && anchor.col === colIndex) return null;\n return [\n {\n label: 'Extend selection to here',\n run: () => this.#extendSelectionTo(rowIndex, colIndex),\n },\n ];\n }\n\n /** Replace the active range with the rectangle from {@link #extendAnchor} to (row, col). */\n #extendSelectionTo(row: number, col: number): void {\n const anchor = this.#extendAnchor;\n if (!anchor) return;\n const next = createRangeFromAnchor(anchor, { row, col });\n this.ranges = [next];\n this.activeRange = next;\n this.cellAnchor = anchor;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Fallback menu for when no `ContextMenuPlugin` is registered. The alternative\n * to a drag must exist whether or not an optional plugin is installed, so the\n * shared bare menu stands in — but it must never stack on top of the real one.\n */\n #openExtendMenu(anchor: HTMLElement, actions: DragAlternativeAction[]): void {\n this.#extendMenu ??= createDragAlternativeMenu('tbw-range-extend-menu', 'tbw-range-extend-menu');\n this.#extendMenu.open(anchor, 'Selection', actions);\n }\n\n /**\n * Arm (or disarm) a range corner after its handle was tapped rather than\n * dragged. The next cell click places the corner.\n */\n #armRangeCorner(corner: RangeCorner): void {\n this.#armedCorner = this.#armedCorner === corner ? null : corner;\n this.#cornerHandles.setArmed(this.#armedCorner);\n if (this.gridElement) {\n announce(\n this.gridElement,\n this.#armedCorner ? 'Select a cell to place the selection corner' : 'Selection corner placement cancelled',\n );\n }\n }\n\n /** Clear any armed corner. Returns `true` when something was actually cleared. */\n #disarmRangeCorner(): boolean {\n if (!this.#armedCorner) return false;\n this.#armedCorner = null;\n this.#cornerHandles.setArmed(null);\n return true;\n }\n\n // #endregion\n // #region Touch chrome\n\n /**\n * Render (or tear down) the touch chrome: the selection-mode toolbar and the\n * range corner handles. Called from `afterRender()`.\n *\n * The toolbar follows `#touchActive`, which can only have been set by a\n * coarse-pointer long-press — the modality check happens once, per event, at\n * entry. Re-testing the `(pointer: coarse)` media query here would break\n * hybrid devices (a Surface reports a fine primary pointer even while the\n * user is touching the screen). The corner handles follow the same rule via\n * `#rangeFromCoarsePointer`: they exist because touch has no Shift/Ctrl, so a\n * mouse-started range never gets them.\n */\n #renderTouchChrome(container: HTMLElement | null): void {\n if (!container) return;\n\n if (this.#touchActive) {\n this.#toolbar.show(container, this.selected.size, this.#contextMenuPlugin() !== undefined, {\n selectAll: () => this.selectAll(),\n clear: () => this.clearSelection(),\n done: () => this.exitTouchSelection(),\n more: (btn) => this.#openOverflowMenu(btn),\n });\n } else {\n this.#toolbar.destroy();\n }\n\n const active =\n this.#rangeFromCoarsePointer && this.#mode.primary === 'range' && this.ranges.length > 0\n ? this.ranges[this.ranges.length - 1]\n : null;\n const rect: RangeRect | null = active ? normalizeRange(active) : null;\n if (!rect) this.#disarmRangeCorner();\n this.#cornerHandles.render(container, rect, (row, col) => this.#cellFor(row, col), {\n cellAt: (x, y) => this.#cellAtPoint(x, y),\n resize: (corner, row, col) => this.#resizeRangeCorner(corner, row, col),\n commit: () => this.requestAfterRender(),\n arm: (corner) => this.#armRangeCorner(corner),\n });\n }\n\n /**\n * Surface the `ContextMenuPlugin` items from the toolbar's \"More…\" button, so\n * touch users don't lose the actions a mouse user reaches by right-clicking.\n */\n #openOverflowMenu(anchorEl: HTMLElement): void {\n const menu = this.#contextMenuPlugin();\n if (!menu) return;\n const rect = anchorEl.getBoundingClientRect?.();\n const rowIndex = this.lastSelected ?? -1;\n menu.showMenu(rect?.left ?? 0, rect?.bottom ?? 0, {\n row: rowIndex >= 0 ? this.rows[rowIndex] : null,\n rowIndex,\n // ContextMenuParams.selectedRows is a list of row *indices*, not row objects.\n selectedRows: this.getSelectedRowIndices(),\n });\n }\n\n // #endregion\n // #region Event Handlers\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean {\n // Skip all selection if disabled at grid level or plugin level\n if (!this.isSelectionEnabled()) return false;\n\n // Skip if event type doesn't match configured trigger.\n // This allows dblclick mode to only select on double-click.\n const { triggerOn = 'click' } = this.config;\n if (event.originalEvent.type !== triggerOn) return false;\n\n switch (this.#mode.primary) {\n case 'cell':\n return this.#clickSelectCell(event);\n case 'row':\n return this.#clickSelectRow(event);\n case 'range':\n return this.#clickSelectRange(event);\n default:\n return false;\n }\n }\n\n /**\n * CELL MODE: single-cell selection. Skips utility columns and non-selectable\n * cells, and only emits when the selection actually changed.\n */\n #clickSelectCell(event: CellClickEvent): boolean {\n const { rowIndex, colIndex } = event;\n\n // Check if this is a utility column (expander columns, etc.)\n // event.column is already resolved from _visibleColumns in the event builder.\n // Allow the event to propagate, but don't select utility cells.\n if (event.column && isUtilityColumn(event.column)) return false;\n if (!this.isCellSelectable(rowIndex, colIndex)) return false;\n\n const currentCell = this.selectedCell;\n // Same cell already selected\n if (currentCell && currentCell.row === rowIndex && currentCell.col === colIndex) return false;\n\n this.selectedCell = { row: rowIndex, col: colIndex };\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return false;\n }\n\n /** ROW MODE: multi-select with Shift/Ctrl, checkbox toggle, or single select. */\n #clickSelectRow(event: CellClickEvent): boolean {\n const { rowIndex, originalEvent, column } = event;\n if (!this.isRowSelectable(rowIndex)) return false;\n\n const multiSelect = this.config.multiSelect !== false;\n const shiftKey = originalEvent.shiftKey && multiSelect;\n // While touch selection mode is active a plain tap toggles, exactly as if\n // Ctrl were held — that is the whole point of the mode. Mouse chords are\n // untouched, so a hybrid device supports both at once.\n const ctrlKey = (originalEvent.ctrlKey || originalEvent.metaKey || this.#touchActive) && multiSelect;\n const isCheckbox = column?.checkboxColumn === true;\n\n if (shiftKey && this.anchor !== null) {\n // Shift+Click: Range select from anchor to clicked row\n const start = Math.min(this.anchor, rowIndex);\n const end = Math.max(this.anchor, rowIndex);\n if (!ctrlKey) this.selected.clear();\n for (let i = start; i <= end; i++) {\n if (this.isRowSelectable(i)) this.selected.add(i);\n }\n } else if (ctrlKey || (isCheckbox && multiSelect)) {\n // Ctrl+Click or checkbox click: Toggle individual row\n if (this.selected.has(rowIndex)) this.selected.delete(rowIndex);\n else this.selected.add(rowIndex);\n this.anchor = rowIndex;\n } else {\n // Plain click (or any click when multiSelect is false): select only clicked row.\n // Same row already selected → nothing to do.\n if (this.selected.size === 1 && this.selected.has(rowIndex)) return false;\n this.selected.clear();\n this.selected.add(rowIndex);\n this.anchor = rowIndex;\n }\n\n this.lastSelected = rowIndex;\n this.explicitSelection = true;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return false;\n }\n\n /** RANGE MODE: Shift+click extends the selection, plain click starts a new one. */\n #clickSelectRange(event: CellClickEvent): boolean {\n const { rowIndex, colIndex, originalEvent } = event;\n\n // Skip utility columns and non-selectable cells - don't start selection from them\n if (event.column && isUtilityColumn(event.column)) return false;\n if (!this.isCellSelectable(rowIndex, colIndex)) return false;\n\n // A tapped (not dragged) corner handle is waiting for a destination — this\n // click places it instead of starting a new selection (SC 2.5.7).\n if (this.#armedCorner) {\n const corner = this.#armedCorner;\n this.#disarmRangeCorner();\n this.#resizeRangeCorner(corner, rowIndex, colIndex);\n return true;\n }\n\n // A tap never reaches `onCellMouseDown` (coarse presses only dispatch it\n // after a long-press), so the handle gate has to be updated here too.\n this.#rangeFromCoarsePointer = this.#isCoarseEvent(originalEvent);\n\n const shiftKey = originalEvent.shiftKey;\n const ctrlKey = (originalEvent.ctrlKey || originalEvent.metaKey) && this.config.multiSelect !== false;\n\n if (shiftKey && this.cellAnchor) {\n // Extend selection from anchor\n const newRange = createRangeFromAnchor(this.cellAnchor, { row: rowIndex, col: colIndex });\n\n // Check if range actually changed\n const currentRange = this.ranges.length > 0 ? this.ranges[this.ranges.length - 1] : null;\n if (currentRange && rangesEqual(currentRange, newRange)) return false;\n\n if (!ctrlKey) this.ranges = [newRange];\n else if (this.ranges.length > 0) this.ranges[this.ranges.length - 1] = newRange;\n else this.ranges.push(newRange);\n this.activeRange = newRange;\n } else {\n const newRange: InternalCellRange = {\n startRow: rowIndex,\n startCol: colIndex,\n endRow: rowIndex,\n endCol: colIndex,\n };\n if (ctrlKey) {\n this.ranges.push(newRange);\n } else {\n // Plain click - only emit if the same single-cell range isn't already selected\n if (this.ranges.length === 1 && rangesEqual(this.ranges[0], newRange)) return false;\n this.ranges = [newRange];\n }\n this.activeRange = newRange;\n this.cellAnchor = { row: rowIndex, col: colIndex };\n this.#extendAnchor = { row: rowIndex, col: colIndex };\n }\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return false;\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n // Skip all selection if disabled at grid level or plugin level\n if (!this.isSelectionEnabled()) return false;\n\n if (this.#mode.columnEnabled && this.#keyColumnAxis(event)) return true;\n\n const mode = this.#mode.primary;\n\n // Escape unwinds one step at a time: an armed range corner first, then\n // touch selection mode, then the selection itself.\n if (event.key === 'Escape' && this.#disarmRangeCorner()) return true;\n\n // Escape leaves touch selection mode first (an external keyboard is the\n // documented escape hatch), and only clears selection on a second press.\n if (event.key === 'Escape' && this.#touchActive) {\n this.exitTouchSelection();\n return true;\n }\n\n // Escape clears selection in all modes\n if (event.key === 'Escape') return this.#keyClearSelection(mode);\n\n const isNavKey = NAV_KEYS.includes(event.key);\n switch (mode) {\n case 'cell':\n return isNavKey ? this.#keyNavCellMode() : false;\n case 'row':\n return this.#keyRowMode(event);\n case 'range':\n return this.#keyRangeMode(event, isNavKey);\n default:\n return false;\n }\n }\n\n /**\n * Column-axis keyboard chords (only reachable when `columnEnabled`):\n * - **Ctrl/⌘+Space** — WAI-ARIA Grid: toggle column selection for the focused\n * column. Per spec the key is `' '`; some older hosts report `'Spacebar'`.\n * - **Ctrl/⌘+Shift+ArrowLeft/Right** — extend column selection along the\n * visible columns.\n *\n * @returns `true` when the chord was consumed.\n */\n #keyColumnAxis(event: KeyboardEvent): boolean {\n const ctrlOrMeta = event.ctrlKey || event.metaKey;\n if (!ctrlOrMeta) return false;\n // Editors keep their own Ctrl+Space / Ctrl+Shift+Arrow (word selection) behaviour.\n if (isFormField(event.target) || this.grid.query<boolean>('isEditing').some(Boolean)) return false;\n\n if (event.key === ' ' || event.key === 'Spacebar') {\n const column = this.visibleColumns[this.grid._focusCol];\n if (!column || isUtilityColumn(column) || typeof column.field !== 'string') return false;\n event.preventDefault();\n event.stopPropagation();\n this.selectColumn(column.field, { toggle: true });\n return true;\n }\n\n if (\n event.shiftKey &&\n this.activeAxis === 'column' &&\n this.config.multiSelect !== false &&\n (event.key === 'ArrowLeft' || event.key === 'ArrowRight')\n ) {\n const fields = selectableColumnFields(this.visibleColumns);\n const direction = event.key === 'ArrowLeft' ? 'left' : 'right';\n const newHead = computeKeyboardExtension(this.columnHead, fields, direction);\n if (newHead === null || this.columnAnchor === null) return false;\n event.preventDefault();\n event.stopPropagation();\n this.selectColumn(newHead, { range: true });\n return true;\n }\n\n return false;\n }\n\n /** Escape: clear the active axis. Defers to EditingPlugin while an edit is open. */\n #keyClearSelection(mode: SelectionMode): boolean {\n // If editing is active, let the EditingPlugin cancel the active edit first\n if (this.grid.query<boolean>('isEditing').some(Boolean)) return false;\n\n // Column axis — clear it only; a single Escape clears the *active* axis when\n // both axes are configured.\n if (this.activeAxis === 'column') {\n this.selectedColumns.clear();\n this.columnAnchor = null;\n this.columnHead = null;\n this.activeAxis = 'none';\n } else if (mode === 'cell') {\n this.selectedCell = null;\n } else if (mode === 'row') {\n this.selected.clear();\n this.anchor = null;\n } else if (mode === 'range') {\n this.ranges = [];\n this.activeRange = null;\n this.cellAnchor = null;\n }\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return true;\n }\n\n /** CELL MODE: selection follows focus (but respects selectability). */\n #keyNavCellMode(): boolean {\n // Use queueMicrotask so grid's handler runs first and updates focusRow/focusCol\n queueMicrotask(() => {\n const focusRow = this.grid._focusRow;\n const focusCol = this.grid._focusCol;\n // Only select if the cell is selectable; clear when navigating to a non-selectable cell\n this.selectedCell = this.isCellSelectable(focusRow, focusCol) ? { row: focusRow, col: focusCol } : null;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n });\n return false; // Let grid handle navigation\n }\n\n /** ROW MODE: Arrow/Page/Ctrl+Home/End move selection, Shift extends, Ctrl+A selects all. */\n #keyRowMode(event: KeyboardEvent): boolean {\n const multiSelect = this.config.multiSelect !== false;\n const isRowNavKey =\n event.key === 'ArrowUp' ||\n event.key === 'ArrowDown' ||\n event.key === 'PageUp' ||\n event.key === 'PageDown' ||\n ((event.ctrlKey || event.metaKey) && (event.key === 'Home' || event.key === 'End'));\n\n if (isRowNavKey) {\n const shiftKey = event.shiftKey && multiSelect;\n\n // Set anchor SYNCHRONOUSLY before grid moves focus\n if (shiftKey && this.anchor === null) this.anchor = this.grid._focusRow;\n\n // Mark explicit selection SYNCHRONOUSLY so #syncSelectionToFocus\n // won't overwrite the anchor if afterRender fires before our update\n this.explicitSelection = true;\n\n // Store pending update — processed in afterRender when grid has updated focusRow\n this.pendingRowKeyUpdate = { shiftKey };\n\n // Schedule afterRender (grid's refreshVirtualWindow(false) may skip it)\n queueMicrotask(() => this.requestAfterRender());\n return false; // Let grid handle navigation\n }\n\n return this.#keySelectAll(event, multiSelect);\n }\n\n /**\n * RANGE MODE: Shift+Arrow extends, plain Arrow resets, Ctrl+A selects all.\n * Tab always navigates without extending (even with Shift).\n */\n #keyRangeMode(event: KeyboardEvent, isNavKey: boolean): boolean {\n if (!isNavKey) return this.#keyRangeSpan(event) || this.#keySelectAll(event, this.config.multiSelect !== false);\n\n const shouldExtend = event.shiftKey && event.key !== 'Tab';\n\n // Capture anchor BEFORE grid moves focus (synchronous)\n // This ensures the anchor is the starting point, not the destination\n if (shouldExtend && !this.cellAnchor) {\n this.cellAnchor = { row: this.grid._focusRow, col: this.grid._focusCol };\n }\n\n // Mark pending update - will be processed in afterRender when grid updates focus\n this.pendingKeyboardUpdate = { shiftKey: shouldExtend };\n\n // Schedule afterRender to run after grid's keyboard handler completes.\n // Grid's refreshVirtualWindow(false) skips afterRender for performance,\n // so we explicitly request it to process pendingKeyboardUpdate.\n queueMicrotask(() => this.requestAfterRender());\n\n return false; // Let grid handle navigation\n }\n\n /**\n * WAI-ARIA APG grid chords in range mode:\n * - **Shift+Space** — select the row(s) spanned by the active range (or the focused row).\n * - **Ctrl/⌘+Space** — select the spanned column(s); only when the column axis is not\n * configured (otherwise {@link #keyColumnAxis} owns it).\n *\n * Skipped for form-field targets and while an edit is open so editors still type spaces.\n */\n #keyRangeSpan(event: KeyboardEvent): boolean {\n if (event.key !== ' ' && event.key !== 'Spacebar') return false;\n const ctrlOrMeta = event.ctrlKey || event.metaKey;\n let axis: 'row' | 'column';\n if (event.shiftKey && !ctrlOrMeta) axis = 'row';\n else if (ctrlOrMeta && !event.shiftKey && !this.#mode.columnEnabled) axis = 'column';\n else return false;\n if (event.altKey) return false;\n if (isFormField(event.target)) return false;\n if (this.grid.query<boolean>('isEditing').some(Boolean)) return false;\n\n const rowCount = this.rows.length;\n const colCount = this.visibleColumns.length;\n if (rowCount === 0 || colCount === 0) return false;\n\n const focus = { row: this.grid._focusRow, col: this.grid._focusCol };\n const span = this.activeRange\n ? normalizeRange(this.activeRange)\n : { startRow: focus.row, startCol: focus.col, endRow: focus.row, endCol: focus.col };\n const range: InternalCellRange =\n axis === 'row'\n ? { startRow: span.startRow, startCol: 0, endRow: span.endRow, endCol: colCount - 1 }\n : { startRow: 0, startCol: span.startCol, endRow: rowCount - 1, endCol: span.endCol };\n\n event.preventDefault();\n event.stopPropagation();\n\n // Anchor on the corner farthest from focus so a following Shift+Arrow keeps the far edge.\n const anchor = {\n row: Math.abs(focus.row - range.startRow) >= Math.abs(focus.row - range.endRow) ? range.startRow : range.endRow,\n col: Math.abs(focus.col - range.startCol) >= Math.abs(focus.col - range.endCol) ? range.startCol : range.endCol,\n };\n this.ranges = [range];\n this.activeRange = range;\n this.#spanRange = { axis, range };\n this.cellAnchor = anchor;\n this.#extendAnchor = anchor;\n this.#pendingSpanAnnouncement = {\n axis,\n count: axis === 'row' ? range.endRow - range.startRow + 1 : range.endCol - range.startCol + 1,\n };\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return true;\n }\n\n /** Ctrl/⌘+A: select all (skipped while editing, and when single-select). */\n #keySelectAll(event: KeyboardEvent, multiSelect: boolean): boolean {\n if (!multiSelect || event.key !== 'a' || !(event.ctrlKey || event.metaKey)) return false;\n if (this.grid.query<boolean>('isEditing').some(Boolean)) return false;\n event.preventDefault();\n event.stopPropagation();\n this.selectAll();\n return true;\n }\n\n /** @internal */\n override onCellMouseDown(event: CellMouseEvent): boolean | void {\n // Skip all selection if disabled at grid level or plugin level\n if (!this.isSelectionEnabled()) return;\n\n // ROW MODE — touch selection entry (#304).\n //\n // `event-delegation.ts` only dispatches `mousedown` for a coarse pointer\n // *after* a 400 ms long-press has elapsed, so reaching here with a coarse\n // event already means \"the user held the row down\". Header presses are\n // excluded — they belong to the column header menu (#270).\n if (this.#mode.primary === 'row') {\n if (event.rowIndex === undefined || event.rowIndex < 0) return;\n if (this.config.multiSelect === false) return;\n if (!this.#isCoarseEvent(event.originalEvent)) return;\n if (event.column && isUtilityColumn(event.column)) return;\n if (this.#touchActive) {\n this.#extendTouchSelection(event.rowIndex);\n return true;\n }\n return this.#enterTouchSelection(event.rowIndex) || undefined;\n }\n\n if (this.#mode.primary !== 'range') return;\n if (event.rowIndex === undefined || event.colIndex === undefined) return;\n if (event.rowIndex < 0) return; // Header\n\n // A tapped corner handle owns the next press: swallow it so no drag starts\n // and the range is not reset before `onCellClick` places the corner.\n if (this.#armedCorner) return true;\n\n this.#rangeFromCoarsePointer = this.#isCoarseEvent(event.originalEvent);\n\n // Skip utility columns (expander columns, etc.)\n // event.column is already resolved from _visibleColumns in the event builder\n if (event.column && isUtilityColumn(event.column)) {\n return; // Don't start selection on utility columns\n }\n\n // Skip non-selectable cells - don't start drag from them\n if (!this.isCellSelectable(event.rowIndex, event.colIndex)) {\n return;\n }\n\n // Let onCellClick handle shift+click for range extension\n if (event.originalEvent.shiftKey && this.cellAnchor) {\n return;\n }\n\n // Start drag selection\n this.isDragging = true;\n const rowIndex = event.rowIndex;\n const colIndex = event.colIndex;\n\n // When multiSelect is false, Ctrl+click starts a new single range instead of adding\n const ctrlKey = (event.originalEvent.ctrlKey || event.originalEvent.metaKey) && this.config.multiSelect !== false;\n\n const newRange: InternalCellRange = {\n startRow: rowIndex,\n startCol: colIndex,\n endRow: rowIndex,\n endCol: colIndex,\n };\n\n // Check if selection is actually changing (for non-Ctrl clicks)\n if (!ctrlKey && this.ranges.length === 1 && rangesEqual(this.ranges[0], newRange)) {\n // Same cell already selected, just update anchor for potential drag\n this.cellAnchor = { row: rowIndex, col: colIndex };\n this.#extendAnchor = { row: rowIndex, col: colIndex };\n return true;\n }\n\n this.cellAnchor = { row: rowIndex, col: colIndex };\n this.#extendAnchor = { row: rowIndex, col: colIndex };\n\n if (!ctrlKey) {\n this.ranges = [];\n }\n\n this.ranges.push(newRange);\n this.activeRange = newRange;\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return true;\n }\n\n /**\n * Point the selection at the cell a context menu was invoked on — however it\n * was invoked: mouse right-click, touch long-press, Shift+F10, the ContextMenu\n * key, or a synthesised `contextmenu`. A target already inside the selection\n * keeps it, so the menu acts on all of it; otherwise the selection moves to\n * the target row (row mode) or cell (cell/range mode), as file managers and\n * spreadsheets do. `#extendAnchor` is left alone so \"Extend selection to here\"\n * still extends from the last primary anchor rather than from the target.\n */\n #selectContextMenuTarget(rowIndex: number, colIndex: number): void {\n if (rowIndex < 0 || !this.isSelectionEnabled()) return;\n // Column axis (mixed modes): a cell in a selected column is part of the selection.\n if (this.activeAxis === 'column' && this.selectedColumns.has(this.visibleColumns[colIndex]?.field ?? '')) return;\n const mode = this.#mode.primary;\n\n if (mode === 'row') {\n if (!this.selected.has(rowIndex)) this.selectRows([rowIndex]);\n return;\n }\n if (mode !== 'cell' && mode !== 'range') return;\n\n const column = this.visibleColumns[colIndex];\n if (!column || isUtilityColumn(column) || !this.isCellSelectable(rowIndex, colIndex)) return;\n\n if (mode === 'cell') {\n const current = this.selectedCell;\n if (current && current.row === rowIndex && current.col === colIndex) return;\n this.selectedCell = { row: rowIndex, col: colIndex };\n } else {\n if (isCellInAnyRange(rowIndex, colIndex, this.ranges)) return;\n const range: InternalCellRange = { startRow: rowIndex, startCol: colIndex, endRow: rowIndex, endCol: colIndex };\n this.ranges = [range];\n this.activeRange = range;\n this.cellAnchor = { row: rowIndex, col: colIndex };\n }\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /** @internal */\n override onCellMouseMove(event: CellMouseEvent): boolean | void {\n // Skip all selection if disabled at grid level or plugin level\n if (!this.isSelectionEnabled()) return;\n\n if (this.#mode.primary !== 'range') return;\n if (!this.isDragging || !this.cellAnchor) return;\n if (event.rowIndex === undefined || event.colIndex === undefined) return;\n if (event.rowIndex < 0) return;\n\n // When dragging, clamp to first data column (skip utility columns)\n // colIndex from events is a visible-column index (from data-col)\n let targetCol = event.colIndex;\n const column = this.visibleColumns[targetCol];\n if (column && isUtilityColumn(column)) {\n // Find the first non-utility visible column\n const firstDataCol = this.visibleColumns.findIndex((col) => !isUtilityColumn(col));\n if (firstDataCol >= 0) {\n targetCol = firstDataCol;\n }\n }\n\n const newRange = createRangeFromAnchor(this.cellAnchor, { row: event.rowIndex, col: targetCol });\n\n // Only update and emit if the range actually changed\n const currentRange = this.ranges.length > 0 ? this.ranges[this.ranges.length - 1] : null;\n if (currentRange && rangesEqual(currentRange, newRange)) {\n return true; // Range unchanged, no need to update\n }\n\n if (this.ranges.length > 0) {\n this.ranges[this.ranges.length - 1] = newRange;\n } else {\n this.ranges.push(newRange);\n }\n this.activeRange = newRange;\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return true;\n }\n\n /** @internal */\n override onCellMouseUp(_event: CellMouseEvent): boolean | void {\n // Skip all selection if disabled at grid level or plugin level\n if (!this.isSelectionEnabled()) return;\n\n if (this.#mode.primary !== 'range') return;\n if (this.isDragging) {\n this.isDragging = false;\n return true;\n }\n }\n\n /**\n * Header click handler — drives column-axis selection.\n *\n * - Plain click (and plain Shift+click): defer to MultiSort / core sort by\n * returning `false`. Header-click sort behavior is unchanged.\n * - **Ctrl/Cmd+click**: toggle selection of the clicked column (or replace,\n * when `multiSelect: false`).\n * - **Ctrl/Cmd+Shift+click**: extend selection from the column anchor to the\n * clicked column. Avoids the plain `Shift+click` chord owned by MultiSort.\n *\n * No-ops when column selection isn't enabled or when the clicked column is\n * a utility column (`utility: true`).\n * @internal\n */\n override onHeaderClick(event: HeaderClickEvent): boolean | void {\n if (!this.isSelectionEnabled()) return false;\n if (!this.#mode.columnEnabled) return false;\n if (event.column && isUtilityColumn(event.column)) return false;\n\n const e = event.originalEvent;\n const ctrlKey = e.ctrlKey || e.metaKey;\n if (!ctrlKey) return false; // Plain / Shift click → sort path\n\n const field = event.field;\n if (!field) return false;\n\n e.preventDefault();\n if (typeof e.stopPropagation === 'function') e.stopPropagation();\n\n const range = e.shiftKey === true && this.config.multiSelect !== false && this.columnAnchor !== null;\n this.selectColumn(field, range ? { range: true } : { toggle: true });\n return true; // Handled — suppress sort\n }\n\n // #region Checkbox Column\n\n /**\n * Inject checkbox column when `checkbox: true` and mode is `'row'`.\n * @internal\n */\n override processColumns(columns: ColumnConfig[]): ColumnConfig[] {\n if (this.config.checkbox && this.#mode.primary === 'row') {\n // Check if checkbox column already exists\n if (columns.some((col) => col.field === CHECKBOX_COLUMN_FIELD)) {\n return columns;\n }\n const checkboxCol = this.#createCheckboxColumn();\n // Insert after the expander or any leading left-pinned columns.\n const expanderIdx = columns.findIndex(isExpanderColumn);\n const firstUnpinnedIdx = columns.findIndex(\n (column) => (column as ColumnConfig & { pinned?: string }).pinned !== 'left',\n );\n const leftPinnedEnd = firstUnpinnedIdx < 0 ? columns.length : firstUnpinnedIdx;\n const insertAt = expanderIdx >= 0 ? Math.max(expanderIdx + 1, leftPinnedEnd) : leftPinnedEnd;\n return [...columns.slice(0, insertAt), checkboxCol, ...columns.slice(insertAt)];\n }\n return columns;\n }\n\n /**\n * Create the checkbox utility column configuration.\n */\n #createCheckboxColumn(): ColumnConfig & { pinned: 'left' } {\n return {\n field: CHECKBOX_COLUMN_FIELD,\n header: '',\n width: 32,\n pinned: 'left',\n resizable: false,\n sortable: false,\n lockPosition: true,\n utility: true,\n checkboxColumn: true,\n headerRenderer: () => {\n // A label, not a div: it forwards the pointer to the checkbox natively,\n // so the target is the whole 32px cell without inflating the box (SC 2.5.8).\n const container = document.createElement('label');\n container.className = 'tbw-checkbox-header';\n // Hide \"select all\" checkbox in single-select mode\n if (this.config.multiSelect === false) return container;\n const checkbox = document.createElement('input');\n checkbox.type = 'checkbox';\n checkbox.className = 'tbw-select-all-checkbox';\n // The wrapping label names the checkbox implicitly AND gives the\n // otherwise-empty `columnheader` cell screen-reader-visible text.\n const labelText = document.createElement('span');\n labelText.className = 'tbw-sr-only';\n labelText.textContent = getA11yMessage(this.gridElement, 'selectAllRows');\n checkbox.addEventListener('click', (e) => {\n e.stopPropagation(); // Prevent header sort\n if ((e.target as HTMLInputElement).checked) {\n this.selectAll();\n } else {\n this.clearSelection();\n }\n });\n // The label's own click keeps bubbling after it forwards to the\n // checkbox; stop it so the header cell sees nothing.\n container.addEventListener('click', (e) => e.stopPropagation());\n container.append(checkbox, labelText);\n return container;\n },\n renderer: (ctx) => {\n const checkbox = document.createElement('input');\n checkbox.type = 'checkbox';\n checkbox.className = 'tbw-select-row-checkbox';\n // Set initial checked state from current selection\n const cellEl = ctx.cellEl;\n const rowIndex = cellEl ? parseInt(cellEl.getAttribute('data-row') ?? '-1', 10) : -1;\n if (rowIndex >= 0) {\n checkbox.checked = this.selected.has(rowIndex);\n }\n checkbox.setAttribute('aria-label', getA11yMessage(this.gridElement, 'selectRow', Math.max(rowIndex, 0)));\n return checkbox;\n },\n };\n }\n\n /**\n * Update checkbox checked states to reflect current selection.\n * Called from #applySelectionClasses.\n */\n #updateCheckboxStates(gridEl: HTMLElement): void {\n // Update row checkboxes\n const rowCheckboxes = gridEl.querySelectorAll('.tbw-select-row-checkbox') as NodeListOf<HTMLInputElement>;\n rowCheckboxes.forEach((checkbox) => {\n const cell = checkbox.closest('.cell');\n const rowIndex = cell ? getRowIndexFromCell(cell) : -1;\n if (rowIndex >= 0) {\n checkbox.checked = this.selected.has(rowIndex);\n }\n });\n\n // Update header select-all checkbox\n const headerCheckbox = gridEl.querySelector('.tbw-select-all-checkbox') as HTMLInputElement | null;\n if (headerCheckbox) {\n const rowCount = this.rows.length;\n let selectableCount = 0;\n if (this.config.isSelectable) {\n for (let i = 0; i < rowCount; i++) {\n if (this.isRowSelectable(i)) selectableCount++;\n }\n } else {\n selectableCount = rowCount;\n }\n const allSelected = selectableCount > 0 && this.selected.size >= selectableCount;\n const someSelected = this.selected.size > 0;\n headerCheckbox.checked = allSelected;\n headerCheckbox.indeterminate = someSelected && !allSelected;\n }\n }\n\n // #endregion\n\n /**\n * True when focus is currently inside the grid host (data-has-focus is set on focusin).\n * Used to determine whether selection should follow the focus cursor.\n */\n #gridHasFocus(): boolean {\n return this.gridElement?.hasAttribute('data-has-focus') ?? false;\n }\n\n /**\n * Sync selection state to the grid's current focus position.\n * In row mode, keeps `selected` in sync with `_focusRow`.\n * In cell mode, keeps `selectedCell` in sync with `_focusRow`/`_focusCol`.\n * Only updates when the focus has changed since the last sync.\n * Skips when `explicitSelection` is set (click/keyboard set selection directly).\n *\n * Issue #392: selection must be a deliberate user action. The grid's focus\n * cursor defaults to (0,0) even before focus enters the grid, so following it\n * unconditionally auto-selects row 0 / cell 0,0 on first render. Only follow\n * focus when focus is genuinely inside the grid. Always advance the synced\n * markers so the resting position is treated as already-synced (tabbing in and\n * landing on the default cell must not select it).\n */\n #syncSelectionToFocus(mode: string): void {\n const focusRow = this.grid._focusRow;\n const focusCol = this.grid._focusCol;\n\n // Only follow focus when the grid actually has focus. Otherwise, keep the\n // synced markers in step so the resting position is not retroactively selected\n // when focus enters the grid later.\n if (!this.#gridHasFocus()) {\n this.lastSyncedFocusRow = focusRow;\n this.lastSyncedFocusCol = focusCol;\n return;\n }\n\n if (mode === 'row') {\n // Skip auto-sync when selection was explicitly set (Shift/Ctrl click, keyboard)\n if (this.explicitSelection) {\n this.explicitSelection = false;\n this.lastSyncedFocusRow = focusRow;\n return;\n }\n\n if (focusRow !== this.lastSyncedFocusRow) {\n this.lastSyncedFocusRow = focusRow;\n if (this.isRowSelectable(focusRow)) {\n if (!this.selected.has(focusRow) || this.selected.size !== 1) {\n this.selected.clear();\n this.selected.add(focusRow);\n this.lastSelected = focusRow;\n this.anchor = focusRow;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n }\n }\n }\n }\n\n if (mode === 'cell') {\n if (this.explicitSelection) {\n this.explicitSelection = false;\n this.lastSyncedFocusRow = focusRow;\n this.lastSyncedFocusCol = focusCol;\n return;\n }\n\n if (focusRow !== this.lastSyncedFocusRow || focusCol !== this.lastSyncedFocusCol) {\n this.lastSyncedFocusRow = focusRow;\n this.lastSyncedFocusCol = focusCol;\n if (this.isCellSelectable(focusRow, focusCol)) {\n const cur = this.selectedCell;\n if (!cur || cur.row !== focusRow || cur.col !== focusCol) {\n this.selectedCell = { row: focusRow, col: focusCol };\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n }\n }\n }\n }\n }\n\n /**\n * Apply CSS selection classes to row/cell elements.\n * Shared by afterRender and onScrollRender.\n */\n #applySelectionClasses(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const mode = this.#mode.primary;\n const columnEnabled = this.#mode.columnEnabled;\n const hasSelectableCallback = !!this.config.isSelectable;\n\n // Reflect multi-select capability on the role=grid element so screen readers\n // announce the grid as multi-selectable. WAI-ARIA requires aria-multiselectable\n // on the element carrying role=\"grid\" — that's `.rows-body` in our render tree,\n // not the host. `multiSelect` defaults to true; only `false` opts out.\n const rowsBodyEl = gridEl.querySelector('.rows-body');\n if (rowsBodyEl) {\n const multi = this.config.multiSelect !== false;\n rowsBodyEl.setAttribute('aria-multiselectable', multi ? 'true' : 'false');\n }\n\n // Clear all selection classes first (including column-selected).\n // Also reset stale aria-selected on cells that previously carried a\n // selection marker — range/column passes set aria-selected=\"true\" on\n // selected cells, and core only updates the attribute when focus\n // changes — so without an explicit reset a cell that lost selection\n // (axis flipped, range shrank, virtualization recycled the node into a\n // non-selected position) would keep the stale value. We MUST scope the\n // reset to cells that had `.selected` / `.column-selected` BEFORE the\n // class wipe — clearing aria-selected unconditionally would also blow\n // away the focused-cell marker that core's keyboard handler / row\n // renderer set for the active cell, regressing keyboard a11y.\n // Header aria-selected is handled in the columnEnabled block below.\n const allCells = gridEl.querySelectorAll('.cell');\n allCells.forEach((cell) => {\n const hadSelectionMarker =\n cell.classList.contains(GridClasses.SELECTED) || cell.classList.contains('column-selected');\n cell.classList.remove(GridClasses.SELECTED, 'top', 'bottom', 'first', 'last', 'column-selected');\n if (hadSelectionMarker) {\n cell.removeAttribute('aria-selected');\n }\n // Clear selectable attribute - will be re-applied below\n if (hasSelectableCallback) {\n cell.removeAttribute('data-selectable');\n }\n });\n\n const allRows = gridEl.querySelectorAll('.data-grid-row');\n allRows.forEach((row) => {\n row.classList.remove(GridClasses.SELECTED, 'row-focus');\n row.setAttribute('aria-selected', 'false');\n // Clear selectable attribute - will be re-applied below\n if (hasSelectableCallback) {\n row.removeAttribute('data-selectable');\n }\n });\n\n // Clear column-selected from header cells too\n if (columnEnabled) {\n const headerCells = gridEl.querySelectorAll('.header-row > .cell');\n headerCells.forEach((cell) => {\n cell.classList.remove('column-selected');\n cell.removeAttribute('aria-selected');\n });\n }\n\n // ROW MODE: Add row-focus class to selected rows, disable cell-focus, update checkboxes\n if (mode === 'row') {\n // In row mode, disable ALL cell-focus styling - row selection takes precedence\n clearCellFocus(gridEl);\n\n allRows.forEach((row) => {\n const firstCell = row.querySelector('.cell[data-row]');\n const rowIndex = getRowIndexFromCell(firstCell);\n if (rowIndex >= 0) {\n // Mark non-selectable rows\n if (hasSelectableCallback && !this.isRowSelectable(rowIndex)) {\n row.setAttribute('data-selectable', 'false');\n }\n if (this.selected.has(rowIndex)) {\n row.classList.add(GridClasses.SELECTED, 'row-focus');\n row.setAttribute('aria-selected', 'true');\n }\n }\n });\n\n // Update checkbox states if checkbox column is enabled\n if (this.config.checkbox) {\n this.#updateCheckboxStates(gridEl);\n }\n }\n\n // CELL/RANGE MODE: Mark non-selectable cells\n if ((mode === 'cell' || mode === 'range') && hasSelectableCallback) {\n const cells = gridEl.querySelectorAll('.cell[data-row][data-col]');\n cells.forEach((cell) => {\n const rowIndex = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n if (rowIndex >= 0 && colIndex >= 0) {\n if (!this.isCellSelectable(rowIndex, colIndex)) {\n cell.setAttribute('data-selectable', 'false');\n }\n }\n });\n }\n\n // RANGE MODE: Add selected and edge classes to cells\n // Uses neighbor-based edge detection for correct multi-range borders\n if (mode === 'range' && this.ranges.length > 0) {\n // Clear all cell-focus first - selection plugin manages focus styling in range mode\n clearCellFocus(gridEl);\n\n // Pre-normalize ranges for efficient neighbor checks\n const normalizedRanges = this.ranges.map(normalizeRange);\n\n // Fast selection check against pre-normalized ranges\n const isInSelection = (r: number, c: number): boolean => {\n for (const range of normalizedRanges) {\n if (r >= range.startRow && r <= range.endRow && c >= range.startCol && c <= range.endCol) {\n return true;\n }\n }\n return false;\n };\n\n const cells = gridEl.querySelectorAll('.cell[data-row][data-col]');\n cells.forEach((cell) => {\n const rowIndex = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n if (rowIndex >= 0 && colIndex >= 0) {\n // Skip utility columns entirely - don't add any selection classes\n // colIndex from data-col is a visible-column index\n const column = this.visibleColumns[colIndex];\n if (column && isUtilityColumn(column)) {\n return;\n }\n\n if (isInSelection(rowIndex, colIndex)) {\n cell.classList.add(GridClasses.SELECTED);\n cell.setAttribute('aria-selected', 'true');\n\n // Edge detection: add border class where neighbor is not selected\n // This handles single ranges, multi-range, and irregular selections correctly\n if (!isInSelection(rowIndex - 1, colIndex)) cell.classList.add('top');\n if (!isInSelection(rowIndex + 1, colIndex)) cell.classList.add('bottom');\n if (!isInSelection(rowIndex, colIndex - 1)) cell.classList.add('first');\n if (!isInSelection(rowIndex, colIndex + 1)) cell.classList.add('last');\n }\n }\n });\n }\n\n // CELL MODE: Let the grid's native .cell-focus styling handle cell highlighting\n // No additional action needed - the grid already manages focus styling\n\n // COLUMN AXIS: Apply column-selected class + aria-selected to the header cell\n // and every data cell in the matching column. Identifies columns by their\n // visible-index (data-col matches the visibleColumns position) so it works\n // regardless of pinning / reordering — selectedColumns stores fields, not\n // indices, so the rendering layer resolves them per-render.\n if (columnEnabled && this.selectedColumns.size > 0) {\n // Build visible-index → field map once for O(1) lookups.\n const colFieldByIndex: (string | undefined)[] = this.visibleColumns.map((c) =>\n typeof c.field === 'string' ? c.field : undefined,\n );\n\n // Header cells — the grid renders header cells with data-col attributes.\n const headerCells = gridEl.querySelectorAll<HTMLElement>('.header-row > .cell[data-col]');\n headerCells.forEach((cell) => {\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n const field = colIndex >= 0 ? colFieldByIndex[colIndex] : undefined;\n if (field && this.selectedColumns.has(field)) {\n cell.classList.add('column-selected');\n cell.setAttribute('aria-selected', 'true');\n }\n });\n\n // Data cells.\n const cells = gridEl.querySelectorAll<HTMLElement>('.cell[data-col]:not(.header-row .cell)');\n cells.forEach((cell) => {\n // Skip header cells (filter above isn't reliable for nested .header-row scoping)\n if (cell.closest('.header-row')) return;\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n if (colIndex < 0) return;\n const column = this.visibleColumns[colIndex];\n if (!column || isUtilityColumn(column)) return;\n const field = colFieldByIndex[colIndex];\n if (field && this.selectedColumns.has(field)) {\n cell.classList.add('column-selected');\n cell.setAttribute('aria-selected', 'true');\n }\n });\n }\n }\n\n /** @internal */\n override afterRender(): void {\n // Skip rendering selection if disabled at grid level or plugin level\n if (!this.isSelectionEnabled()) return;\n\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const container = gridEl.querySelector('.tbw-grid-root');\n const mode = this.#mode.primary;\n\n // Process pending row keyboard navigation update (row mode)\n // This runs AFTER the grid has updated focusRow\n if (this.pendingRowKeyUpdate && mode === 'row') {\n const { shiftKey } = this.pendingRowKeyUpdate;\n this.pendingRowKeyUpdate = null;\n\n const focusRow = this.grid._focusRow;\n\n if (shiftKey && this.anchor !== null) {\n // Shift+nav: Extend selection from anchor to new focus\n this.selected.clear();\n const start = Math.min(this.anchor, focusRow);\n const end = Math.max(this.anchor, focusRow);\n for (let i = start; i <= end; i++) {\n if (this.isRowSelectable(i)) {\n this.selected.add(i);\n }\n }\n } else {\n // Plain nav: Single select\n if (this.isRowSelectable(focusRow)) {\n this.selected.clear();\n this.selected.add(focusRow);\n this.anchor = focusRow;\n } else {\n this.selected.clear();\n }\n }\n\n this.lastSelected = focusRow;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n }\n\n // Process pending keyboard navigation update (range mode)\n // This runs AFTER the grid has updated focusRow/focusCol\n if (this.pendingKeyboardUpdate && mode === 'range') {\n const { shiftKey } = this.pendingKeyboardUpdate;\n this.pendingKeyboardUpdate = null;\n\n const currentRow = this.grid._focusRow;\n const currentCol = this.grid._focusCol;\n\n if (shiftKey && this.cellAnchor) {\n // Extend selection from anchor to current focus\n let newRange = createRangeFromAnchor(this.cellAnchor, { row: currentRow, col: currentCol });\n const span = this.#spanRange;\n if (span && span.range === this.activeRange) {\n newRange =\n span.axis === 'row'\n ? { ...newRange, startCol: 0, endCol: this.visibleColumns.length - 1 }\n : { ...newRange, startRow: 0, endRow: this.rows.length - 1 };\n span.range = newRange;\n }\n this.ranges = [newRange];\n this.activeRange = newRange;\n } else if (!shiftKey) {\n // Without shift, clear selection (cell-focus will show instead)\n this.ranges = [];\n this.activeRange = null;\n this.cellAnchor = { row: currentRow, col: currentCol }; // Reset anchor to current position\n }\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n }\n\n // Sync selection to grid's focus position.\n // This ensures selection follows keyboard navigation (Tab, arrows, etc.)\n // regardless of which plugin moved the focus.\n this.#syncSelectionToFocus(mode);\n\n // Set data attribute on host for CSS variable scoping\n this.gridElement.setAttribute('data-selection-mode', mode);\n\n // Toggle .selecting class during drag to prevent text selection\n if (container) {\n container.classList.toggle('selecting', this.isDragging);\n }\n\n this.#applySelectionClasses();\n this.#renderTouchChrome(container as HTMLElement | null);\n }\n\n /**\n * Called after scroll-triggered row rendering.\n * Reapplies selection classes to recycled DOM elements.\n * @internal\n */\n override onScrollRender(): void {\n // Skip rendering selection classes if disabled\n if (!this.isSelectionEnabled()) return;\n\n this.#applySelectionClasses();\n }\n\n // #endregion\n\n // #region Public API\n\n /**\n * Get the current selection as a unified result.\n * Works for all selection modes and always returns ranges.\n *\n * @example\n * ```ts\n * const selection = plugin.getSelection();\n * if (selection.ranges.length > 0) {\n * const { from, to } = selection.ranges[0];\n * // For cell mode: from === to (single cell)\n * // For row mode: from.col = 0, to.col = lastCol (full row)\n * // For range mode: rectangular selection\n * }\n * ```\n */\n getSelection(): SelectionResult {\n const event = this.#buildEvent();\n return {\n mode: this.config.mode,\n activeAxis: event.activeAxis,\n ranges: event.ranges,\n selectedColumns: event.selectedColumns,\n anchor: this.cellAnchor,\n };\n }\n\n /**\n * Get all selected cells across all ranges.\n */\n getSelectedCells(): Array<{ row: number; col: number }> {\n return getAllCellsInRanges(this.ranges);\n }\n\n /**\n * Check if a specific cell is in range selection.\n */\n isCellSelected(row: number, col: number): boolean {\n return isCellInAnyRange(row, col, this.ranges);\n }\n\n /**\n * Select all selectable rows (row mode) or all cells (range mode).\n *\n * In row mode, selects every row where `isSelectable` returns true (or all rows if no callback).\n * In range mode, creates a single range spanning all rows and visible columns.\n * Array modes resolve to their row/range axis. Has no effect in cell mode.\n *\n * @example\n * ```ts\n * const plugin = grid.getPluginByName('selection');\n * plugin.selectAll(); // Selects everything in current mode\n * ```\n */\n selectAll(): void {\n const mode = this.#mode.primary;\n\n // Single-select mode: selectAll is a no-op\n if (this.config.multiSelect === false) return;\n\n if (mode === 'row') {\n this.selected.clear();\n for (let i = 0; i < this.rows.length; i++) {\n if (this.isRowSelectable(i)) {\n this.selected.add(i);\n }\n }\n this.explicitSelection = true;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n } else if (mode === 'range') {\n const rowCount = this.rows.length;\n const colCount = this.visibleColumns.length;\n if (rowCount > 0 && colCount > 0) {\n const allRange: InternalCellRange = {\n startRow: 0,\n startCol: 0,\n endRow: rowCount - 1,\n endCol: colCount - 1,\n };\n this.ranges = [allRange];\n this.activeRange = allRange;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n }\n }\n\n /**\n * Select specific rows by index (row mode only).\n * Replaces the current selection with the provided row indices.\n * Indices that are out of bounds or fail the `isSelectable` check are ignored.\n *\n * @param indices - Array of row indices to select\n *\n * @example\n * ```ts\n * const plugin = grid.getPluginByName('selection');\n * plugin.selectRows([0, 2, 4]); // Select rows 0, 2, and 4\n * ```\n */\n selectRows(indices: number[]): void {\n if (this.#mode.primary !== 'row') return;\n // In single-select mode, only use the last index\n const effectiveIndices =\n this.config.multiSelect === false && indices.length > 1 ? [indices[indices.length - 1]] : indices;\n this.selected.clear();\n for (const idx of effectiveIndices) {\n if (idx >= 0 && idx < this.rows.length && this.isRowSelectable(idx)) {\n this.selected.add(idx);\n }\n }\n this.anchor = effectiveIndices.length > 0 ? effectiveIndices[effectiveIndices.length - 1] : null;\n this.explicitSelection = true;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Get the indices of all rows touched by the current selection.\n * Returns indices sorted in ascending order.\n *\n * Works across all selection modes:\n * - **Row mode**: The selected row indices.\n * - **Cell mode**: The row index of the selected cell, or `[]`.\n * - **Range mode**: The unique row indices that intersect any selected range.\n *\n * Indices refer to the grid's processed (sorted/filtered) row array.\n *\n * @example\n * ```ts\n * const plugin = grid.getPluginByName('selection');\n * const rows = plugin.getSelectedRowIndices(); // [0, 2, 4]\n * ```\n */\n getSelectedRowIndices(): number[] {\n const mode = this.#mode.primary;\n\n if (mode === 'row') {\n return [...this.selected].sort((a, b) => a - b);\n }\n\n const rowCount = this.rows.length;\n\n if (mode === 'cell' && this.selectedCell) {\n const { row } = this.selectedCell;\n return row >= 0 && row < rowCount ? [row] : [];\n }\n\n if (mode === 'range' && this.ranges.length > 0) {\n // Merge clamped row intervals instead of Set + sort — a select-all range on a\n // large grid is read on every context-menu invocation / drag start (#541).\n const intervals: Array<[number, number]> = [];\n for (const range of this.ranges) {\n const minRow = Math.max(0, Math.min(range.startRow, range.endRow));\n const maxRow = Math.min(rowCount - 1, Math.max(range.startRow, range.endRow));\n if (minRow <= maxRow) intervals.push([minRow, maxRow]);\n }\n intervals.sort((a, b) => a[0] - b[0]);\n const result: number[] = [];\n let next = 0;\n for (const [minRow, maxRow] of intervals) {\n for (let r = Math.max(minRow, next); r <= maxRow; r++) result.push(r);\n next = Math.max(next, maxRow + 1);\n }\n return result;\n }\n\n return [];\n }\n\n /**\n * Get the actual row objects for the current selection.\n *\n * Works across all selection modes:\n * - **Row mode**: Returns the row objects for all selected rows.\n * - **Cell mode**: Returns the single row containing the selected cell, or `[]`.\n * - **Range mode**: Returns the unique row objects that intersect any selected range.\n *\n * Row objects are resolved from the grid's processed (sorted/filtered) row array,\n * so they always reflect the current visual order.\n *\n * @example\n * ```ts\n * const plugin = grid.getPluginByName('selection');\n * const selected = plugin.getSelectedRows(); // [{ id: 1, name: 'Alice' }, ...]\n * ```\n */\n getSelectedRows<T = unknown>(): T[] {\n const rows = this.rows;\n return this.getSelectedRowIndices()\n .filter((i) => i >= 0 && i < rows.length)\n .map((i) => rows[i]) as T[];\n }\n\n /**\n * Replace the entire column-axis selection with `fields` in a single\n * batched operation. Filters out unknown / utility / hidden fields against\n * the current visible columns, updates `selectedColumns` once, sets the\n * anchor/head to the last accepted field (or null when empty), emits\n * `selection-change` exactly once, and schedules a single render.\n *\n * Used by the `selectColumns` plugin query so external callers wiring\n * many fields at once don't pay N×emit + N×requestAfterRender.\n */\n #setColumnSelection(fields: readonly string[]): void {\n if (!this.#mode.columnEnabled) return;\n\n const visible = selectableColumnFields(this.visibleColumns);\n const allowed = new Set(visible);\n // Preserve caller order but de-duplicate and filter unknowns/utility cols.\n const accepted: string[] = [];\n const seen = new Set<string>();\n for (const f of fields) {\n if (!allowed.has(f) || seen.has(f)) continue;\n seen.add(f);\n accepted.push(f);\n }\n\n this.#enforceMutualExclusion('column');\n\n this.selectedColumns.clear();\n for (const f of accepted) this.selectedColumns.add(f);\n const last = accepted.length > 0 ? accepted[accepted.length - 1] : null;\n this.columnAnchor = last;\n this.columnHead = last;\n this.activeAxis = this.selectedColumns.size > 0 ? 'column' : 'none';\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Toggle, add, or replace a column in the column-axis selection.\n *\n * Column selection is identified by **field name**, so it survives column\n * pinning, reordering, and virtualization recycling. The column must be\n * present in the grid's visible columns and must not be a utility column.\n *\n * Only available when `mode` includes `'column'`. With `multiSelect: false`,\n * `range`/`toggle` options are ignored and the call always replaces the\n * current selection with the single column.\n *\n * @param field - The column field name to select.\n * @param options.range - When true and a `columnAnchor` exists, selects\n * every column from anchor to `field` inclusive (Ctrl+Shift+Click semantics).\n * @param options.toggle - When true, removes `field` if already selected;\n * otherwise adds it. Without `toggle`, plain calls replace the selection.\n * @since 2.8.0\n */\n selectColumn(field: string, options: { range?: boolean; toggle?: boolean } = {}): void {\n if (!this.#mode.columnEnabled) return;\n const fields = selectableColumnFields(this.visibleColumns);\n if (!fields.includes(field)) return;\n\n this.#enforceMutualExclusion('column');\n\n const multiSelect = this.config.multiSelect !== false;\n if (!multiSelect) {\n this.selectedColumns.clear();\n this.selectedColumns.add(field);\n this.columnAnchor = field;\n this.columnHead = field;\n } else if (options.range && this.columnAnchor) {\n const range = fieldsBetween(this.columnAnchor, field, fields);\n this.selectedColumns.clear();\n for (const f of range) this.selectedColumns.add(f);\n this.columnHead = field;\n } else if (options.toggle) {\n if (this.selectedColumns.has(field)) {\n this.selectedColumns.delete(field);\n } else {\n this.selectedColumns.add(field);\n }\n this.columnAnchor = field;\n this.columnHead = field;\n } else {\n this.selectedColumns.clear();\n this.selectedColumns.add(field);\n this.columnAnchor = field;\n this.columnHead = field;\n }\n\n this.activeAxis = this.selectedColumns.size > 0 ? 'column' : 'none';\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Remove a column from the column-axis selection. No-op if `field` isn't selected.\n * @since 2.8.0\n */\n deselectColumn(field: string): void {\n if (!this.#mode.columnEnabled) return;\n if (!this.selectedColumns.delete(field)) return;\n if (this.selectedColumns.size === 0) {\n this.columnAnchor = null;\n this.columnHead = null;\n if (this.activeAxis === 'column') this.activeAxis = 'none';\n }\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Select every selectable column. No-op when `multiSelect: false` or column\n * mode isn't enabled.\n * @since 2.8.0\n */\n selectAllColumns(): void {\n if (!this.#mode.columnEnabled) return;\n if (this.config.multiSelect === false) return;\n const fields = selectableColumnFields(this.visibleColumns);\n if (fields.length === 0) return;\n this.#enforceMutualExclusion('column');\n this.selectedColumns.clear();\n for (const f of fields) this.selectedColumns.add(f);\n this.columnAnchor = fields[0];\n this.columnHead = fields[fields.length - 1];\n this.activeAxis = 'column';\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Clear column-axis selection only. Leaves any row/cell/range selection intact.\n * @since 2.8.0\n */\n clearColumnSelection(): void {\n if (this.selectedColumns.size === 0) return;\n this.selectedColumns.clear();\n this.columnAnchor = null;\n this.columnHead = null;\n if (this.activeAxis === 'column') this.activeAxis = 'none';\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Get the field names of all currently selected columns, in visible-column\n * order. Returns an empty array when the column axis is inactive or empty.\n * @since 2.8.0\n */\n getSelectedColumns(): readonly string[] {\n if (this.selectedColumns.size === 0) return [];\n const fields = selectableColumnFields(this.visibleColumns);\n return fields.filter((f) => this.selectedColumns.has(f));\n }\n\n /**\n * Clear all selection (every axis).\n */\n clearSelection(): void {\n this.selectedCell = null;\n this.selected.clear();\n this.anchor = null;\n this.ranges = [];\n this.activeRange = null;\n this.cellAnchor = null;\n this.selectedColumns.clear();\n this.columnAnchor = null;\n this.columnHead = null;\n this.activeAxis = 'none';\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Set selected ranges programmatically.\n */\n setRanges(ranges: CellRange[]): void {\n this.ranges = ranges.map((r) => ({\n startRow: r.from.row,\n startCol: r.from.col,\n endRow: r.to.row,\n endCol: r.to.col,\n }));\n this.activeRange = this.ranges.length > 0 ? this.ranges[this.ranges.length - 1] : null;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n // #endregion\n\n // #region Private Helpers\n\n #buildEvent(): SelectionChangeDetail {\n // Derive the axis from current state so all existing in-row code paths\n // (which mutate state then emit) report the correct axis without needing\n // to pre-set `this.activeAxis` themselves. Mutual exclusion is enforced\n // separately in {@link #enforceMutualExclusion}.\n const primary = this.#mode.primary;\n const inRowPopulated =\n (primary === 'row' && this.selected.size > 0) ||\n (primary === 'cell' && this.selectedCell !== null) ||\n (primary === 'range' && this.ranges.length > 0);\n\n // Mutual exclusion: in `bothAxes` mode, the user just mutated the in-row\n // axis (we know because `#buildEvent` is called from the in-row code paths\n // immediately after state changes) — so clear stale column selection. The\n // column-axis code paths call `#enforceMutualExclusion('column')`\n // explicitly BEFORE mutating; they then update `activeAxis` to 'column'\n // so the in-row state seen here is empty and this branch doesn't trigger.\n if (this.#mode.bothAxes && inRowPopulated && this.selectedColumns.size > 0) {\n this.selectedColumns.clear();\n this.columnAnchor = null;\n this.columnHead = null;\n if (this.gridElement) {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'selectionAxisChanged', 'row'));\n }\n }\n\n let axis: SelectionAxis;\n if (inRowPopulated) {\n // In-row state always wins when populated — column-axis paths clear\n // in-row state via #enforceMutualExclusion before mutating columns.\n if (primary === 'row') axis = 'row';\n else if (primary === 'cell') axis = 'cell';\n else axis = 'range';\n } else if (this.selectedColumns.size > 0) {\n axis = 'column';\n } else {\n axis = 'none';\n }\n this.activeAxis = axis;\n\n const event = buildSelectionEvent(\n this.config.mode,\n axis,\n primary,\n {\n selectedCell: this.selectedCell,\n selected: this.selected,\n ranges: this.ranges,\n selectedColumns: this.selectedColumns,\n },\n this.columns.length,\n selectableColumnFields(this.visibleColumns),\n );\n // Debounced screen reader announcement for selection changes\n const span = this.#pendingSpanAnnouncement;\n this.#pendingSpanAnnouncement = null;\n if (this.announceTimer) clearTimeout(this.announceTimer);\n this.announceTimer = setTimeout(() => {\n if (span) {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'rangeSpanSelected', span.axis, span.count));\n } else if (event.activeAxis === 'column') {\n const cols = event.selectedColumns;\n if (cols.length === 1) {\n const field = cols[0];\n const col = this.columns.find((c) => c.field === field);\n const label = (typeof col?.header === 'string' && col.header) || field;\n announce(this.gridElement, getA11yMessage(this.gridElement, 'columnSelected', label));\n } else if (cols.length > 1) {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'columnSelectionChanged', cols.length));\n } else {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'columnSelectionCleared'));\n }\n } else {\n const count = event.activeAxis === 'row' ? this.selected.size : event.ranges.length;\n if (count > 0) {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'selectionChanged', count));\n }\n }\n }, 150);\n return event;\n }\n\n /**\n * Enforce row↔column mutual exclusion when both axes are configured\n * (`mode: ['row', 'column']` etc.). Call BEFORE mutating the destination\n * axis so its data won't be wiped along with the inactive axis.\n *\n * Single-string-mode configs are no-ops (the inactive axis can't have data\n * because there's no UI path to populate it). The in-row → column path is\n * called explicitly by the column-axis code; the column → in-row path is\n * handled automatically inside {@link #buildEvent} (which runs on every\n * in-row state change immediately before emitting).\n */\n #enforceMutualExclusion(toAxis: 'row' | 'cell' | 'range' | 'column'): void {\n if (!this.#mode.bothAxes) return;\n if (toAxis === 'column') {\n const hadInRow = this.selected.size > 0 || this.selectedCell !== null || this.ranges.length > 0;\n if (!hadInRow) return;\n this.selected.clear();\n this.lastSelected = null;\n this.anchor = null;\n this.selectedCell = null;\n this.ranges = [];\n this.activeRange = null;\n this.cellAnchor = null;\n if (this.gridElement) {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'selectionAxisChanged', 'column'));\n }\n }\n // Column → in-row flip is handled inside #buildEvent (auto-detected by\n // observing populated in-row state with stale columns).\n }\n\n // #endregion\n}\n"],"mappings":"2HAoCA,IAAa,EAoBD,WCwJZ,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,GAIoB,mBAA1B,sBACT,sBAAA,KACE,EAAG,YAAc,IAGnB,EAAG,YAAc,EAErB,CAUA,SAAgB,EACd,EACA,KACG,GAOH,MAAM,GAHJ,GAAU,oBAAqB,EAC1B,EAA0D,qBAC3D,IACmB,MAAM,WAAW,GAC1C,OAAI,EAAiB,KAAY,GACzB,EAAsB,MAAsB,EACtD,CCvMA,SAAgB,EAAoB,GAClC,IAAK,EAAM,OAAO,EAClB,MAAM,EAAO,EAAK,aAAa,YAC/B,GAAI,EAAM,OAAO,SAAS,EAAM,IAGhC,MAAM,EAAQ,EAAK,QAAQ,kBAC3B,IAAK,EAAO,OAAO,EAEnB,MAAM,EAAS,EAAM,cACrB,IAAK,EAAQ,OAAO,EAGpB,MAAM,EAAO,EAAO,iBAAiB,2BACrC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAK,OAAQ,IAC/B,GAAI,EAAK,KAAO,EAAO,OAAO,EAEhC,OAAO,CACT,CAgBA,SAAgB,EAAe,GACxB,GACL,EAAK,iBAAiB,eAAe,QAAS,GAAO,EAAG,UAAU,OAAO,cAC3E,CC3DA,SAAgB,EAAiB,GAC/B,MApBmC,mBAoB5B,EAAO,KAChB,CAMA,SAAgB,EAAgB,GAC9B,OAA0B,IAAnB,EAAO,OACh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OAAS,GAC/E,OACf,KAAK,SAAS,QACd,KAAK,aAAe,KACpB,KAAK,OAAS,KACd,KAAK,aAAe,KACpB,KAAK,OAAS,GACd,KAAK,YAAc,KACnB,KAAK,WAAa,KACd,KAAK,aACP,EAAS,KAAK,YAAa,EAAe,KAAK,YAAa,uBAAwB,UAExF,CAGF"}
1
+ {"version":3,"file":"index.js","names":["styles","BaseGridPlugin","DEFAULT_A11Y_MESSAGES","getPrimaryPointer","startPointerDrag","GridClasses","announce","gridEl","message","effectiveConfig","a11y","announcements","el","querySelector","textContent","requestAnimationFrame","getA11yMessage","key","args","customFn","messages","getRowIndexFromCell","cell","attr","getAttribute","parseInt","rowEl","closest","parent","parentElement","rows","querySelectorAll","i","length","clearCellFocus","root","forEach","classList","remove","isExpanderColumn","column","field","isUtilityColumn","utility","supportsPopover","HTMLElement","prototype","showPopover","createDragAlternativeMenu","id","className","opened","disposed","abort","AbortController","close","hidePopover","hidden","document","addEventListener","e","composedPath","includes","capture","signal","element","open","anchor","label","actions","createElement","setAttribute","next","relatedTarget","Node","contains","build","host","body","parentNode","appendChild","replaceChildren","action","btn","type","disabled","run","a","getBoundingClientRect","box","left","Math","max","min","window","innerWidth","width","below","bottom","top","height","innerHeight","style","round","place","focus","dispose","isFormFieldKeyTarget","event","path","target","tag","tagName","isContentEditable","normalizeMode","mode","validModes","Set","has","Error","primary","columnEnabled","bothAxes","Array","isArray","m","size","join","other","find","selectableColumnFields","visibleColumns","fields","col","push","indexOfField","indexOf","normalizeRange","range","startRow","endRow","startCol","endCol","toPublicRange","normalized","from","row","to","isCellInAnyRange","ranges","some","isCellInRange","getCellsInRange","cells","createRangeFromAnchor","current","rangesEqual","b","normA","normB","TOOLBAR_CLASS","SelectionToolbar","count","more","callbacks","mounted","this","show","container","selectedCount","showMore","mount","String","destroy","ownerDocument","button","selectAll","clear","done","prepend","onClick","dataset","preventDefault","stopPropagation","HANDLE_CLASS","RangeCornerHandles","start","end","armed","render","rect","cellFor","createHandle","setArmed","hide","corner","handle","name","on","toggle","cellRect","hostRect","x","right","y","onPointerDown","pointerType","add","moved","onMove","moveEvent","cellAt","clientX","clientY","resize","onEnd","commit","arm","onCancel","primaryModeOf","CHECKBOX_COLUMN_FIELD","NAV_KEYS","SelectionPlugin","static","hookPriority","processColumns","queries","description","configRules","severity","check","config","triggerOn","checkbox","styles","defaultConfig","enabled","multiSelect","touchMode","touchSelectionActive","touchActive","rangeFromCoarsePointer","toolbar","cornerHandles","armedCorner","extendAnchor","extendMenu","selected","lastSelected","activeRange","cellAnchor","isDragging","pendingKeyboardUpdate","pendingRowKeyUpdate","selectedCell","selectedColumns","columnAnchor","columnHead","activeAxis","lastSyncedFocusRow","lastSyncedFocusCol","announceTimer","pendingSpanAnnouncement","spanRange","explicitSelection","isSelectionEnabled","grid","selectable","checkSelectable","rowIndex","colIndex","isSelectable","isRowSelectable","isCellSelectable","attach","super","clearSelectionSilent","emit","buildEvent","requestAfterRender","lastSourceRowCount","sourceRowCount","detail","hasSelection","disconnectSignal","contextMenuPlugin","extendActions","openExtendMenu","handleQuery","query","getSelection","getSelectedRowIndices","getSelectedRows","selectRows","context","getSelectedColumns","setColumnSelection","selectContextMenuTarget","params","isHeader","columnIndex","map","order","detach","gridElement","removeAttribute","clearTimeout","isCoarseEvent","enterTouchSelection","exitTouchSelection","extendTouchSelection","candidate","getPluginByName","showMenu","cellAtPoint","elementFromPoint","resizeRangeCorner","extendSelectionTo","armRangeCorner","disarmRangeCorner","renderTouchChrome","clearSelection","openOverflowMenu","active","anchorEl","menu","selectedRows","onCellClick","originalEvent","clickSelectCell","clickSelectRow","clickSelectRange","currentCell","shiftKey","ctrlKey","metaKey","isCheckbox","checkboxColumn","delete","newRange","currentRange","onKeyDown","keyColumnAxis","keyClearSelection","isNavKey","keyNavCellMode","keyRowMode","keyRangeMode","Boolean","_focusCol","selectColumn","direction","newHead","head","headIdx","computeKeyboardExtension","queueMicrotask","focusRow","_focusRow","focusCol","keySelectAll","keyRangeSpan","shouldExtend","ctrlOrMeta","axis","altKey","rowCount","colCount","span","abs","onCellMouseDown","onCellMouseMove","targetCol","firstDataCol","findIndex","onCellMouseUp","_event","onHeaderClick","columns","checkboxCol","createCheckboxColumn","expanderIdx","firstUnpinnedIdx","pinned","leftPinnedEnd","insertAt","slice","header","resizable","sortable","lockPosition","headerRenderer","labelText","checked","append","renderer","ctx","cellEl","updateCheckboxStates","headerCheckbox","selectableCount","allSelected","someSelected","indeterminate","gridHasFocus","hasAttribute","syncSelectionToFocus","cur","applySelectionClasses","hasSelectableCallback","rowsBodyEl","multi","hadSelectionMarker","allRows","normalizedRanges","isInSelection","r","c","colFieldByIndex","afterRender","currentRow","currentCol","onScrollRender","getSelectedCells","cellMap","Map","set","values","getAllCellsInRanges","isCellSelected","allRange","indices","effectiveIndices","idx","sort","intervals","minRow","maxRow","result","filter","visible","allowed","accepted","seen","f","enforceMutualExclusion","last","options","fieldsBetween","deselectColumn","selectAllColumns","clearColumnSelection","setRanges","inRowPopulated","configuredMode","state","visibleColumnFieldsInOrder","sorted","buildSelectionEvent","setTimeout","cols","toAxis"],"sources":["../../../../../../libs/grid/src/lib/core/constants.ts","../../../../../../libs/grid/src/lib/core/internal/aria.ts","../../../../../../libs/grid/src/lib/core/internal/utils.ts","../../../../../../libs/grid/src/lib/core/plugin/expander-column.ts","../../../../../../libs/grid/src/lib/plugins/shared/drag-alternative-menu.ts","../../../../../../libs/grid/src/lib/plugins/shared/form-field-target.ts","../../../../../../libs/grid/src/lib/plugins/selection/column-selection.ts","../../../../../../libs/grid/src/lib/plugins/selection/range-selection.ts","../../../../../../libs/grid/src/lib/plugins/selection/selection.css?inline","../../../../../../libs/grid/src/lib/plugins/selection/touch-selection.ts","../../../../../../libs/grid/src/lib/plugins/selection/selection-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 * 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<Required<A11yMessages>[K]>\n): string {\n type MessageFn = (...a: Parameters<Required<A11yMessages>[K]>) => 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 MessageFn | undefined;\n if (customFn) return customFn(...args);\n return (DEFAULT_A11Y_MESSAGES[key] as MessageFn)(...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 ? '&#x1F5F9;' : '&#9744;'}</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 * Shared Expander Column Utilities\n *\n * Provides a fixed expander column for plugins that need expand/collapse icons\n * (MasterDetail, Tree, RowGrouping). The column is:\n * - Always first in the grid\n * - Cannot be reordered (lockPosition: true)\n * - Has no header (empty string)\n * - Has no right border (borderless styling)\n * - Narrow width (just fits the icon)\n */\n\nimport type { ColumnConfig } from '../types';\n\n/** Special field name for the expander column */\nexport const EXPANDER_COLUMN_FIELD = '__tbw_expander';\n\n/** Default width for the expander column (pixels) */\nexport const EXPANDER_COLUMN_WIDTH = 32;\n\n/**\n * Marker interface for expander column renderers.\n * Used to detect if expander column is already present.\n */\nexport interface ExpanderColumnRenderer {\n (ctx: any): HTMLElement;\n __expanderColumn?: true;\n /** Plugin name that created this expander */\n __expanderPlugin?: string;\n}\n\n/**\n * Check if a column is an expander column.\n */\nexport function isExpanderColumn(column: ColumnConfig): boolean {\n return column.field === EXPANDER_COLUMN_FIELD;\n}\n\n/**\n * Check if a column is a utility column (excluded from selection, clipboard, etc.).\n * Utility columns are non-data columns like expander columns.\n */\nexport function isUtilityColumn(column: ColumnConfig): boolean {\n return column.utility === true;\n}\n\n/**\n * Find an existing expander column in the column array.\n */\nexport function findExpanderColumn(columns: readonly ColumnConfig[]): ColumnConfig | undefined {\n return columns.find(isExpanderColumn);\n}\n\n/**\n * Create the base expander column config.\n * Plugins should add their own renderer to customize the expand icon behavior.\n *\n * @param pluginName - Name of the plugin creating the expander (for debugging)\n * @returns Base column config for the expander column\n */\nexport function createExpanderColumnConfig(pluginName: string): ColumnConfig {\n return {\n field: EXPANDER_COLUMN_FIELD as any,\n header: '', // No header text - visually merges with next column\n width: EXPANDER_COLUMN_WIDTH,\n resizable: false,\n sortable: false,\n filterable: false, // No filter button for expander column\n lockPosition: true,\n utility: true, // Marks this as a utility column (excluded from selection, clipboard, etc.)\n meta: {\n expanderColumn: true,\n expanderPlugin: pluginName,\n },\n };\n}\n","/**\n * Generic click-only action menu — the shared building block for WCAG 2.2\n * SC 2.5.7 \"Dragging Movements\" alternatives in plugins.\n *\n * Every drag affordance in the grid needs a path that works with plain clicks\n * or taps. A keyboard equivalent is **not** enough: SC 2.5.7 is specifically\n * about pointer input, and the W3C Understanding text calls out \"a pop-up menu\n * after tap\" as a conforming alternative. This module is that pop-up.\n *\n * Lives under `plugins/shared/` on purpose: each plugin bundle is built\n * self-contained, so this code is duplicated into the plugins that use it and\n * never lands in the core `index.js` budget.\n *\n * @since 3.6.0\n * @internal\n */\n\n/** Gap between the anchor element and the menu, in px. */\nconst ANCHOR_GAP_PX = 6;\n\n/** Runtime check — happy-dom and older browsers may lack the Popover API. */\nfunction supportsPopover(): boolean {\n return typeof HTMLElement.prototype?.showPopover === 'function';\n}\n\nlet hoverlessQuery: MediaQueryList | null | undefined;\n\n/** Whether the primary pointer cannot hover (touch, most switch devices). */\nfunction isHoverless(): boolean {\n if (hoverlessQuery === undefined) hoverlessQuery = globalThis.matchMedia?.('(hover: none)') ?? null;\n return hoverlessQuery?.matches ?? false;\n}\n\n/**\n * Whether a plugin should also expose its drag alternative as a dedicated\n * inline control, on top of the menu that is always available.\n *\n * Hover-less pointers get one unconditionally — a control revealed on hover is\n * unreachable when nothing can hover, and long-press is the wrong fallback for\n * the tremor and low-dexterity users SC 2.5.7 exists for.\n *\n * Driven by `a11y.dragAlternatives` on the grid config.\n */\nexport function prefersInlineDragAlternative(grid: {\n effectiveConfig?: { a11y?: { dragAlternatives?: 'menu' | 'inline' } };\n}): boolean {\n return grid.effectiveConfig?.a11y?.dragAlternatives === 'inline' || isHoverless();\n}\n\n/** One clickable entry in the menu. */\nexport interface DragAlternativeAction {\n /** Visible text, also the accessible name. */\n label: string;\n /** Render the entry but refuse the click (e.g. \"Move up\" on the first row). */\n disabled?: boolean;\n /** Invoked on click; the menu closes first so focus handling is predictable. */\n run(): void;\n}\n\nexport interface DragAlternativeMenu {\n /**\n * Show `actions` anchored to `anchor`, with `label` as the group's accessible\n * name. Mounted inside the anchor's grid host so it inherits theme tokens.\n */\n open(anchor: HTMLElement, label: string, actions: readonly DragAlternativeAction[]): void;\n /** Hide the menu. Safe to call when already closed. */\n close(): void;\n /** Remove the element and every document-level listener. */\n dispose(): void;\n /** The menu element, or `null` before the first {@link DragAlternativeMenu.open}. */\n readonly element: HTMLElement | null;\n}\n\n/**\n * Create a menu instance.\n *\n * @param id - DOM id for the menu element, unique per owning plugin.\n * @param className - Root class name, so each plugin can style its own menu.\n */\nexport function createDragAlternativeMenu(id: string, className: string): DragAlternativeMenu {\n let root: HTMLDivElement | null = null;\n let opened = false;\n let disposed = false;\n const abort = new AbortController();\n\n function close(): void {\n if (!opened || !root) return;\n opened = false;\n if (supportsPopover()) root.hidePopover();\n root.hidden = true;\n }\n\n function build(): HTMLDivElement {\n const el = document.createElement('div');\n el.id = id;\n el.className = className;\n el.setAttribute('popover', 'manual');\n el.setAttribute('role', 'group');\n // Without the Popover API there is no UA `display: none`, so hide it here.\n el.hidden = true;\n // Tabbing past either end dismisses instead of stranding the user — the\n // menu has no visible trigger to tab back to. A null `relatedTarget` (click\n // focus in Firefox/Safari, focus leaving the document) is ignored.\n el.addEventListener(\n 'focusout',\n (e) => {\n const next = (e as FocusEvent).relatedTarget;\n if (next instanceof Node && !el.contains(next)) close();\n },\n { signal: abort.signal },\n );\n return el;\n }\n\n /**\n * Position against the anchor in viewport coordinates. The menu lives in the\n * top layer, so its containing block is the viewport regardless of where the\n * anchor sits in the DOM.\n */\n function place(anchor: HTMLElement): void {\n if (!root) return;\n const a = anchor.getBoundingClientRect();\n const box = root.getBoundingClientRect();\n const left = Math.max(4, Math.min(a.left, window.innerWidth - box.width - 4));\n const below = a.bottom + ANCHOR_GAP_PX;\n const top = below + box.height <= window.innerHeight ? below : Math.max(4, a.top - ANCHOR_GAP_PX - box.height);\n root.style.left = `${Math.round(left)}px`;\n root.style.top = `${Math.round(top)}px`;\n }\n\n // Any pointer press outside the menu dismisses it. Capture phase so the press\n // that lands on a grid cell still reaches its own handler afterwards.\n document.addEventListener(\n 'pointerdown',\n (e) => {\n if (opened && root && !e.composedPath().includes(root)) close();\n },\n { capture: true, signal: abort.signal },\n );\n document.addEventListener(\n 'keydown',\n (e) => {\n if ((e as KeyboardEvent).key === 'Escape') close();\n },\n { capture: true, signal: abort.signal },\n );\n\n return {\n get element() {\n return root;\n },\n open(anchor, label, actions) {\n if (disposed || actions.length === 0) return;\n if (!root) root = build();\n // Mount inside the grid host (light DOM) so theme custom properties and\n // `color-scheme` cascade in; the top layer keeps it out of overflow.\n const host = anchor.closest<HTMLElement>('tbw-grid, [data-tbw-grid]') ?? document.body;\n if (root.parentNode !== host) host.appendChild(root);\n root.setAttribute('aria-label', label);\n root.replaceChildren();\n for (const action of actions) {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = `${className}-item`;\n btn.textContent = action.label;\n btn.disabled = action.disabled === true;\n btn.addEventListener('click', () => {\n close();\n action.run();\n });\n root.appendChild(btn);\n }\n root.hidden = false;\n if (!opened && supportsPopover()) root.showPopover();\n opened = true;\n place(anchor);\n root.querySelector<HTMLButtonElement>('button:not([disabled])')?.focus();\n },\n close,\n dispose() {\n disposed = true;\n close();\n abort.abort();\n root?.remove();\n root = null;\n },\n };\n}\n","/**\n * True when a keyboard event originates in a text-entry control — `<input>`, `<select>`,\n * `<textarea>` or a contenteditable element. Plugin key handlers (e.g. Space to toggle a tree\n * row) must defer to the control so the keystroke is typed rather than swallowed.\n *\n * Reads `composedPath()[0]` so controls inside an editor's open shadow root are recognised;\n * `event.target` is retargeted to the shadow host by the time the grid sees the event.\n * @internal\n */\nexport function isFormFieldKeyTarget(event: Event): boolean {\n const path = event.composedPath?.() ?? [];\n const target = path.length ? path[0] : event.target;\n if (!(target instanceof HTMLElement)) return false;\n const tag = target.tagName;\n return tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA' || target.isContentEditable;\n}\n","/**\n * Column Selection Core Logic\n *\n * Pure functions for column selection: mode normalization, range expansion\n * across visible columns, and Ctrl+Shift+Arrow extension math. All grid-DOM\n * interaction lives in `SelectionPlugin.ts` — this module is dependency-free\n * and trivially unit-testable.\n *\n * @since 2.8.0\n */\n\nimport type { ColumnConfig } from '../../core/types';\nimport type { SelectionMode } from './types';\n\n// #region Mode normalization\n\n/**\n * Normalized representation of `SelectionConfig.mode`. Splits the user-supplied\n * mode (single string OR array) into:\n *\n * - `primary`: the in-row axis (`'cell' | 'row' | 'range'`) — drives existing\n * click/drag/keyboard behavior. When the user configured column-only, this is\n * `'column'` and the in-row hooks treat it as inert.\n * - `columnEnabled`: whether the column axis is also active. Drives Ctrl+Click\n * on header, Ctrl+Space on focused cell, and the column-selection render pass.\n * - `bothAxes`: shorthand for \"column AND a non-column axis are configured\" —\n * this is the only state where the row↔column mutual-exclusion logic kicks in.\n */\nexport interface NormalizedModeConfig {\n primary: SelectionMode;\n columnEnabled: boolean;\n bothAxes: boolean;\n}\n\n/**\n * Normalize the user-supplied `mode` and validate it.\n *\n * Allowed shapes:\n * - Single: `'cell' | 'row' | 'column' | 'range'`\n * - Array: `['column', X]` or `[X, 'column']` where X is `'cell' | 'row' | 'range'`\n * - Single-element arrays are treated as the contained string for ergonomics.\n *\n * Throws on:\n * - Empty array\n * - Arrays of 3+ items\n * - Arrays without `'column'` (the only purpose of an array is to enable the\n * column axis alongside an in-row axis — `['row', 'cell']` etc. don't compose)\n * - Duplicate entries\n * - Unknown mode strings\n */\nexport function normalizeMode(mode: SelectionMode | SelectionMode[]): NormalizedModeConfig {\n const validModes: ReadonlySet<string> = new Set(['cell', 'row', 'column', 'range']);\n\n if (typeof mode === 'string') {\n if (!validModes.has(mode)) {\n throw new Error(\n `[SelectionPlugin] Invalid selection mode: \"${mode}\". Expected one of: 'cell' | 'row' | 'column' | 'range'.`,\n );\n }\n return {\n primary: mode,\n columnEnabled: mode === 'column',\n bothAxes: false,\n };\n }\n\n if (!Array.isArray(mode)) {\n throw new Error(`[SelectionPlugin] Invalid selection mode: expected string or array, got ${typeof mode}.`);\n }\n\n if (mode.length === 0) {\n throw new Error(`[SelectionPlugin] Invalid selection mode: array must contain at least one mode.`);\n }\n\n for (const m of mode) {\n if (!validModes.has(m)) {\n throw new Error(\n `[SelectionPlugin] Invalid selection mode in array: \"${m}\". Expected one of: 'cell' | 'row' | 'column' | 'range'.`,\n );\n }\n }\n\n // Reject duplicates\n if (new Set(mode).size !== mode.length) {\n throw new Error(`[SelectionPlugin] Invalid selection mode: array contains duplicate entries (${mode.join(', ')}).`);\n }\n\n // Single-element array → treat as plain string\n if (mode.length === 1) {\n return normalizeMode(mode[0]);\n }\n\n if (mode.length > 2) {\n throw new Error(\n `[SelectionPlugin] Invalid selection mode: arrays of more than 2 modes are not supported. Got [${mode.join(', ')}].`,\n );\n }\n\n // 2-element array: must contain 'column' + one of 'cell' | 'row' | 'range'\n const hasColumn = mode.includes('column');\n if (!hasColumn) {\n throw new Error(\n `[SelectionPlugin] Invalid selection mode: [${mode.join(', ')}]. ` +\n `Two-mode arrays must include 'column' (the only valid combinations are ['row','column'], ['cell','column'], ['range','column']). ` +\n `Other in-row modes don't compose meaningfully.`,\n );\n }\n\n const other = mode.find((m) => m !== 'column') as SelectionMode;\n if (other === 'column') {\n // Both entries are 'column' — already caught by duplicate check, but defend\n throw new Error(`[SelectionPlugin] Invalid selection mode: [${mode.join(', ')}].`);\n }\n\n return {\n primary: other,\n columnEnabled: true,\n bothAxes: true,\n };\n}\n\n// #endregion\n\n// #region Field/index helpers\n\n/**\n * Build the ordered list of selectable column fields from the grid's visible\n * columns. Utility columns (checkbox, expander, drag handle) are excluded —\n * they exist to support grid behavior, not to be selected.\n */\nexport function selectableColumnFields(visibleColumns: readonly ColumnConfig[]): string[] {\n const fields: string[] = [];\n for (const col of visibleColumns) {\n if ((col as { utility?: boolean }).utility === true) continue;\n if (typeof col.field === 'string' && col.field.length > 0) {\n fields.push(col.field);\n }\n }\n return fields;\n}\n\n/** Find the index of `field` within the selectable-fields list. -1 if not present. */\nexport function indexOfField(field: string, fields: readonly string[]): number {\n return fields.indexOf(field);\n}\n\n/**\n * Compute the inclusive field range from `anchor` to `target` along the\n * visible-column order. Returns the fields between the two (inclusive),\n * regardless of which one is to the left. Empty if either is missing.\n */\nexport function fieldsBetween(anchor: string, target: string, fields: readonly string[]): string[] {\n const a = indexOfField(anchor, fields);\n const b = indexOfField(target, fields);\n if (a === -1 || b === -1) return [];\n const start = Math.min(a, b);\n const end = Math.max(a, b);\n return fields.slice(start, end + 1);\n}\n\n// #endregion\n\n// #region Keyboard extension (Ctrl+Shift+Arrow)\n\n/**\n * Compute the new \"head\" field after pressing `ArrowLeft` or `ArrowRight`\n * during column-axis keyboard extension. `head` is the most recently focused\n * column edge (the one that moves); `anchor` stays put.\n *\n * Returns the new head field, or `null` if the move would go out of bounds\n * (caller should leave selection unchanged).\n */\nexport function computeKeyboardExtension(\n head: string | null,\n fields: readonly string[],\n direction: 'left' | 'right',\n): string | null {\n if (fields.length === 0) return null;\n if (head === null) return null;\n const headIdx = indexOfField(head, fields);\n if (headIdx < 0) return null;\n const next = direction === 'left' ? Math.max(0, headIdx - 1) : Math.min(fields.length - 1, headIdx + 1);\n if (next === headIdx) return null;\n return fields[next];\n}\n\n// #endregion\n","/**\n * Cell Range Selection Core Logic\n *\n * Pure functions for cell range selection operations.\n */\n\nimport type { InternalCellRange, CellRange } from './types';\n\n/**\n * Normalize a range so startRow/startCol are always <= endRow/endCol.\n * This handles cases where user drags from bottom-right to top-left.\n *\n * @param range - The range to normalize\n * @returns Normalized range with start <= end for both dimensions\n */\nexport function normalizeRange(range: InternalCellRange): InternalCellRange {\n return {\n startRow: Math.min(range.startRow, range.endRow),\n startCol: Math.min(range.startCol, range.endCol),\n endRow: Math.max(range.startRow, range.endRow),\n endCol: Math.max(range.startCol, range.endCol),\n };\n}\n\n/**\n * Convert an internal range to the public event format.\n *\n * @param range - The internal range to convert\n * @returns Public CellRange format with from/to coordinates\n */\nexport function toPublicRange(range: InternalCellRange): CellRange {\n const normalized = normalizeRange(range);\n return {\n from: { row: normalized.startRow, col: normalized.startCol },\n to: { row: normalized.endRow, col: normalized.endCol },\n };\n}\n\n/**\n * Convert multiple internal ranges to public format.\n *\n * @param ranges - Array of internal ranges\n * @returns Array of public CellRange format\n */\nexport function toPublicRanges(ranges: InternalCellRange[]): CellRange[] {\n return ranges.map(toPublicRange);\n}\n\n/**\n * Check if a cell is within a specific range.\n *\n * @param row - The row index to check\n * @param col - The column index to check\n * @param range - The range to check against\n * @returns True if the cell is within the range\n */\nexport function isCellInRange(row: number, col: number, range: InternalCellRange): boolean {\n const normalized = normalizeRange(range);\n return (\n row >= normalized.startRow && row <= normalized.endRow && col >= normalized.startCol && col <= normalized.endCol\n );\n}\n\n/**\n * Check if a cell is within any of the provided ranges.\n *\n * @param row - The row index to check\n * @param col - The column index to check\n * @param ranges - Array of ranges to check against\n * @returns True if the cell is within any range\n */\nexport function isCellInAnyRange(row: number, col: number, ranges: InternalCellRange[]): boolean {\n return ranges.some((range) => isCellInRange(row, col, range));\n}\n\n/**\n * Get all cells within a range as an array of {row, col} objects.\n *\n * @param range - The range to enumerate\n * @returns Array of all cell coordinates in the range\n */\nexport function getCellsInRange(range: InternalCellRange): Array<{ row: number; col: number }> {\n const cells: Array<{ row: number; col: number }> = [];\n const normalized = normalizeRange(range);\n\n for (let row = normalized.startRow; row <= normalized.endRow; row++) {\n for (let col = normalized.startCol; col <= normalized.endCol; col++) {\n cells.push({ row, col });\n }\n }\n\n return cells;\n}\n\n/**\n * Get all unique cells across multiple ranges.\n * Deduplicates cells that appear in overlapping ranges.\n *\n * @param ranges - Array of ranges to enumerate\n * @returns Array of unique cell coordinates\n */\nexport function getAllCellsInRanges(ranges: InternalCellRange[]): Array<{ row: number; col: number }> {\n const cellMap = new Map<string, { row: number; col: number }>();\n\n for (const range of ranges) {\n for (const cell of getCellsInRange(range)) {\n cellMap.set(`${cell.row},${cell.col}`, cell);\n }\n }\n\n return [...cellMap.values()];\n}\n\n/**\n * Merge overlapping or adjacent ranges into fewer ranges.\n * Simple implementation - returns ranges as-is for now.\n * More complex merging logic can be added later for optimization.\n *\n * @param ranges - Array of ranges to merge\n * @returns Merged array of ranges\n */\nexport function mergeRanges(ranges: InternalCellRange[]): InternalCellRange[] {\n // Simple implementation - more complex merging can be added later\n return ranges;\n}\n\n/**\n * Create a range from an anchor cell to a current cell position.\n * The range is not normalized - it preserves the direction of selection.\n *\n * @param anchor - The anchor cell (where selection started)\n * @param current - The current cell (where selection ends)\n * @returns An InternalCellRange from anchor to current\n */\nexport function createRangeFromAnchor(\n anchor: { row: number; col: number },\n current: { row: number; col: number }\n): InternalCellRange {\n return {\n startRow: anchor.row,\n startCol: anchor.col,\n endRow: current.row,\n endCol: current.col,\n };\n}\n\n/**\n * Calculate the number of cells in a range.\n *\n * @param range - The range to measure\n * @returns Total number of cells in the range\n */\nexport function getRangeCellCount(range: InternalCellRange): number {\n const normalized = normalizeRange(range);\n const rowCount = normalized.endRow - normalized.startRow + 1;\n const colCount = normalized.endCol - normalized.startCol + 1;\n return rowCount * colCount;\n}\n\n/**\n * Check if two ranges are equal (same boundaries).\n *\n * @param a - First range\n * @param b - Second range\n * @returns True if ranges have same boundaries after normalization\n */\nexport function rangesEqual(a: InternalCellRange, b: InternalCellRange): boolean {\n const normA = normalizeRange(a);\n const normB = normalizeRange(b);\n return (\n normA.startRow === normB.startRow &&\n normA.startCol === normB.startCol &&\n normA.endRow === normB.endRow &&\n normA.endCol === normB.endCol\n );\n}\n\n/**\n * Check if a range is a single cell (1x1).\n *\n * @param range - The range to check\n * @returns True if the range is exactly one cell\n */\nexport function isSingleCell(range: InternalCellRange): boolean {\n const normalized = normalizeRange(range);\n return normalized.startRow === normalized.endRow && normalized.startCol === normalized.endCol;\n}\n","/**\n * Selection Plugin Styles\n *\n * Scoped to tbw-grid using CSS nesting for light DOM compatibility.\n */\n@layer tbw-plugins {\n tbw-grid {\n /* Prevent text selection during range drag */\n &.selecting .data-grid-row > .cell {\n user-select: none;\n }\n\n /* Prevent text selection when any selection exists */\n &:has(.selection) {\n user-select: none;\n /* Disable cell-focus outline in row mode - row is the focus unit.\n Also disable row-focus outline - selection plugin uses ::after borders instead. */\n &[data-selection-mode='row'] .cell-focus,\n &[data-selection-mode='row'] .row-focus,\n &[data-selection-mode='range'] .cell-focus {\n outline: none;\n }\n }\n\n /* Row selection - use accent color for row focus (only when grid is focused) */\n .data-grid-row.row-focus {\n background-color: var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%));\n /* Replace outline with per-side pseudo-element borders that can collapse */\n outline: none;\n position: relative;\n\n &::after {\n content: '';\n position: absolute;\n inset: 0;\n pointer-events: none;\n border-width: 0;\n border-style: var(--tbw-selection-border-style, var(--tbw-border-style));\n border-color: var(--tbw-range-border-color, var(--tbw-color-accent));\n border-top-width: var(--tbw-selection-border-width, var(--tbw-border-width));\n border-bottom-width: var(--tbw-selection-border-width, var(--tbw-border-width));\n /* Must paint above sticky cells (.sticky-left/.sticky-right have\n z-index: 25 in core/styles/base.css) so the selection border is\n continuous across pinned columns. The border ::after has\n pointer-events: none, so it doesn't interfere with cell content. */\n z-index: 26;\n }\n\n /* Collapse borders between adjacent selected rows */\n + .data-grid-row.row-focus::after {\n border-top-width: 0;\n }\n &:has(+ .data-grid-row.row-focus)::after {\n border-bottom-width: 0;\n }\n\n /* Sticky cells (.sticky-left/.sticky-right) have an opaque\n background-color to hide unpinned content scrolling beneath them\n (see core/styles/rows.css). That opaque layer also hides the\n row-focus background-color set above. Re-paint sticky cells with\n the focus tint layered over panel-bg so the selection tint is\n visible across pinned columns. The selection BORDER is handled by\n the row's ::after with z-index above the sticky cells — no need\n to redraw it here. */\n > .cell.sticky-left,\n > .cell.sticky-right {\n background:\n linear-gradient(var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0),\n var(--tbw-color-panel-bg);\n }\n }\n\n /* Non-selectable selected rows use the row-alt background as the muted\n indicator — keep sticky cells in sync so pinned columns don't flash\n the accent tint on rows that aren't actually selectable. */\n .data-grid-row.row-focus[data-selectable='false'] {\n > .cell.sticky-left,\n > .cell.sticky-right {\n background: var(--tbw-color-row-alt);\n }\n }\n\n /* Selection cell styles - for range mode */\n .data-grid-row > .cell.selected {\n background-color: var(--tbw-range-selection-bg);\n position: relative;\n\n /* Pseudo-element draws the selection range border inside the cell's\n padding box. Uses inset: 0 to stay within overflow: hidden bounds.\n The cell's own borders (row divider, column border) remain visible\n outside the selection border — this is intentional and consistent\n across all themes regardless of border width or visibility. */\n &::after {\n content: '';\n position: absolute;\n inset: 0;\n pointer-events: none;\n border: 0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);\n z-index: 1;\n }\n\n &.top::after {\n border-top-width: var(--tbw-selection-border-width, var(--tbw-border-width));\n }\n &.bottom::after {\n border-bottom-width: var(--tbw-selection-border-width, var(--tbw-border-width));\n }\n &.first::after {\n border-left-width: var(--tbw-selection-border-width, var(--tbw-border-width));\n }\n &.last::after {\n border-right-width: var(--tbw-selection-border-width, var(--tbw-border-width));\n }\n }\n\n /* Non-selectable row styling (row mode).\n The row is dimmed to signal \"not selectable\", but its *data* is still\n content the user has to read, so the exception WCAG 1.4.3 grants inactive\n UI components does not apply. 0.6 pushed the text to 4.24:1 on white;\n 0.65 is the lowest value that clears AA (5.02:1). */\n .data-grid-row[data-selectable='false'] {\n cursor: not-allowed;\n opacity: var(--tbw-selection-disabled-opacity, 0.65);\n\n /* Muted selection indicator */\n &.row-focus {\n background-color: var(--tbw-color-row-alt);\n }\n }\n\n /* Non-selectable cell styling (cell/range mode) */\n .data-grid-row > .cell[data-selectable='false'] {\n cursor: not-allowed;\n opacity: var(--tbw-selection-disabled-opacity, 0.65);\n\n /* Prevent selection highlight on non-selectable cells */\n &.selected {\n background-color: var(--tbw-selection-warning-bg, rgba(from var(--tbw-color-error) r g b / 50%));\n }\n }\n\n /* Selection summary in header */\n .tbw-selection-summary {\n font-size: var(--tbw-font-size-sm, 0.8125rem);\n color: var(--tbw-color-fg-muted);\n white-space: nowrap;\n }\n\n /* Checkbox column styles */\n .data-grid-row > .cell[data-field='__tbw_checkbox'],\n .header-row > .cell[data-field='__tbw_checkbox'] {\n text-align: center;\n cursor: pointer;\n padding: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n /* Row checkboxes are visual indicators - clicks pass through to cell */\n .tbw-select-row-checkbox {\n pointer-events: none;\n margin: 0;\n cursor: pointer;\n }\n\n /* Header select-all checkbox container */\n .tbw-checkbox-header {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100%;\n cursor: pointer;\n }\n\n .tbw-select-all-checkbox {\n margin: 0;\n cursor: pointer;\n }\n\n /* SC 2.5.8: the row checkbox is not itself a target — the row click selects,\n so the whole cell accepts the pointer. Select-all has its own handler, and\n gets a cell-sized target from the `<label>` wrapper instead of a 24px box.\n Coarse pointers still grow the boxes, which is a comfort choice. */\n @media (pointer: coarse) {\n .tbw-select-row-checkbox,\n .tbw-select-all-checkbox {\n min-width: var(--tbw-touch-target-min, 24px);\n min-height: var(--tbw-touch-target-min, 24px);\n }\n }\n\n /* ---- Column-axis selection ----------------------------------------- */\n /* Background tint for selected columns. Applied to the matching header\n cell and every data cell whose data-col resolves to a selected field.\n The tint uses --tbw-column-selection-bg (overridable) defaulting to\n a 12 % accent overlay — visually distinct from row-focus but uses the\n same palette so themes stay coherent. */\n .header-row > .cell.column-selected,\n .data-grid-row > .cell.column-selected {\n background:\n linear-gradient(var(--tbw-column-selection-bg, rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0),\n var(--tbw-color-panel-bg);\n }\n\n /* Pinned columns repaint with sticky background; layer the column tint\n on top of the panel-bg fill so the indicator survives pinning. */\n .data-grid-row > .cell.column-selected.sticky-left,\n .data-grid-row > .cell.column-selected.sticky-right,\n .header-row > .cell.column-selected.sticky-left,\n .header-row > .cell.column-selected.sticky-right {\n background:\n linear-gradient(var(--tbw-column-selection-bg, rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0),\n var(--tbw-color-panel-bg);\n }\n\n /* ========== Touch selection mode (#304) ========== */\n\n /* Sticky action bar shown while touch selection mode is active. Rendered\n only on coarse-pointer devices, so the sizing targets a finger. */\n .tbw-selection-toolbar {\n position: sticky;\n top: 0;\n z-index: 30;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n padding: 4px 8px;\n background: var(--tbw-color-panel-bg);\n border-bottom: 1px solid var(--tbw-color-border);\n font-size: 13px;\n }\n\n .tbw-selection-toolbar-count {\n font-weight: 600;\n white-space: nowrap;\n }\n\n .tbw-selection-toolbar-actions {\n display: flex;\n align-items: center;\n gap: 4px;\n }\n\n /* `--tbw-touch-target-min` is owned by the touch-target sub-issue (#305);\n the literal fallback keeps this file readable on its own. */\n .tbw-selection-toolbar-btn {\n min-height: var(--tbw-touch-target-min, 24px);\n padding: 0 10px;\n border: 0;\n /* Themes set radii for much larger surfaces (Material uses 12px), which\n turns a 24px control into a lozenge. */\n border-radius: min(var(--tbw-border-radius, 4px), 6px);\n background: transparent;\n color: inherit;\n font: inherit;\n cursor: pointer;\n\n &:hover,\n &:focus-visible {\n background: var(--tbw-color-row-hover, light-dark(#f0f0f0, #2a2a2a));\n }\n\n &[data-action='done'] {\n font-weight: 600;\n color: var(--tbw-color-accent-text, var(--tbw-color-accent));\n }\n }\n\n /* Draggable corner dots on an active cell range (iOS Numbers idiom).\n Additive — a mouse user gets them too. The visible dot is smaller than\n the hit area, and `touch-action` is off because the drag runs on pointer\n capture. */\n .tbw-range-handle {\n position: absolute;\n z-index: 25;\n width: var(--tbw-touch-target-min, 24px);\n height: var(--tbw-touch-target-min, 24px);\n translate: -50% -50%;\n background: radial-gradient(circle, var(--tbw-color-accent) 0 5px, transparent 5px);\n cursor: crosshair;\n touch-action: none;\n\n &[hidden] {\n display: none;\n }\n\n &.dragging {\n scale: 1.3;\n }\n\n /* Tapped rather than dragged: the handle is waiting for the cell that\n will receive this corner (WCAG 2.2 SC 2.5.7). */\n &.armed {\n scale: 1.3;\n outline: 2px solid var(--tbw-color-accent);\n outline-offset: -4px;\n border-radius: 50%;\n }\n }\n }\n} /* End @layer tbw-plugins */\n","/**\n * Touch selection mode — long-press to enter, tap to toggle, tap \"Done\" to exit.\n *\n * This module owns the *presentation* half of the touch selection idiom\n * (#304): the selection-mode toolbar and the cell-range corner handles.\n * The state machine itself lives in `SelectionPlugin`, which drives these two\n * classes from its `afterRender()` hook.\n *\n * @module\n * @since 3.5.0\n */\n\nimport { startPointerDrag } from '../../core/internal/pointer-drag';\n\n// #region Types\n\n/**\n * What happens to the selection when touch selection mode is exited.\n *\n * - `'transient'` (default) — leaving selection mode clears the selection, the\n * Gmail / Google Photos behaviour. The mode *is* the selection.\n * - `'sticky'` — the selection survives, so a subsequent tap-to-toggle round\n * can start from what was already selected.\n *\n * @since 3.5.0\n */\nexport type TouchSelectionMode = 'sticky' | 'transient';\n\n/** Callbacks the toolbar invokes; all are supplied by `SelectionPlugin`. */\nexport interface SelectionToolbarCallbacks {\n /** \"Select all\" pressed. */\n selectAll(): void;\n /** \"Clear\" pressed. */\n clear(): void;\n /** \"Done\" pressed — exit selection mode. */\n done(): void;\n /** \"More…\" pressed. Receives the button so a menu can be anchored to it. */\n more(anchor: HTMLElement): void;\n}\n\n/** A normalized rectangle in (row, visible-column) space. */\nexport interface RangeRect {\n startRow: number;\n startCol: number;\n endRow: number;\n endCol: number;\n}\n\n/** Which corner of the range rectangle a handle controls. */\nexport type RangeCorner = 'start' | 'end';\n\n/** Callbacks the corner handles invoke while being dragged. */\nexport interface RangeHandleCallbacks {\n /** Resolve the cell under a viewport coordinate, or `null` if there is none. */\n cellAt(clientX: number, clientY: number): { row: number; col: number } | null;\n /** The dragged corner moved to a new cell. */\n resize(corner: RangeCorner, row: number, col: number): void;\n /** The drag finished (pointerup) or was aborted (Escape / pointercancel). */\n commit(): void;\n /**\n * The handle was pressed and released without moving — a tap, not a drag.\n * The non-dragging path required by WCAG 2.2 SC 2.5.7: the plugin arms this\n * corner and the next cell tap places it.\n */\n arm(corner: RangeCorner): void;\n}\n\n// #endregion\n\n// #region Selection-mode toolbar\n\n/** CSS class of the toolbar root. Also used by `selection.css`. */\nconst TOOLBAR_CLASS = 'tbw-selection-toolbar';\n\n/**\n * The sticky \"N selected · Select all · Clear · More… · Done\" bar shown while\n * touch selection mode is active.\n *\n * Mounted lazily on first {@link SelectionToolbar.show} and torn down by\n * {@link SelectionToolbar.destroy}. Buttons are `type=\"button\"` so the bar can\n * safely live inside a host form.\n */\nexport class SelectionToolbar {\n #root: HTMLElement | null = null;\n #count: HTMLElement | null = null;\n #more: HTMLButtonElement | null = null;\n #callbacks: SelectionToolbarCallbacks | null = null;\n\n /** True while the toolbar is in the DOM. */\n get mounted(): boolean {\n return this.#root !== null;\n }\n\n /** The toolbar root element, or `null` when not mounted. Test seam. */\n get element(): HTMLElement | null {\n return this.#root;\n }\n\n /**\n * Mount (if needed) and update the toolbar.\n *\n * @param container Element the toolbar is prepended to — normally `.tbw-grid-root`.\n * @param selectedCount Number of selected items, rendered as \"N selected\".\n * @param showMore Whether the \"More…\" overflow button is rendered. Only true\n * when a `ContextMenuPlugin` is registered, so touch users keep parity with\n * the right-click menu.\n */\n show(container: HTMLElement, selectedCount: number, showMore: boolean, callbacks: SelectionToolbarCallbacks): void {\n this.#callbacks = callbacks;\n if (!this.#root) this.#mount(container);\n if (this.#count) {\n this.#count.textContent = `${selectedCount} selected`;\n }\n this.#root?.setAttribute('data-selected-count', String(selectedCount));\n if (this.#more) this.#more.hidden = !showMore;\n }\n\n /** Remove the toolbar from the DOM. Safe to call when not mounted. */\n destroy(): void {\n this.#root?.remove();\n this.#root = null;\n this.#count = null;\n this.#more = null;\n this.#callbacks = null;\n }\n\n #mount(container: HTMLElement): void {\n const root = container.ownerDocument.createElement('div');\n root.className = TOOLBAR_CLASS;\n root.setAttribute('role', 'toolbar');\n root.setAttribute('aria-label', 'Selection');\n\n const count = container.ownerDocument.createElement('span');\n count.className = `${TOOLBAR_CLASS}-count`;\n count.setAttribute('aria-live', 'polite');\n root.appendChild(count);\n\n const actions = container.ownerDocument.createElement('div');\n actions.className = `${TOOLBAR_CLASS}-actions`;\n root.appendChild(actions);\n\n actions.appendChild(this.#button(container, 'select-all', 'Select all', () => this.#callbacks?.selectAll()));\n actions.appendChild(this.#button(container, 'clear', 'Clear', () => this.#callbacks?.clear()));\n const more = this.#button(container, 'more', 'More…', (btn) => this.#callbacks?.more(btn));\n more.setAttribute('aria-haspopup', 'menu');\n actions.appendChild(more);\n actions.appendChild(this.#button(container, 'done', 'Done', () => this.#callbacks?.done()));\n\n container.prepend(root);\n this.#root = root;\n this.#count = count;\n this.#more = more;\n }\n\n #button(\n container: HTMLElement,\n action: string,\n label: string,\n onClick: (btn: HTMLButtonElement) => void,\n ): HTMLButtonElement {\n const btn = container.ownerDocument.createElement('button');\n btn.type = 'button';\n btn.className = `${TOOLBAR_CLASS}-btn`;\n btn.dataset.action = action;\n btn.textContent = label;\n btn.addEventListener('click', (e) => {\n e.preventDefault();\n e.stopPropagation();\n onClick(btn);\n });\n return btn;\n }\n}\n\n// #endregion\n\n// #region Cell-range corner handles\n\n/** CSS class of a corner handle. Also used by `selection.css`. */\nconst HANDLE_CLASS = 'tbw-range-handle';\n\n/**\n * The two draggable dots at the top-left and bottom-right corners of an active\n * cell range (the iOS Numbers / Google Sheets idiom).\n *\n * They are additive rather than touch-only: a mouse user can drag them too.\n * Whether they are rendered at all is decided by `SelectionPlugin`, which only\n * asks for them when the range was started by a coarse pointer.\n * Positioning is recomputed on every render because the grid recycles row DOM\n * during virtualization, so a handle's anchor cell may not exist at all after\n * a scroll — in that case the handle is simply hidden.\n */\nexport class RangeCornerHandles {\n #start: HTMLElement | null = null;\n #end: HTMLElement | null = null;\n #callbacks: RangeHandleCallbacks | null = null;\n #armed: RangeCorner | null = null;\n\n /**\n * Render (or hide) the handles for `rect`.\n *\n * @param container Positioned ancestor the handles are absolutely placed in.\n * @param rect The normalized range, or `null` to hide the handles.\n * @param cellFor Resolves the DOM cell for a (row, col) pair, or `undefined`\n * when that cell is outside the rendered window.\n */\n render(\n container: HTMLElement,\n rect: RangeRect | null,\n cellFor: (row: number, col: number) => HTMLElement | null,\n callbacks: RangeHandleCallbacks,\n ): void {\n this.#callbacks = callbacks;\n if (!rect) {\n this.#hide();\n return;\n }\n\n this.#start ??= this.#createHandle(container, 'start');\n this.#end ??= this.#createHandle(container, 'end');\n\n this.#place(container, this.#start, cellFor(rect.startRow, rect.startCol), 'start');\n this.#place(container, this.#end, cellFor(rect.endRow, rect.endCol), 'end');\n this.setArmed(this.#armed);\n }\n\n /**\n * Mark one corner as waiting for the tap that will place it, or clear the\n * marking with `null`. Purely presentational — the plugin owns the state.\n */\n setArmed(corner: RangeCorner | null): void {\n this.#armed = corner;\n for (const [handle, name] of [\n [this.#start, 'start'],\n [this.#end, 'end'],\n ] as const) {\n if (!handle) continue;\n const on = corner === name;\n handle.classList.toggle('armed', on);\n handle.setAttribute('aria-pressed', String(on));\n }\n }\n\n /** Remove both handles from the DOM. Safe to call when not rendered. */\n destroy(): void {\n this.#start?.remove();\n this.#end?.remove();\n this.#start = null;\n this.#end = null;\n this.#callbacks = null;\n this.#armed = null;\n }\n\n #hide(): void {\n if (this.#start) this.#start.hidden = true;\n if (this.#end) this.#end.hidden = true;\n }\n\n #place(container: HTMLElement, handle: HTMLElement | null, cell: HTMLElement | null, corner: RangeCorner): void {\n if (!handle) return;\n if (!cell) {\n handle.hidden = true;\n return;\n }\n handle.hidden = false;\n // getBoundingClientRect is unavailable/zeroed in some test environments;\n // the handle still renders (and is assertable) with a zero offset.\n const cellRect = cell.getBoundingClientRect?.();\n const hostRect = container.getBoundingClientRect?.();\n if (!cellRect || !hostRect) return;\n const x = corner === 'start' ? cellRect.left - hostRect.left : cellRect.right - hostRect.left;\n const y = corner === 'start' ? cellRect.top - hostRect.top : cellRect.bottom - hostRect.top;\n handle.style.left = `${x}px`;\n handle.style.top = `${y}px`;\n }\n\n #createHandle(container: HTMLElement, corner: RangeCorner): HTMLElement {\n const el = container.ownerDocument.createElement('div');\n el.className = `${HANDLE_CLASS} ${HANDLE_CLASS}-${corner}`;\n el.dataset.corner = corner;\n // A real button, not decoration: it is tappable as well as draggable, so it\n // needs a name and a pressed state for the armed (tap-to-place) mode.\n el.setAttribute('role', 'button');\n el.setAttribute('tabindex', '-1');\n el.setAttribute('aria-pressed', 'false');\n el.setAttribute(\n 'aria-label',\n corner === 'start'\n ? 'Selection start corner — drag, or activate to place it with a tap'\n : 'Selection end corner — drag, or activate to place it with a tap',\n );\n el.addEventListener('pointerdown', (e) => this.#onPointerDown(e as PointerEvent, el, corner));\n container.appendChild(el);\n return el;\n }\n\n #onPointerDown(e: PointerEvent, handle: HTMLElement, corner: RangeCorner): void {\n if (e.button !== 0 && e.pointerType === 'mouse') return;\n e.preventDefault();\n e.stopPropagation();\n const callbacks = this.#callbacks;\n if (!callbacks) return;\n\n handle.classList.add('dragging');\n // `startPointerDrag` promotes immediately with these options, so `onMove`\n // firing at least once is the only reliable signal that this was a drag.\n let moved = false;\n const finish = (): void => {\n handle.classList.remove('dragging');\n callbacks.commit();\n };\n startPointerDrag(e, handle, {\n onMove: (moveEvent) => {\n moved = true;\n const target = callbacks.cellAt(moveEvent.clientX, moveEvent.clientY);\n if (target) callbacks.resize(corner, target.row, target.col);\n },\n onEnd: () => {\n handle.classList.remove('dragging');\n if (moved) callbacks.commit();\n else callbacks.arm(corner);\n },\n // An aborted drag still leaves the range wherever the last move put it,\n // so the plugin must re-render — but it is never a tap.\n onCancel: finish,\n });\n }\n}\n\n// #endregion\n","/**\n * Selection Plugin (Class-based)\n *\n * Provides selection functionality for tbw-grid.\n * Supports three modes:\n * - 'cell': Single cell selection (default). No border, just focus highlight.\n * - 'row': Row selection. Clicking a cell selects the entire row.\n * - 'range': Range selection. Shift+click or drag to select rectangular cell ranges.\n */\n\nimport { GridClasses } from '../../core/constants';\nimport { announce, getA11yMessage } from '../../core/internal/aria';\nimport { getPrimaryPointer } from '../../core/internal/pointer-modality';\nimport { clearCellFocus, getRowIndexFromCell } from '../../core/internal/utils';\nimport type { GridElement, HeaderClickEvent, PluginManifest, PluginQuery } from '../../core/plugin/base-plugin';\nimport { BaseGridPlugin, CellClickEvent, CellMouseEvent } from '../../core/plugin/base-plugin';\nimport { isExpanderColumn, isUtilityColumn } from '../../core/plugin/expander-column';\nimport type { ColumnConfig } from '../../core/types';\nimport type { ContextMenuParams, HeaderContextMenuItem } from '../context-menu/types';\nimport {\n createDragAlternativeMenu,\n type DragAlternativeAction,\n type DragAlternativeMenu,\n} from '../shared/drag-alternative-menu';\nimport { isFormFieldKeyTarget } from '../shared/form-field-target';\nimport {\n computeKeyboardExtension,\n fieldsBetween,\n normalizeMode,\n selectableColumnFields,\n type NormalizedModeConfig,\n} from './column-selection';\nimport {\n createRangeFromAnchor,\n getAllCellsInRanges,\n isCellInAnyRange,\n normalizeRange,\n rangesEqual,\n toPublicRanges,\n} from './range-selection';\nimport styles from './selection.css?inline';\nimport { RangeCornerHandles, SelectionToolbar, type RangeCorner, type RangeRect } from './touch-selection';\nimport type {\n CellRange,\n InternalCellRange,\n SelectionAxis,\n SelectionChangeDetail,\n SelectionConfig,\n SelectionMode,\n SelectionResult,\n} from './types';\n\n/**\n * Resolve the primary in-row mode from a config that may be a single string\n * or an array. Used by `configRules` (which run before `attach()` populates\n * the cached normalized mode). Falls back to `'cell'` on invalid input —\n * `attach()` will throw the proper error message later.\n */\nfunction primaryModeOf(mode: SelectionMode | SelectionMode[] | undefined): SelectionMode {\n if (typeof mode === 'string') return mode;\n if (Array.isArray(mode)) {\n const other = mode.find((m) => m !== 'column');\n if (other) return other;\n if (mode.includes('column')) return 'column';\n }\n return 'cell';\n}\n\n/** Special field name for the selection checkbox column */\nconst CHECKBOX_COLUMN_FIELD = '__tbw_checkbox';\n\n/**\n * Order band for the range-extension item contributed to the context menu.\n * `insertGroupSeparators` groups by the tens digit, so 60 keeps it in its own\n * group below column move (50-53).\n */\nconst EXTEND_ITEM_ORDER = 60;\n\n/** Keys that move grid focus — selection reacts to these in cell/range mode. */\nconst NAV_KEYS: readonly string[] = [\n 'ArrowUp',\n 'ArrowDown',\n 'ArrowLeft',\n 'ArrowRight',\n 'Tab',\n 'Home',\n 'End',\n 'PageUp',\n 'PageDown',\n];\n\n/**\n * Build the selection change event detail for the current state.\n *\n * `axis` decides which axis \"won\" — when both row and column are populated\n * (which can only happen in transient states inside mutual-exclusion handling),\n * `axis` is the source of truth for which one to report.\n */\nfunction buildSelectionEvent(\n configuredMode: SelectionMode | SelectionMode[],\n axis: SelectionAxis,\n primary: SelectionMode,\n state: {\n selectedCell: { row: number; col: number } | null;\n selected: Set<number>;\n ranges: InternalCellRange[];\n selectedColumns: Set<string>;\n },\n colCount: number,\n visibleColumnFieldsInOrder: readonly string[],\n): SelectionChangeDetail {\n // Column axis active → ignore in-row state, report column field names in\n // visible-column order. WHY: `Set` insertion order reflects toggle history\n // (so the same selection emits different orderings depending on how the\n // user reached it), which makes `selection-change.detail.selectedColumns`\n // non-deterministic for consumers. Filtering the visible field list keeps\n // the event detail stable and consistent with `getSelectedColumns()`.\n if (axis === 'column' && state.selectedColumns.size > 0) {\n return {\n mode: configuredMode,\n activeAxis: 'column',\n ranges: [],\n selectedColumns: visibleColumnFieldsInOrder.filter((f) => state.selectedColumns.has(f)),\n };\n }\n\n if (primary === 'cell' && state.selectedCell) {\n return {\n mode: configuredMode,\n activeAxis: 'cell',\n ranges: [\n {\n from: { row: state.selectedCell.row, col: state.selectedCell.col },\n to: { row: state.selectedCell.row, col: state.selectedCell.col },\n },\n ],\n selectedColumns: [],\n };\n }\n\n if (primary === 'row' && state.selected.size > 0) {\n // Sort rows and merge contiguous indices into minimal ranges\n const sorted = [...state.selected].sort((a, b) => a - b);\n const ranges: CellRange[] = [];\n let start = sorted[0];\n let end = start;\n for (let i = 1; i < sorted.length; i++) {\n if (sorted[i] === end + 1) {\n end = sorted[i];\n } else {\n ranges.push({ from: { row: start, col: 0 }, to: { row: end, col: colCount - 1 } });\n start = sorted[i];\n end = start;\n }\n }\n ranges.push({ from: { row: start, col: 0 }, to: { row: end, col: colCount - 1 } });\n return { mode: configuredMode, activeAxis: 'row', ranges, selectedColumns: [] };\n }\n\n if (primary === 'range' && state.ranges.length > 0) {\n return {\n mode: configuredMode,\n activeAxis: 'range',\n ranges: toPublicRanges(state.ranges),\n selectedColumns: [],\n };\n }\n\n return { mode: configuredMode, activeAxis: 'none', ranges: [], selectedColumns: [] };\n}\n\n/**\n * Selection Plugin for tbw-grid\n *\n * Adds cell, row, and range selection capabilities to the grid with full keyboard support.\n * Whether you need simple cell highlighting or complex multi-range selections, this plugin has you covered.\n *\n * ## Installation\n *\n * ```ts\n * import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';\n * ```\n *\n * ## Selection Modes\n *\n * Configure the plugin with one of three modes via {@link SelectionConfig}:\n *\n * - **`'cell'`** - Single cell selection (default). Click cells to select individually.\n * - **`'row'`** - Full row selection. Click anywhere in a row to select the entire row.\n * - **`'range'`** - Rectangular selection. Click and drag or Shift+Click to select ranges.\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Arrow Keys` | Move selection |\n * | `Shift + Arrow` | Extend selection (range mode) |\n * | `Ctrl/Cmd + Click` | Toggle selection (multi-select) |\n * | `Shift + Click` | Extend to clicked cell/row |\n * | `Ctrl/Cmd + A` | Select all (range mode) |\n * | `Escape` | Clear selection |\n *\n * > **Note:** When `multiSelect: false`, Ctrl/Shift modifiers are ignored —\n * > clicks always select a single item.\n *\n * ## CSS Custom Properties\n *\n * | Property | Description |\n * |----------|-------------|\n * | `--tbw-focus-background` | Focused row background |\n * | `--tbw-range-selection-bg` | Range selection fill |\n * | `--tbw-range-border-color` | Range selection border |\n *\n * @example Basic row selection\n * ```ts\n * grid.gridConfig = {\n * columns: [...],\n * plugins: [new SelectionPlugin({ mode: 'row' })],\n * };\n * ```\n *\n * @example Range selection with event handling\n * ```ts\n * grid.gridConfig = {\n * plugins: [new SelectionPlugin({ mode: 'range' })],\n * };\n *\n * grid.on('selection-change', ({ mode, ranges }) => {\n * console.log(`Selected ${ranges.length} ranges in ${mode} mode`);\n * });\n * ```\n *\n * @example Programmatic selection control\n * ```ts\n * const plugin = grid.getPluginByName('selection');\n *\n * // Get current selection\n * const selection = plugin.getSelection();\n * console.log(selection.ranges);\n *\n * // Set selection programmatically\n * plugin.setRanges([{ from: { row: 0, col: 0 }, to: { row: 5, col: 3 } }]);\n *\n * // Clear all selection\n * plugin.clearSelection();\n * ```\n *\n * @see {@link SelectionMode} for detailed mode descriptions\n * @see {@link SelectionConfig} for configuration options\n * @see {@link SelectionResult} for the selection result structure\n * @see {@link SelectionConfig} for interactive examples in the docs site\n * @since 0.1.1\n */\nexport class SelectionPlugin extends BaseGridPlugin<SelectionConfig> {\n /**\n * Plugin manifest - declares queries and configuration validation rules.\n * @internal\n */\n static override readonly manifest: PluginManifest<SelectionConfig> = {\n hookPriority: {\n // Inject the checkbox before pinned-columns reorders and applies sticky offsets.\n processColumns: -20,\n },\n queries: [\n { type: 'getSelection', description: 'Get the current selection state' },\n { type: 'selectRows', description: 'Select specific rows by index (row mode only)' },\n {\n type: 'getSelectedRowIndices',\n description: 'Get sorted array of row indices touched by the current selection (works in all modes)',\n },\n { type: 'getSelectedRows', description: 'Get actual row objects for the current selection (works in all modes)' },\n { type: 'getSelectedColumns', description: 'Get field names of selected columns (column mode only)' },\n { type: 'selectColumns', description: 'Select specific columns by field name (column mode only)' },\n {\n type: 'selectContextMenuTarget',\n description:\n 'Move the selection to the cell a context menu was invoked on unless it is already selected; returns getSelectedRowIndices()',\n },\n {\n type: 'getContextMenuItems',\n description: 'Contribute the non-dragging range-extension action (WCAG 2.2 SC 2.5.7)',\n },\n ],\n configRules: [\n {\n id: 'selection/range-dblclick',\n severity: 'warn',\n message:\n `\"triggerOn: 'dblclick'\" has no effect when mode is \"range\".\\n` +\n ` → Range selection uses drag interaction (mousedown → mousemove), not click events.\\n` +\n ` → The \"triggerOn\" option only affects \"cell\" and \"row\" selection modes.`,\n check: (config) => primaryModeOf(config.mode) === 'range' && config.triggerOn === 'dblclick',\n },\n {\n id: 'selection/column-checkbox',\n severity: 'warn',\n message:\n `\"checkbox: true\" only renders in row mode.\\n` +\n ` → Column selection has no checkbox UI; activate columns via Ctrl+Click on a header or Ctrl+Space on a focused cell.`,\n check: (config) => !!config.checkbox && primaryModeOf(config.mode) !== 'row',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'selection';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<SelectionConfig> {\n return {\n mode: 'cell',\n triggerOn: 'click',\n enabled: true,\n multiSelect: true,\n touchMode: 'transient',\n };\n }\n\n // #region Touch Selection State (#304)\n\n /**\n * True while touch selection mode is active — long-press entered it, plain\n * taps now toggle instead of replacing, and the selection toolbar is shown.\n *\n * Read-only for consumers; drive it with {@link exitTouchSelection}.\n *\n * @since 3.5.0\n */\n get touchSelectionActive(): boolean {\n return this.#touchActive;\n }\n\n #touchActive = false;\n /**\n * Whether the *current* range was started by a finger/stylus. Gates the\n * corner handles: on desktop they would sit inside other ranges (multi-range\n * is mouse-only) and get in the way of normal drag-selection.\n */\n #rangeFromCoarsePointer = false;\n readonly #toolbar = new SelectionToolbar();\n readonly #cornerHandles = new RangeCornerHandles();\n\n // #endregion\n\n // #region Non-dragging range alternatives (WCAG 2.2 SC 2.5.7)\n\n /** Corner waiting for the tap that will place it, set by tapping its handle. */\n #armedCorner: RangeCorner | null = null;\n /**\n * Last cell the user deliberately anchored with a *primary* interaction.\n * Kept separate from {@link cellAnchor} because opening a context menu outside\n * the range re-anchors that one so the menu targets the invoked cell (see\n * `#selectContextMenuTarget`) — which would leave \"Extend selection to here\"\n * with nothing to extend from.\n */\n #extendAnchor: { row: number; col: number } | null = null;\n #extendMenu: DragAlternativeMenu | null = null;\n\n // #endregion\n\n // #region Internal State\n /** Row selection state (row mode) */\n private selected = new Set<number>();\n private lastSelected: number | null = null;\n private anchor: number | null = null;\n\n /** Range selection state (range mode) */\n private ranges: InternalCellRange[] = [];\n private activeRange: InternalCellRange | null = null;\n private cellAnchor: { row: number; col: number } | null = null;\n private isDragging = false;\n\n /** Pending keyboard navigation update (processed in afterRender) */\n private pendingKeyboardUpdate: { shiftKey: boolean } | null = null;\n\n /** Pending row-mode keyboard update (processed in afterRender) */\n private pendingRowKeyUpdate: { shiftKey: boolean } | null = null;\n\n /** Cell selection state (cell mode) */\n private selectedCell: { row: number; col: number } | null = null;\n\n /**\n * Column selection state (column mode / `['row','column']` array mode).\n * Stored as field-name strings so selection survives column pinning,\n * reordering, and virtualization recycling.\n */\n private selectedColumns = new Set<string>();\n /** Anchor column for Ctrl+Shift+click range extension. */\n private columnAnchor: string | null = null;\n /** Head column for Ctrl+Shift+Arrow keyboard extension. */\n private columnHead: string | null = null;\n /** Which axis last won. Drives `SelectionChangeDetail.activeAxis` and mutual exclusion. */\n private activeAxis: SelectionAxis = 'none';\n\n /**\n * Normalized mode config, computed once in `attach()`. All mode checks in this\n * plugin go through `this.#mode` rather than `this.config.mode` so the\n * single-string vs. array distinction is resolved in exactly one place.\n */\n #mode: NormalizedModeConfig = { primary: 'cell', columnEnabled: false, bothAxes: false };\n\n /** Last synced focus row — used to detect when grid focus moves so selection follows */\n private lastSyncedFocusRow = -1;\n /** Last synced focus col (cell mode) */\n private lastSyncedFocusCol = -1;\n\n /** Debounce timer for selection announcements */\n private announceTimer: ReturnType<typeof setTimeout> | null = null;\n /** Set by Shift/Ctrl+Space so the next announcement names the rows/columns selected. */\n #pendingSpanAnnouncement: { axis: 'row' | 'column'; count: number } | null = null;\n /** Range built by Shift/Ctrl+Space; Shift+Arrow keeps its spanned axis full while it is still `activeRange`. */\n #spanRange: { axis: 'row' | 'column'; range: InternalCellRange } | null = null;\n\n /** True when selection was explicitly set (click/keyboard) — prevents #syncSelectionToFocus from overwriting */\n private explicitSelection = false;\n\n // #endregion\n\n // #region Private Helpers - Selection Enabled Check\n\n /**\n * Check if selection is enabled at the grid level.\n * Grid-wide `selectable: false` or plugin's `enabled: false` disables all selection.\n */\n private isSelectionEnabled(): boolean {\n // Check plugin config first\n if (this.config.enabled === false) return false;\n // Check grid-level config\n return this.grid.effectiveConfig?.selectable !== false;\n }\n\n // #endregion\n\n // #region Private Helpers - Selectability\n\n /**\n * Check if a row/cell is selectable.\n * Returns true if selectable, false if not.\n */\n private checkSelectable(rowIndex: number, colIndex?: number): boolean {\n const { isSelectable } = this.config;\n if (!isSelectable) return true; // No callback = all selectable\n\n const row = this.rows[rowIndex];\n if (!row) return false;\n\n // colIndex is a visible-column index (from data-col), so use visibleColumns\n const column = colIndex !== undefined ? this.visibleColumns[colIndex] : undefined;\n return isSelectable(row, rowIndex, column, colIndex);\n }\n\n /**\n * Check if an entire row is selectable (for row mode).\n */\n private isRowSelectable(rowIndex: number): boolean {\n return this.checkSelectable(rowIndex);\n }\n\n /**\n * Check if a cell is selectable (for cell/range modes).\n */\n private isCellSelectable(rowIndex: number, colIndex: number): boolean {\n return this.checkSelectable(rowIndex, colIndex);\n }\n\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Resolve the user-supplied mode (string OR array) into a single normalized\n // shape. Throws on invalid combinations (e.g. ['row', 'cell']).\n this.#mode = normalizeMode(this.config.mode);\n\n // Subscribe to events that invalidate selection\n // When rows change due to filtering/grouping/tree/sort operations, selection indices become invalid\n this.on('filter-change', () => this.clearSelectionSilent());\n this.on('group-toggle', () => this.clearSelectionSilent());\n this.on('tree-expand', () => this.clearSelectionSilent());\n this.on('sort-change', () => this.clearSelectionSilent());\n\n // Auto-select the row currently being edited so consumers of getSelectedRows()\n // / selectedRows() always see the row the user is actually working with.\n // Issue #284: editing and selection were independent, so a row could be in\n // edit mode while selectedRows() returned a stale (or different) row.\n // Only meaningful in row mode — cell mode tracks single-cell focus, range\n // mode is for bulk selection. We listen to `edit-open` (broadcast by\n // EditingPlugin) — `edit-close` is intentionally ignored so existing\n // selections are preserved when the user finishes editing.\n this.on<{ rowIndex: number; row: unknown }>('edit-open', ({ rowIndex, row }) => {\n if (!this.isSelectionEnabled()) return;\n if (row == null || rowIndex < 0) return;\n if (this.#mode.primary !== 'row') return;\n if (!this.isRowSelectable(rowIndex)) return;\n if (this.selected.has(rowIndex)) return;\n // multiSelect: false → replace; otherwise add to existing set so\n // multi-selection is preserved when the user enters edit on one row.\n if (this.config.multiSelect === false) {\n this.selected.clear();\n }\n this.selected.add(rowIndex);\n this.lastSelected = rowIndex;\n this.anchor = rowIndex;\n this.explicitSelection = true;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n });\n\n // Source-row collection replaced from outside (host swapped `[rows]`).\n // `data-change` also fires for in-place cell edits, so gate on sourceRowCount\n // changing — the only signal that the source collection actually grew/shrank.\n // Without this, stored row indices resolve against a different array and\n // getSelectedRows() silently returns the wrong rows.\n let lastSourceRowCount = -1;\n grid.addEventListener(\n 'data-change',\n ((event: CustomEvent<{ sourceRowCount: number }>) => {\n const { sourceRowCount } = event.detail;\n const hasSelection = this.selected.size > 0 || this.ranges.length > 0 || this.selectedCell !== null;\n if (lastSourceRowCount !== -1 && sourceRowCount !== lastSourceRowCount && hasSelection) {\n this.clearSelectionSilent();\n }\n lastSourceRowCount = sourceRowCount;\n }) as EventListener,\n { signal: this.disconnectSignal },\n );\n\n // SC 2.5.7 fallback: without a ContextMenuPlugin there is no menu to\n // contribute \"Extend selection to here\" to, so host a bare one. Delegated\n // rather than per-cell — cells are recycled on every render.\n grid.addEventListener(\n 'contextmenu',\n ((event: MouseEvent) => {\n if (this.#contextMenuPlugin()) return; // the real menu owns this gesture\n const cell = (event.target as Element | null)?.closest?.<HTMLElement>('.cell[data-row][data-col]');\n if (!cell) return;\n const row = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const col = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n const actions = this.#extendActions(row, col);\n if (!actions) return;\n event.preventDefault();\n this.#openExtendMenu(cell, actions);\n }) as EventListener,\n { signal: this.disconnectSignal },\n );\n }\n\n /**\n * Handle queries from other plugins.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'getSelection') {\n return this.getSelection();\n }\n if (query.type === 'getSelectedRowIndices') {\n return this.getSelectedRowIndices();\n }\n if (query.type === 'getSelectedRows') {\n return this.getSelectedRows();\n }\n if (query.type === 'selectRows') {\n this.selectRows(query.context as number[]);\n return true;\n }\n if (query.type === 'getSelectedColumns') {\n return this.getSelectedColumns();\n }\n if (query.type === 'selectColumns') {\n const fields = query.context as string[];\n this.#setColumnSelection(fields);\n return true;\n }\n if (query.type === 'selectContextMenuTarget') {\n const { rowIndex, colIndex } = query.context as { rowIndex: number; colIndex: number };\n this.#selectContextMenuTarget(rowIndex, colIndex);\n return this.getSelectedRowIndices();\n }\n if (query.type === 'getContextMenuItems') {\n const params = query.context as ContextMenuParams | undefined;\n if (!params || params.isHeader) return undefined;\n const actions = this.#extendActions(params.rowIndex, params.columnIndex);\n if (!actions) return undefined;\n return actions.map((action, i): HeaderContextMenuItem => ({\n id: `selection-extend-${i}`,\n label: action.label,\n disabled: action.disabled,\n action: () => action.run(),\n order: EXTEND_ITEM_ORDER + i,\n }));\n }\n return undefined;\n }\n\n /** @internal */\n override detach(): void {\n // Clear aria-multiselectable that we set on the role=grid element.\n // Other lifecycle teardown happens below.\n const rowsBodyEl = this.gridElement?.querySelector('.rows-body');\n rowsBodyEl?.removeAttribute('aria-multiselectable');\n\n this.#toolbar.destroy();\n this.#cornerHandles.destroy();\n this.#extendMenu?.dispose();\n this.#extendMenu = null;\n this.#armedCorner = null;\n this.#extendAnchor = null;\n this.#touchActive = false;\n\n this.selected.clear();\n this.ranges = [];\n this.activeRange = null;\n this.cellAnchor = null;\n this.isDragging = false;\n this.selectedCell = null;\n this.selectedColumns.clear();\n this.columnAnchor = null;\n this.columnHead = null;\n this.activeAxis = 'none';\n this.pendingKeyboardUpdate = null;\n this.pendingRowKeyUpdate = null;\n this.lastSyncedFocusRow = -1;\n this.lastSyncedFocusCol = -1;\n // Cancel the debounced screen-reader announcement so it can't fire after\n // teardown (the callback reaches `announce()` → `requestAnimationFrame`,\n // which is undefined once the host/DOM env is gone — surfaces as an\n // \"Unhandled Error: requestAnimationFrame is not defined\" in tests).\n if (this.announceTimer) {\n clearTimeout(this.announceTimer);\n this.announceTimer = null;\n }\n }\n\n /**\n * Clear selection without emitting an event.\n * Used when selection is invalidated by external changes (filtering, grouping, etc.)\n *\n * Column selection is intentionally PRESERVED here — it tracks field names,\n * not row indices, so it stays valid across filter/sort/group changes. Use\n * {@link clearSelection} (public) or {@link #clearAllAxesSilent} for a full wipe.\n */\n private clearSelectionSilent(): void {\n this.selected.clear();\n this.ranges = [];\n this.activeRange = null;\n this.cellAnchor = null;\n this.selectedCell = null;\n this.lastSelected = null;\n this.anchor = null;\n this.lastSyncedFocusRow = -1;\n this.lastSyncedFocusCol = -1;\n if (this.activeAxis !== 'column') {\n this.activeAxis = 'none';\n }\n this.requestAfterRender();\n }\n\n // #endregion\n\n // #region Touch Selection Mode (#304)\n\n /**\n * True when a press originated from a finger or stylus.\n *\n * Prefers the per-event `pointerType` over the `(pointer: coarse)` media\n * query so that a hybrid device (e.g. a Surface with both a touchscreen and\n * a mouse) keeps mouse chords working while touch gets the long-press idiom.\n */\n #isCoarseEvent(e: MouseEvent): boolean {\n const pointerType = (e as PointerEvent).pointerType;\n if (pointerType === 'touch' || pointerType === 'pen') return true;\n if (pointerType === 'mouse') return false;\n return getPrimaryPointer() === 'coarse';\n }\n\n /**\n * Enter touch selection mode, seeding it with `rowIndex`.\n *\n * Long-pressing a row while already in the mode range-extends from the\n * anchor instead — that branch is handled by the caller.\n */\n #enterTouchSelection(rowIndex: number): boolean {\n if (!this.isRowSelectable(rowIndex)) return false;\n this.#touchActive = true;\n this.selected.clear();\n this.selected.add(rowIndex);\n this.anchor = rowIndex;\n this.lastSelected = rowIndex;\n this.explicitSelection = true;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return true;\n }\n\n /**\n * Leave touch selection mode.\n *\n * With the default `touchMode: 'transient'` this also clears the selection —\n * the mode *is* the selection, as in Gmail. With `touchMode: 'sticky'` the\n * selection survives so a later round can build on it.\n *\n * No-op when the mode is not active.\n *\n * @since 3.5.0\n */\n exitTouchSelection(): void {\n if (!this.#touchActive) return;\n this.#touchActive = false;\n if ((this.config.touchMode ?? 'transient') === 'transient') {\n this.selected.clear();\n this.anchor = null;\n this.lastSelected = null;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n }\n this.requestAfterRender();\n }\n\n /** Range-extend from the touch anchor to `rowIndex` (second long-press). */\n #extendTouchSelection(rowIndex: number): void {\n const anchor = this.anchor ?? rowIndex;\n const start = Math.min(anchor, rowIndex);\n const end = Math.max(anchor, rowIndex);\n for (let i = start; i <= end; i++) {\n if (this.isRowSelectable(i)) this.selected.add(i);\n }\n this.lastSelected = rowIndex;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /** The `ContextMenuPlugin` instance, when one is registered. */\n #contextMenuPlugin(): { showMenu(x: number, y: number, params: Record<string, unknown>): void } | undefined {\n const plugin = this.grid?.getPluginByName?.('contextMenu') ?? this.grid?.getPluginByName?.('context-menu');\n const candidate = plugin as { showMenu?: unknown } | undefined;\n return typeof candidate?.showMenu === 'function'\n ? (candidate as { showMenu(x: number, y: number, params: Record<string, unknown>): void })\n : undefined;\n }\n\n /** Resolve the rendered cell element for a (row, visible-col) pair. */\n #cellFor(row: number, col: number): HTMLElement | null {\n return this.gridElement?.querySelector<HTMLElement>(`.cell[data-row=\"${row}\"][data-col=\"${col}\"]`) ?? null;\n }\n\n /** Resolve the (row, col) of the cell under a viewport coordinate. */\n #cellAtPoint(clientX: number, clientY: number): { row: number; col: number } | null {\n const host = this.gridElement;\n const doc = host?.ownerDocument;\n const el = doc?.elementFromPoint?.(clientX, clientY);\n const cell = (el as Element | null)?.closest?.('.cell[data-row][data-col]');\n // `elementFromPoint` is document-wide: when several grids share a page the\n // drag can wander over a *different* grid's cells. Only accept cells that\n // belong to this grid instance.\n if (!cell || !host?.contains?.(cell)) return null;\n const row = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const col = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n return row >= 0 && col >= 0 ? { row, col } : null;\n }\n\n /** Move one corner of the active range while its handle is dragged. */\n #resizeRangeCorner(corner: RangeCorner, row: number, col: number): void {\n const current = this.ranges[this.ranges.length - 1];\n if (!current) return;\n const normalized = normalizeRange(current);\n const anchor =\n corner === 'start'\n ? { row: normalized.endRow, col: normalized.endCol }\n : { row: normalized.startRow, col: normalized.startCol };\n const next = createRangeFromAnchor(anchor, { row, col });\n if (rangesEqual(current, next)) return;\n this.ranges[this.ranges.length - 1] = next;\n this.activeRange = next;\n this.cellAnchor = anchor;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n // #endregion\n // #region Non-dragging range alternatives (WCAG 2.2 SC 2.5.7)\n\n /**\n * The single-pointer alternative to paint-dragging a range: click the first\n * cell as usual, then open the context menu on the opposite corner and pick\n * \"Extend selection to here\".\n *\n * Returns `null` — not an empty array — when the action does not apply, so\n * the plugin contributes nothing rather than a dead entry.\n */\n #extendActions(rowIndex: number, colIndex: number): DragAlternativeAction[] | null {\n if (this.#mode.primary !== 'range') return null;\n if (!this.isSelectionEnabled()) return null;\n if (rowIndex < 0 || colIndex < 0) return null;\n if (!this.isCellSelectable(rowIndex, colIndex)) return null;\n const anchor = this.#extendAnchor;\n if (!anchor) return null;\n if (anchor.row === rowIndex && anchor.col === colIndex) return null;\n return [\n {\n label: 'Extend selection to here',\n run: () => this.#extendSelectionTo(rowIndex, colIndex),\n },\n ];\n }\n\n /** Replace the active range with the rectangle from {@link #extendAnchor} to (row, col). */\n #extendSelectionTo(row: number, col: number): void {\n const anchor = this.#extendAnchor;\n if (!anchor) return;\n const next = createRangeFromAnchor(anchor, { row, col });\n this.ranges = [next];\n this.activeRange = next;\n this.cellAnchor = anchor;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Fallback menu for when no `ContextMenuPlugin` is registered. The alternative\n * to a drag must exist whether or not an optional plugin is installed, so the\n * shared bare menu stands in — but it must never stack on top of the real one.\n */\n #openExtendMenu(anchor: HTMLElement, actions: DragAlternativeAction[]): void {\n this.#extendMenu ??= createDragAlternativeMenu('tbw-range-extend-menu', 'tbw-range-extend-menu');\n this.#extendMenu.open(anchor, 'Selection', actions);\n }\n\n /**\n * Arm (or disarm) a range corner after its handle was tapped rather than\n * dragged. The next cell click places the corner.\n */\n #armRangeCorner(corner: RangeCorner): void {\n this.#armedCorner = this.#armedCorner === corner ? null : corner;\n this.#cornerHandles.setArmed(this.#armedCorner);\n if (this.gridElement) {\n announce(\n this.gridElement,\n this.#armedCorner ? 'Select a cell to place the selection corner' : 'Selection corner placement cancelled',\n );\n }\n }\n\n /** Clear any armed corner. Returns `true` when something was actually cleared. */\n #disarmRangeCorner(): boolean {\n if (!this.#armedCorner) return false;\n this.#armedCorner = null;\n this.#cornerHandles.setArmed(null);\n return true;\n }\n\n // #endregion\n // #region Touch chrome\n\n /**\n * Render (or tear down) the touch chrome: the selection-mode toolbar and the\n * range corner handles. Called from `afterRender()`.\n *\n * The toolbar follows `#touchActive`, which can only have been set by a\n * coarse-pointer long-press — the modality check happens once, per event, at\n * entry. Re-testing the `(pointer: coarse)` media query here would break\n * hybrid devices (a Surface reports a fine primary pointer even while the\n * user is touching the screen). The corner handles follow the same rule via\n * `#rangeFromCoarsePointer`: they exist because touch has no Shift/Ctrl, so a\n * mouse-started range never gets them.\n */\n #renderTouchChrome(container: HTMLElement | null): void {\n if (!container) return;\n\n if (this.#touchActive) {\n this.#toolbar.show(container, this.selected.size, this.#contextMenuPlugin() !== undefined, {\n selectAll: () => this.selectAll(),\n clear: () => this.clearSelection(),\n done: () => this.exitTouchSelection(),\n more: (btn) => this.#openOverflowMenu(btn),\n });\n } else {\n this.#toolbar.destroy();\n }\n\n const active =\n this.#rangeFromCoarsePointer && this.#mode.primary === 'range' && this.ranges.length > 0\n ? this.ranges[this.ranges.length - 1]\n : null;\n const rect: RangeRect | null = active ? normalizeRange(active) : null;\n if (!rect) this.#disarmRangeCorner();\n this.#cornerHandles.render(container, rect, (row, col) => this.#cellFor(row, col), {\n cellAt: (x, y) => this.#cellAtPoint(x, y),\n resize: (corner, row, col) => this.#resizeRangeCorner(corner, row, col),\n commit: () => this.requestAfterRender(),\n arm: (corner) => this.#armRangeCorner(corner),\n });\n }\n\n /**\n * Surface the `ContextMenuPlugin` items from the toolbar's \"More…\" button, so\n * touch users don't lose the actions a mouse user reaches by right-clicking.\n */\n #openOverflowMenu(anchorEl: HTMLElement): void {\n const menu = this.#contextMenuPlugin();\n if (!menu) return;\n const rect = anchorEl.getBoundingClientRect?.();\n const rowIndex = this.lastSelected ?? -1;\n menu.showMenu(rect?.left ?? 0, rect?.bottom ?? 0, {\n row: rowIndex >= 0 ? this.rows[rowIndex] : null,\n rowIndex,\n // ContextMenuParams.selectedRows is a list of row *indices*, not row objects.\n selectedRows: this.getSelectedRowIndices(),\n });\n }\n\n // #endregion\n // #region Event Handlers\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean {\n // Skip all selection if disabled at grid level or plugin level\n if (!this.isSelectionEnabled()) return false;\n\n // Skip if event type doesn't match configured trigger.\n // This allows dblclick mode to only select on double-click.\n const { triggerOn = 'click' } = this.config;\n if (event.originalEvent.type !== triggerOn) return false;\n\n switch (this.#mode.primary) {\n case 'cell':\n return this.#clickSelectCell(event);\n case 'row':\n return this.#clickSelectRow(event);\n case 'range':\n return this.#clickSelectRange(event);\n default:\n return false;\n }\n }\n\n /**\n * CELL MODE: single-cell selection. Skips utility columns and non-selectable\n * cells, and only emits when the selection actually changed.\n */\n #clickSelectCell(event: CellClickEvent): boolean {\n const { rowIndex, colIndex } = event;\n\n // Check if this is a utility column (expander columns, etc.)\n // event.column is already resolved from _visibleColumns in the event builder.\n // Allow the event to propagate, but don't select utility cells.\n if (event.column && isUtilityColumn(event.column)) return false;\n if (!this.isCellSelectable(rowIndex, colIndex)) return false;\n\n const currentCell = this.selectedCell;\n // Same cell already selected\n if (currentCell && currentCell.row === rowIndex && currentCell.col === colIndex) return false;\n\n this.selectedCell = { row: rowIndex, col: colIndex };\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return false;\n }\n\n /** ROW MODE: multi-select with Shift/Ctrl, checkbox toggle, or single select. */\n #clickSelectRow(event: CellClickEvent): boolean {\n const { rowIndex, originalEvent, column } = event;\n if (!this.isRowSelectable(rowIndex)) return false;\n\n const multiSelect = this.config.multiSelect !== false;\n const shiftKey = originalEvent.shiftKey && multiSelect;\n // While touch selection mode is active a plain tap toggles, exactly as if\n // Ctrl were held — that is the whole point of the mode. Mouse chords are\n // untouched, so a hybrid device supports both at once.\n const ctrlKey = (originalEvent.ctrlKey || originalEvent.metaKey || this.#touchActive) && multiSelect;\n const isCheckbox = column?.checkboxColumn === true;\n\n if (shiftKey && this.anchor !== null) {\n // Shift+Click: Range select from anchor to clicked row\n const start = Math.min(this.anchor, rowIndex);\n const end = Math.max(this.anchor, rowIndex);\n if (!ctrlKey) this.selected.clear();\n for (let i = start; i <= end; i++) {\n if (this.isRowSelectable(i)) this.selected.add(i);\n }\n } else if (ctrlKey || (isCheckbox && multiSelect)) {\n // Ctrl+Click or checkbox click: Toggle individual row\n if (this.selected.has(rowIndex)) this.selected.delete(rowIndex);\n else this.selected.add(rowIndex);\n this.anchor = rowIndex;\n } else {\n // Plain click (or any click when multiSelect is false): select only clicked row.\n // Same row already selected → nothing to do.\n if (this.selected.size === 1 && this.selected.has(rowIndex)) return false;\n this.selected.clear();\n this.selected.add(rowIndex);\n this.anchor = rowIndex;\n }\n\n this.lastSelected = rowIndex;\n this.explicitSelection = true;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return false;\n }\n\n /** RANGE MODE: Shift+click extends the selection, plain click starts a new one. */\n #clickSelectRange(event: CellClickEvent): boolean {\n const { rowIndex, colIndex, originalEvent } = event;\n\n // Skip utility columns and non-selectable cells - don't start selection from them\n if (event.column && isUtilityColumn(event.column)) return false;\n if (!this.isCellSelectable(rowIndex, colIndex)) return false;\n\n // A tapped (not dragged) corner handle is waiting for a destination — this\n // click places it instead of starting a new selection (SC 2.5.7).\n if (this.#armedCorner) {\n const corner = this.#armedCorner;\n this.#disarmRangeCorner();\n this.#resizeRangeCorner(corner, rowIndex, colIndex);\n return true;\n }\n\n // A tap never reaches `onCellMouseDown` (coarse presses only dispatch it\n // after a long-press), so the handle gate has to be updated here too.\n this.#rangeFromCoarsePointer = this.#isCoarseEvent(originalEvent);\n\n const shiftKey = originalEvent.shiftKey;\n const ctrlKey = (originalEvent.ctrlKey || originalEvent.metaKey) && this.config.multiSelect !== false;\n\n if (shiftKey && this.cellAnchor) {\n // Extend selection from anchor\n const newRange = createRangeFromAnchor(this.cellAnchor, { row: rowIndex, col: colIndex });\n\n // Check if range actually changed\n const currentRange = this.ranges.length > 0 ? this.ranges[this.ranges.length - 1] : null;\n if (currentRange && rangesEqual(currentRange, newRange)) return false;\n\n if (!ctrlKey) this.ranges = [newRange];\n else if (this.ranges.length > 0) this.ranges[this.ranges.length - 1] = newRange;\n else this.ranges.push(newRange);\n this.activeRange = newRange;\n } else {\n const newRange: InternalCellRange = {\n startRow: rowIndex,\n startCol: colIndex,\n endRow: rowIndex,\n endCol: colIndex,\n };\n if (ctrlKey) {\n this.ranges.push(newRange);\n } else {\n // Plain click - only emit if the same single-cell range isn't already selected\n if (this.ranges.length === 1 && rangesEqual(this.ranges[0], newRange)) return false;\n this.ranges = [newRange];\n }\n this.activeRange = newRange;\n this.cellAnchor = { row: rowIndex, col: colIndex };\n this.#extendAnchor = { row: rowIndex, col: colIndex };\n }\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return false;\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean {\n // Skip all selection if disabled at grid level or plugin level\n if (!this.isSelectionEnabled()) return false;\n\n if (this.#mode.columnEnabled && this.#keyColumnAxis(event)) return true;\n\n const mode = this.#mode.primary;\n\n // Escape unwinds one step at a time: an armed range corner first, then\n // touch selection mode, then the selection itself.\n if (event.key === 'Escape' && this.#disarmRangeCorner()) return true;\n\n // Escape leaves touch selection mode first (an external keyboard is the\n // documented escape hatch), and only clears selection on a second press.\n if (event.key === 'Escape' && this.#touchActive) {\n this.exitTouchSelection();\n return true;\n }\n\n // Escape clears selection in all modes\n if (event.key === 'Escape') return this.#keyClearSelection(mode);\n\n const isNavKey = NAV_KEYS.includes(event.key);\n switch (mode) {\n case 'cell':\n return isNavKey ? this.#keyNavCellMode() : false;\n case 'row':\n return this.#keyRowMode(event);\n case 'range':\n return this.#keyRangeMode(event, isNavKey);\n default:\n return false;\n }\n }\n\n /**\n * Column-axis keyboard chords (only reachable when `columnEnabled`):\n * - **Ctrl/⌘+Space** — WAI-ARIA Grid: toggle column selection for the focused\n * column. Per spec the key is `' '`; some older hosts report `'Spacebar'`.\n * - **Ctrl/⌘+Shift+ArrowLeft/Right** — extend column selection along the\n * visible columns.\n *\n * @returns `true` when the chord was consumed.\n */\n #keyColumnAxis(event: KeyboardEvent): boolean {\n const ctrlOrMeta = event.ctrlKey || event.metaKey;\n if (!ctrlOrMeta) return false;\n // Editors keep their own Ctrl+Space / Ctrl+Shift+Arrow (word selection) behaviour.\n if (isFormFieldKeyTarget(event) || this.grid.query<boolean>('isEditing').some(Boolean)) return false;\n\n if (event.key === ' ' || event.key === 'Spacebar') {\n const column = this.visibleColumns[this.grid._focusCol];\n if (!column || isUtilityColumn(column) || typeof column.field !== 'string') return false;\n event.preventDefault();\n event.stopPropagation();\n this.selectColumn(column.field, { toggle: true });\n return true;\n }\n\n if (\n event.shiftKey &&\n this.activeAxis === 'column' &&\n this.config.multiSelect !== false &&\n (event.key === 'ArrowLeft' || event.key === 'ArrowRight')\n ) {\n const fields = selectableColumnFields(this.visibleColumns);\n const direction = event.key === 'ArrowLeft' ? 'left' : 'right';\n const newHead = computeKeyboardExtension(this.columnHead, fields, direction);\n if (newHead === null || this.columnAnchor === null) return false;\n event.preventDefault();\n event.stopPropagation();\n this.selectColumn(newHead, { range: true });\n return true;\n }\n\n return false;\n }\n\n /** Escape: clear the active axis. Defers to EditingPlugin while an edit is open. */\n #keyClearSelection(mode: SelectionMode): boolean {\n // If editing is active, let the EditingPlugin cancel the active edit first\n if (this.grid.query<boolean>('isEditing').some(Boolean)) return false;\n\n // Column axis — clear it only; a single Escape clears the *active* axis when\n // both axes are configured.\n if (this.activeAxis === 'column') {\n this.selectedColumns.clear();\n this.columnAnchor = null;\n this.columnHead = null;\n this.activeAxis = 'none';\n } else if (mode === 'cell') {\n this.selectedCell = null;\n } else if (mode === 'row') {\n this.selected.clear();\n this.anchor = null;\n } else if (mode === 'range') {\n this.ranges = [];\n this.activeRange = null;\n this.cellAnchor = null;\n }\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return true;\n }\n\n /** CELL MODE: selection follows focus (but respects selectability). */\n #keyNavCellMode(): boolean {\n // Use queueMicrotask so grid's handler runs first and updates focusRow/focusCol\n queueMicrotask(() => {\n const focusRow = this.grid._focusRow;\n const focusCol = this.grid._focusCol;\n // Only select if the cell is selectable; clear when navigating to a non-selectable cell\n this.selectedCell = this.isCellSelectable(focusRow, focusCol) ? { row: focusRow, col: focusCol } : null;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n });\n return false; // Let grid handle navigation\n }\n\n /** ROW MODE: Arrow/Page/Ctrl+Home/End move selection, Shift extends, Ctrl+A selects all. */\n #keyRowMode(event: KeyboardEvent): boolean {\n const multiSelect = this.config.multiSelect !== false;\n const isRowNavKey =\n event.key === 'ArrowUp' ||\n event.key === 'ArrowDown' ||\n event.key === 'PageUp' ||\n event.key === 'PageDown' ||\n ((event.ctrlKey || event.metaKey) && (event.key === 'Home' || event.key === 'End'));\n\n if (isRowNavKey) {\n const shiftKey = event.shiftKey && multiSelect;\n\n // Set anchor SYNCHRONOUSLY before grid moves focus\n if (shiftKey && this.anchor === null) this.anchor = this.grid._focusRow;\n\n // Mark explicit selection SYNCHRONOUSLY so #syncSelectionToFocus\n // won't overwrite the anchor if afterRender fires before our update\n this.explicitSelection = true;\n\n // Store pending update — processed in afterRender when grid has updated focusRow\n this.pendingRowKeyUpdate = { shiftKey };\n\n // Schedule afterRender (grid's refreshVirtualWindow(false) may skip it)\n queueMicrotask(() => this.requestAfterRender());\n return false; // Let grid handle navigation\n }\n\n return this.#keySelectAll(event, multiSelect);\n }\n\n /**\n * RANGE MODE: Shift+Arrow extends, plain Arrow resets, Ctrl+A selects all.\n * Tab always navigates without extending (even with Shift).\n */\n #keyRangeMode(event: KeyboardEvent, isNavKey: boolean): boolean {\n if (!isNavKey) return this.#keyRangeSpan(event) || this.#keySelectAll(event, this.config.multiSelect !== false);\n\n const shouldExtend = event.shiftKey && event.key !== 'Tab';\n\n // Capture anchor BEFORE grid moves focus (synchronous)\n // This ensures the anchor is the starting point, not the destination\n if (shouldExtend && !this.cellAnchor) {\n this.cellAnchor = { row: this.grid._focusRow, col: this.grid._focusCol };\n }\n\n // Mark pending update - will be processed in afterRender when grid updates focus\n this.pendingKeyboardUpdate = { shiftKey: shouldExtend };\n\n // Schedule afterRender to run after grid's keyboard handler completes.\n // Grid's refreshVirtualWindow(false) skips afterRender for performance,\n // so we explicitly request it to process pendingKeyboardUpdate.\n queueMicrotask(() => this.requestAfterRender());\n\n return false; // Let grid handle navigation\n }\n\n /**\n * WAI-ARIA APG grid chords in range mode:\n * - **Shift+Space** — select the row(s) spanned by the active range (or the focused row).\n * - **Ctrl/⌘+Space** — select the spanned column(s); only when the column axis is not\n * configured (otherwise {@link #keyColumnAxis} owns it).\n *\n * Skipped for form-field targets and while an edit is open so editors still type spaces.\n */\n #keyRangeSpan(event: KeyboardEvent): boolean {\n if (event.key !== ' ' && event.key !== 'Spacebar') return false;\n const ctrlOrMeta = event.ctrlKey || event.metaKey;\n let axis: 'row' | 'column';\n if (event.shiftKey && !ctrlOrMeta) axis = 'row';\n else if (ctrlOrMeta && !event.shiftKey && !this.#mode.columnEnabled) axis = 'column';\n else return false;\n if (event.altKey) return false;\n if (isFormFieldKeyTarget(event)) return false;\n if (this.grid.query<boolean>('isEditing').some(Boolean)) return false;\n\n const rowCount = this.rows.length;\n const colCount = this.visibleColumns.length;\n if (rowCount === 0 || colCount === 0) return false;\n\n const focus = { row: this.grid._focusRow, col: this.grid._focusCol };\n const span = this.activeRange\n ? normalizeRange(this.activeRange)\n : { startRow: focus.row, startCol: focus.col, endRow: focus.row, endCol: focus.col };\n const range: InternalCellRange =\n axis === 'row'\n ? { startRow: span.startRow, startCol: 0, endRow: span.endRow, endCol: colCount - 1 }\n : { startRow: 0, startCol: span.startCol, endRow: rowCount - 1, endCol: span.endCol };\n\n event.preventDefault();\n event.stopPropagation();\n\n // Anchor on the corner farthest from focus so a following Shift+Arrow keeps the far edge.\n const anchor = {\n row: Math.abs(focus.row - range.startRow) >= Math.abs(focus.row - range.endRow) ? range.startRow : range.endRow,\n col: Math.abs(focus.col - range.startCol) >= Math.abs(focus.col - range.endCol) ? range.startCol : range.endCol,\n };\n this.ranges = [range];\n this.activeRange = range;\n this.#spanRange = { axis, range };\n this.cellAnchor = anchor;\n this.#extendAnchor = anchor;\n this.#pendingSpanAnnouncement = {\n axis,\n count: axis === 'row' ? range.endRow - range.startRow + 1 : range.endCol - range.startCol + 1,\n };\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return true;\n }\n\n /** Ctrl/⌘+A: select all (skipped while editing, and when single-select). */\n #keySelectAll(event: KeyboardEvent, multiSelect: boolean): boolean {\n if (!multiSelect || event.key !== 'a' || !(event.ctrlKey || event.metaKey)) return false;\n if (this.grid.query<boolean>('isEditing').some(Boolean)) return false;\n event.preventDefault();\n event.stopPropagation();\n this.selectAll();\n return true;\n }\n\n /** @internal */\n override onCellMouseDown(event: CellMouseEvent): boolean | void {\n // Skip all selection if disabled at grid level or plugin level\n if (!this.isSelectionEnabled()) return;\n\n // ROW MODE — touch selection entry (#304).\n //\n // `event-delegation.ts` only dispatches `mousedown` for a coarse pointer\n // *after* a 400 ms long-press has elapsed, so reaching here with a coarse\n // event already means \"the user held the row down\". Header presses are\n // excluded — they belong to the column header menu (#270).\n if (this.#mode.primary === 'row') {\n if (event.rowIndex === undefined || event.rowIndex < 0) return;\n if (this.config.multiSelect === false) return;\n if (!this.#isCoarseEvent(event.originalEvent)) return;\n if (event.column && isUtilityColumn(event.column)) return;\n if (this.#touchActive) {\n this.#extendTouchSelection(event.rowIndex);\n return true;\n }\n return this.#enterTouchSelection(event.rowIndex) || undefined;\n }\n\n if (this.#mode.primary !== 'range') return;\n if (event.rowIndex === undefined || event.colIndex === undefined) return;\n if (event.rowIndex < 0) return; // Header\n\n // A tapped corner handle owns the next press: swallow it so no drag starts\n // and the range is not reset before `onCellClick` places the corner.\n if (this.#armedCorner) return true;\n\n this.#rangeFromCoarsePointer = this.#isCoarseEvent(event.originalEvent);\n\n // Skip utility columns (expander columns, etc.)\n // event.column is already resolved from _visibleColumns in the event builder\n if (event.column && isUtilityColumn(event.column)) {\n return; // Don't start selection on utility columns\n }\n\n // Skip non-selectable cells - don't start drag from them\n if (!this.isCellSelectable(event.rowIndex, event.colIndex)) {\n return;\n }\n\n // Let onCellClick handle shift+click for range extension\n if (event.originalEvent.shiftKey && this.cellAnchor) {\n return;\n }\n\n // Start drag selection\n this.isDragging = true;\n const rowIndex = event.rowIndex;\n const colIndex = event.colIndex;\n\n // When multiSelect is false, Ctrl+click starts a new single range instead of adding\n const ctrlKey = (event.originalEvent.ctrlKey || event.originalEvent.metaKey) && this.config.multiSelect !== false;\n\n const newRange: InternalCellRange = {\n startRow: rowIndex,\n startCol: colIndex,\n endRow: rowIndex,\n endCol: colIndex,\n };\n\n // Check if selection is actually changing (for non-Ctrl clicks)\n if (!ctrlKey && this.ranges.length === 1 && rangesEqual(this.ranges[0], newRange)) {\n // Same cell already selected, just update anchor for potential drag\n this.cellAnchor = { row: rowIndex, col: colIndex };\n this.#extendAnchor = { row: rowIndex, col: colIndex };\n return true;\n }\n\n this.cellAnchor = { row: rowIndex, col: colIndex };\n this.#extendAnchor = { row: rowIndex, col: colIndex };\n\n if (!ctrlKey) {\n this.ranges = [];\n }\n\n this.ranges.push(newRange);\n this.activeRange = newRange;\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return true;\n }\n\n /**\n * Point the selection at the cell a context menu was invoked on — however it\n * was invoked: mouse right-click, touch long-press, Shift+F10, the ContextMenu\n * key, or a synthesised `contextmenu`. A target already inside the selection\n * keeps it, so the menu acts on all of it; otherwise the selection moves to\n * the target row (row mode) or cell (cell/range mode), as file managers and\n * spreadsheets do. `#extendAnchor` is left alone so \"Extend selection to here\"\n * still extends from the last primary anchor rather than from the target.\n */\n #selectContextMenuTarget(rowIndex: number, colIndex: number): void {\n if (rowIndex < 0 || !this.isSelectionEnabled()) return;\n // Column axis (mixed modes): a cell in a selected column is part of the selection.\n if (this.activeAxis === 'column' && this.selectedColumns.has(this.visibleColumns[colIndex]?.field ?? '')) return;\n const mode = this.#mode.primary;\n\n if (mode === 'row') {\n if (!this.selected.has(rowIndex)) this.selectRows([rowIndex]);\n return;\n }\n if (mode !== 'cell' && mode !== 'range') return;\n\n const column = this.visibleColumns[colIndex];\n if (!column || isUtilityColumn(column) || !this.isCellSelectable(rowIndex, colIndex)) return;\n\n if (mode === 'cell') {\n const current = this.selectedCell;\n if (current && current.row === rowIndex && current.col === colIndex) return;\n this.selectedCell = { row: rowIndex, col: colIndex };\n } else {\n if (isCellInAnyRange(rowIndex, colIndex, this.ranges)) return;\n const range: InternalCellRange = { startRow: rowIndex, startCol: colIndex, endRow: rowIndex, endCol: colIndex };\n this.ranges = [range];\n this.activeRange = range;\n this.cellAnchor = { row: rowIndex, col: colIndex };\n }\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /** @internal */\n override onCellMouseMove(event: CellMouseEvent): boolean | void {\n // Skip all selection if disabled at grid level or plugin level\n if (!this.isSelectionEnabled()) return;\n\n if (this.#mode.primary !== 'range') return;\n if (!this.isDragging || !this.cellAnchor) return;\n if (event.rowIndex === undefined || event.colIndex === undefined) return;\n if (event.rowIndex < 0) return;\n\n // When dragging, clamp to first data column (skip utility columns)\n // colIndex from events is a visible-column index (from data-col)\n let targetCol = event.colIndex;\n const column = this.visibleColumns[targetCol];\n if (column && isUtilityColumn(column)) {\n // Find the first non-utility visible column\n const firstDataCol = this.visibleColumns.findIndex((col) => !isUtilityColumn(col));\n if (firstDataCol >= 0) {\n targetCol = firstDataCol;\n }\n }\n\n const newRange = createRangeFromAnchor(this.cellAnchor, { row: event.rowIndex, col: targetCol });\n\n // Only update and emit if the range actually changed\n const currentRange = this.ranges.length > 0 ? this.ranges[this.ranges.length - 1] : null;\n if (currentRange && rangesEqual(currentRange, newRange)) {\n return true; // Range unchanged, no need to update\n }\n\n if (this.ranges.length > 0) {\n this.ranges[this.ranges.length - 1] = newRange;\n } else {\n this.ranges.push(newRange);\n }\n this.activeRange = newRange;\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n return true;\n }\n\n /** @internal */\n override onCellMouseUp(_event: CellMouseEvent): boolean | void {\n // Skip all selection if disabled at grid level or plugin level\n if (!this.isSelectionEnabled()) return;\n\n if (this.#mode.primary !== 'range') return;\n if (this.isDragging) {\n this.isDragging = false;\n return true;\n }\n }\n\n /**\n * Header click handler — drives column-axis selection.\n *\n * - Plain click (and plain Shift+click): defer to MultiSort / core sort by\n * returning `false`. Header-click sort behavior is unchanged.\n * - **Ctrl/Cmd+click**: toggle selection of the clicked column (or replace,\n * when `multiSelect: false`).\n * - **Ctrl/Cmd+Shift+click**: extend selection from the column anchor to the\n * clicked column. Avoids the plain `Shift+click` chord owned by MultiSort.\n *\n * No-ops when column selection isn't enabled or when the clicked column is\n * a utility column (`utility: true`).\n * @internal\n */\n override onHeaderClick(event: HeaderClickEvent): boolean | void {\n if (!this.isSelectionEnabled()) return false;\n if (!this.#mode.columnEnabled) return false;\n if (event.column && isUtilityColumn(event.column)) return false;\n\n const e = event.originalEvent;\n const ctrlKey = e.ctrlKey || e.metaKey;\n if (!ctrlKey) return false; // Plain / Shift click → sort path\n\n const field = event.field;\n if (!field) return false;\n\n e.preventDefault();\n if (typeof e.stopPropagation === 'function') e.stopPropagation();\n\n const range = e.shiftKey === true && this.config.multiSelect !== false && this.columnAnchor !== null;\n this.selectColumn(field, range ? { range: true } : { toggle: true });\n return true; // Handled — suppress sort\n }\n\n // #region Checkbox Column\n\n /**\n * Inject checkbox column when `checkbox: true` and mode is `'row'`.\n * @internal\n */\n override processColumns(columns: ColumnConfig[]): ColumnConfig[] {\n if (this.config.checkbox && this.#mode.primary === 'row') {\n // Check if checkbox column already exists\n if (columns.some((col) => col.field === CHECKBOX_COLUMN_FIELD)) {\n return columns;\n }\n const checkboxCol = this.#createCheckboxColumn();\n // Insert after the expander or any leading left-pinned columns.\n const expanderIdx = columns.findIndex(isExpanderColumn);\n const firstUnpinnedIdx = columns.findIndex(\n (column) => (column as ColumnConfig & { pinned?: string }).pinned !== 'left',\n );\n const leftPinnedEnd = firstUnpinnedIdx < 0 ? columns.length : firstUnpinnedIdx;\n const insertAt = expanderIdx >= 0 ? Math.max(expanderIdx + 1, leftPinnedEnd) : leftPinnedEnd;\n return [...columns.slice(0, insertAt), checkboxCol, ...columns.slice(insertAt)];\n }\n return columns;\n }\n\n /**\n * Create the checkbox utility column configuration.\n */\n #createCheckboxColumn(): ColumnConfig & { pinned: 'left' } {\n return {\n field: CHECKBOX_COLUMN_FIELD,\n header: '',\n width: 32,\n pinned: 'left',\n resizable: false,\n sortable: false,\n lockPosition: true,\n utility: true,\n checkboxColumn: true,\n headerRenderer: () => {\n // A label, not a div: it forwards the pointer to the checkbox natively,\n // so the target is the whole 32px cell without inflating the box (SC 2.5.8).\n const container = document.createElement('label');\n container.className = 'tbw-checkbox-header';\n // Hide \"select all\" checkbox in single-select mode\n if (this.config.multiSelect === false) return container;\n const checkbox = document.createElement('input');\n checkbox.type = 'checkbox';\n checkbox.className = 'tbw-select-all-checkbox';\n // The wrapping label names the checkbox implicitly AND gives the\n // otherwise-empty `columnheader` cell screen-reader-visible text.\n const labelText = document.createElement('span');\n labelText.className = 'tbw-sr-only';\n labelText.textContent = getA11yMessage(this.gridElement, 'selectAllRows');\n checkbox.addEventListener('click', (e) => {\n e.stopPropagation(); // Prevent header sort\n if ((e.target as HTMLInputElement).checked) {\n this.selectAll();\n } else {\n this.clearSelection();\n }\n });\n // The label's own click keeps bubbling after it forwards to the\n // checkbox; stop it so the header cell sees nothing.\n container.addEventListener('click', (e) => e.stopPropagation());\n container.append(checkbox, labelText);\n return container;\n },\n renderer: (ctx) => {\n const checkbox = document.createElement('input');\n checkbox.type = 'checkbox';\n checkbox.className = 'tbw-select-row-checkbox';\n // Set initial checked state from current selection\n const cellEl = ctx.cellEl;\n const rowIndex = cellEl ? parseInt(cellEl.getAttribute('data-row') ?? '-1', 10) : -1;\n if (rowIndex >= 0) {\n checkbox.checked = this.selected.has(rowIndex);\n }\n checkbox.setAttribute('aria-label', getA11yMessage(this.gridElement, 'selectRow', Math.max(rowIndex, 0)));\n return checkbox;\n },\n };\n }\n\n /**\n * Update checkbox checked states to reflect current selection.\n * Called from #applySelectionClasses.\n */\n #updateCheckboxStates(gridEl: HTMLElement): void {\n // Update row checkboxes\n const rowCheckboxes = gridEl.querySelectorAll('.tbw-select-row-checkbox') as NodeListOf<HTMLInputElement>;\n rowCheckboxes.forEach((checkbox) => {\n const cell = checkbox.closest('.cell');\n const rowIndex = cell ? getRowIndexFromCell(cell) : -1;\n if (rowIndex >= 0) {\n checkbox.checked = this.selected.has(rowIndex);\n }\n });\n\n // Update header select-all checkbox\n const headerCheckbox = gridEl.querySelector('.tbw-select-all-checkbox') as HTMLInputElement | null;\n if (headerCheckbox) {\n const rowCount = this.rows.length;\n let selectableCount = 0;\n if (this.config.isSelectable) {\n for (let i = 0; i < rowCount; i++) {\n if (this.isRowSelectable(i)) selectableCount++;\n }\n } else {\n selectableCount = rowCount;\n }\n const allSelected = selectableCount > 0 && this.selected.size >= selectableCount;\n const someSelected = this.selected.size > 0;\n headerCheckbox.checked = allSelected;\n headerCheckbox.indeterminate = someSelected && !allSelected;\n }\n }\n\n // #endregion\n\n /**\n * True when focus is currently inside the grid host (data-has-focus is set on focusin).\n * Used to determine whether selection should follow the focus cursor.\n */\n #gridHasFocus(): boolean {\n return this.gridElement?.hasAttribute('data-has-focus') ?? false;\n }\n\n /**\n * Sync selection state to the grid's current focus position.\n * In row mode, keeps `selected` in sync with `_focusRow`.\n * In cell mode, keeps `selectedCell` in sync with `_focusRow`/`_focusCol`.\n * Only updates when the focus has changed since the last sync.\n * Skips when `explicitSelection` is set (click/keyboard set selection directly).\n *\n * Issue #392: selection must be a deliberate user action. The grid's focus\n * cursor defaults to (0,0) even before focus enters the grid, so following it\n * unconditionally auto-selects row 0 / cell 0,0 on first render. Only follow\n * focus when focus is genuinely inside the grid. Always advance the synced\n * markers so the resting position is treated as already-synced (tabbing in and\n * landing on the default cell must not select it).\n */\n #syncSelectionToFocus(mode: string): void {\n const focusRow = this.grid._focusRow;\n const focusCol = this.grid._focusCol;\n\n // Only follow focus when the grid actually has focus. Otherwise, keep the\n // synced markers in step so the resting position is not retroactively selected\n // when focus enters the grid later.\n if (!this.#gridHasFocus()) {\n this.lastSyncedFocusRow = focusRow;\n this.lastSyncedFocusCol = focusCol;\n return;\n }\n\n if (mode === 'row') {\n // Skip auto-sync when selection was explicitly set (Shift/Ctrl click, keyboard)\n if (this.explicitSelection) {\n this.explicitSelection = false;\n this.lastSyncedFocusRow = focusRow;\n return;\n }\n\n if (focusRow !== this.lastSyncedFocusRow) {\n this.lastSyncedFocusRow = focusRow;\n if (this.isRowSelectable(focusRow)) {\n if (!this.selected.has(focusRow) || this.selected.size !== 1) {\n this.selected.clear();\n this.selected.add(focusRow);\n this.lastSelected = focusRow;\n this.anchor = focusRow;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n }\n }\n }\n }\n\n if (mode === 'cell') {\n if (this.explicitSelection) {\n this.explicitSelection = false;\n this.lastSyncedFocusRow = focusRow;\n this.lastSyncedFocusCol = focusCol;\n return;\n }\n\n if (focusRow !== this.lastSyncedFocusRow || focusCol !== this.lastSyncedFocusCol) {\n this.lastSyncedFocusRow = focusRow;\n this.lastSyncedFocusCol = focusCol;\n if (this.isCellSelectable(focusRow, focusCol)) {\n const cur = this.selectedCell;\n if (!cur || cur.row !== focusRow || cur.col !== focusCol) {\n this.selectedCell = { row: focusRow, col: focusCol };\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n }\n }\n }\n }\n }\n\n /**\n * Apply CSS selection classes to row/cell elements.\n * Shared by afterRender and onScrollRender.\n */\n #applySelectionClasses(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const mode = this.#mode.primary;\n const columnEnabled = this.#mode.columnEnabled;\n const hasSelectableCallback = !!this.config.isSelectable;\n\n // Reflect multi-select capability on the role=grid element so screen readers\n // announce the grid as multi-selectable. WAI-ARIA requires aria-multiselectable\n // on the element carrying role=\"grid\" — that's `.rows-body` in our render tree,\n // not the host. `multiSelect` defaults to true; only `false` opts out.\n const rowsBodyEl = gridEl.querySelector('.rows-body');\n if (rowsBodyEl) {\n const multi = this.config.multiSelect !== false;\n rowsBodyEl.setAttribute('aria-multiselectable', multi ? 'true' : 'false');\n }\n\n // Clear all selection classes first (including column-selected).\n // Also reset stale aria-selected on cells that previously carried a\n // selection marker — range/column passes set aria-selected=\"true\" on\n // selected cells, and core only updates the attribute when focus\n // changes — so without an explicit reset a cell that lost selection\n // (axis flipped, range shrank, virtualization recycled the node into a\n // non-selected position) would keep the stale value. We MUST scope the\n // reset to cells that had `.selected` / `.column-selected` BEFORE the\n // class wipe — clearing aria-selected unconditionally would also blow\n // away the focused-cell marker that core's keyboard handler / row\n // renderer set for the active cell, regressing keyboard a11y.\n // Header aria-selected is handled in the columnEnabled block below.\n const allCells = gridEl.querySelectorAll('.cell');\n allCells.forEach((cell) => {\n const hadSelectionMarker =\n cell.classList.contains(GridClasses.SELECTED) || cell.classList.contains('column-selected');\n cell.classList.remove(GridClasses.SELECTED, 'top', 'bottom', 'first', 'last', 'column-selected');\n if (hadSelectionMarker) {\n cell.removeAttribute('aria-selected');\n }\n // Clear selectable attribute - will be re-applied below\n if (hasSelectableCallback) {\n cell.removeAttribute('data-selectable');\n }\n });\n\n const allRows = gridEl.querySelectorAll('.data-grid-row');\n allRows.forEach((row) => {\n row.classList.remove(GridClasses.SELECTED, 'row-focus');\n row.setAttribute('aria-selected', 'false');\n // Clear selectable attribute - will be re-applied below\n if (hasSelectableCallback) {\n row.removeAttribute('data-selectable');\n }\n });\n\n // Clear column-selected from header cells too\n if (columnEnabled) {\n const headerCells = gridEl.querySelectorAll('.header-row > .cell');\n headerCells.forEach((cell) => {\n cell.classList.remove('column-selected');\n cell.removeAttribute('aria-selected');\n });\n }\n\n // ROW MODE: Add row-focus class to selected rows, disable cell-focus, update checkboxes\n if (mode === 'row') {\n // In row mode, disable ALL cell-focus styling - row selection takes precedence\n clearCellFocus(gridEl);\n\n allRows.forEach((row) => {\n const firstCell = row.querySelector('.cell[data-row]');\n const rowIndex = getRowIndexFromCell(firstCell);\n if (rowIndex >= 0) {\n // Mark non-selectable rows\n if (hasSelectableCallback && !this.isRowSelectable(rowIndex)) {\n row.setAttribute('data-selectable', 'false');\n }\n if (this.selected.has(rowIndex)) {\n row.classList.add(GridClasses.SELECTED, 'row-focus');\n row.setAttribute('aria-selected', 'true');\n }\n }\n });\n\n // Update checkbox states if checkbox column is enabled\n if (this.config.checkbox) {\n this.#updateCheckboxStates(gridEl);\n }\n }\n\n // CELL/RANGE MODE: Mark non-selectable cells\n if ((mode === 'cell' || mode === 'range') && hasSelectableCallback) {\n const cells = gridEl.querySelectorAll('.cell[data-row][data-col]');\n cells.forEach((cell) => {\n const rowIndex = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n if (rowIndex >= 0 && colIndex >= 0) {\n if (!this.isCellSelectable(rowIndex, colIndex)) {\n cell.setAttribute('data-selectable', 'false');\n }\n }\n });\n }\n\n // RANGE MODE: Add selected and edge classes to cells\n // Uses neighbor-based edge detection for correct multi-range borders\n if (mode === 'range' && this.ranges.length > 0) {\n // Clear all cell-focus first - selection plugin manages focus styling in range mode\n clearCellFocus(gridEl);\n\n // Pre-normalize ranges for efficient neighbor checks\n const normalizedRanges = this.ranges.map(normalizeRange);\n\n // Fast selection check against pre-normalized ranges\n const isInSelection = (r: number, c: number): boolean => {\n for (const range of normalizedRanges) {\n if (r >= range.startRow && r <= range.endRow && c >= range.startCol && c <= range.endCol) {\n return true;\n }\n }\n return false;\n };\n\n const cells = gridEl.querySelectorAll('.cell[data-row][data-col]');\n cells.forEach((cell) => {\n const rowIndex = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n if (rowIndex >= 0 && colIndex >= 0) {\n // Skip utility columns entirely - don't add any selection classes\n // colIndex from data-col is a visible-column index\n const column = this.visibleColumns[colIndex];\n if (column && isUtilityColumn(column)) {\n return;\n }\n\n if (isInSelection(rowIndex, colIndex)) {\n cell.classList.add(GridClasses.SELECTED);\n cell.setAttribute('aria-selected', 'true');\n\n // Edge detection: add border class where neighbor is not selected\n // This handles single ranges, multi-range, and irregular selections correctly\n if (!isInSelection(rowIndex - 1, colIndex)) cell.classList.add('top');\n if (!isInSelection(rowIndex + 1, colIndex)) cell.classList.add('bottom');\n if (!isInSelection(rowIndex, colIndex - 1)) cell.classList.add('first');\n if (!isInSelection(rowIndex, colIndex + 1)) cell.classList.add('last');\n }\n }\n });\n }\n\n // CELL MODE: Let the grid's native .cell-focus styling handle cell highlighting\n // No additional action needed - the grid already manages focus styling\n\n // COLUMN AXIS: Apply column-selected class + aria-selected to the header cell\n // and every data cell in the matching column. Identifies columns by their\n // visible-index (data-col matches the visibleColumns position) so it works\n // regardless of pinning / reordering — selectedColumns stores fields, not\n // indices, so the rendering layer resolves them per-render.\n if (columnEnabled && this.selectedColumns.size > 0) {\n // Build visible-index → field map once for O(1) lookups.\n const colFieldByIndex: (string | undefined)[] = this.visibleColumns.map((c) =>\n typeof c.field === 'string' ? c.field : undefined,\n );\n\n // Header cells — the grid renders header cells with data-col attributes.\n const headerCells = gridEl.querySelectorAll<HTMLElement>('.header-row > .cell[data-col]');\n headerCells.forEach((cell) => {\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n const field = colIndex >= 0 ? colFieldByIndex[colIndex] : undefined;\n if (field && this.selectedColumns.has(field)) {\n cell.classList.add('column-selected');\n cell.setAttribute('aria-selected', 'true');\n }\n });\n\n // Data cells.\n const cells = gridEl.querySelectorAll<HTMLElement>('.cell[data-col]:not(.header-row .cell)');\n cells.forEach((cell) => {\n // Skip header cells (filter above isn't reliable for nested .header-row scoping)\n if (cell.closest('.header-row')) return;\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n if (colIndex < 0) return;\n const column = this.visibleColumns[colIndex];\n if (!column || isUtilityColumn(column)) return;\n const field = colFieldByIndex[colIndex];\n if (field && this.selectedColumns.has(field)) {\n cell.classList.add('column-selected');\n cell.setAttribute('aria-selected', 'true');\n }\n });\n }\n }\n\n /** @internal */\n override afterRender(): void {\n // Skip rendering selection if disabled at grid level or plugin level\n if (!this.isSelectionEnabled()) return;\n\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const container = gridEl.querySelector('.tbw-grid-root');\n const mode = this.#mode.primary;\n\n // Process pending row keyboard navigation update (row mode)\n // This runs AFTER the grid has updated focusRow\n if (this.pendingRowKeyUpdate && mode === 'row') {\n const { shiftKey } = this.pendingRowKeyUpdate;\n this.pendingRowKeyUpdate = null;\n\n const focusRow = this.grid._focusRow;\n\n if (shiftKey && this.anchor !== null) {\n // Shift+nav: Extend selection from anchor to new focus\n this.selected.clear();\n const start = Math.min(this.anchor, focusRow);\n const end = Math.max(this.anchor, focusRow);\n for (let i = start; i <= end; i++) {\n if (this.isRowSelectable(i)) {\n this.selected.add(i);\n }\n }\n } else {\n // Plain nav: Single select\n if (this.isRowSelectable(focusRow)) {\n this.selected.clear();\n this.selected.add(focusRow);\n this.anchor = focusRow;\n } else {\n this.selected.clear();\n }\n }\n\n this.lastSelected = focusRow;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n }\n\n // Process pending keyboard navigation update (range mode)\n // This runs AFTER the grid has updated focusRow/focusCol\n if (this.pendingKeyboardUpdate && mode === 'range') {\n const { shiftKey } = this.pendingKeyboardUpdate;\n this.pendingKeyboardUpdate = null;\n\n const currentRow = this.grid._focusRow;\n const currentCol = this.grid._focusCol;\n\n if (shiftKey && this.cellAnchor) {\n // Extend selection from anchor to current focus\n let newRange = createRangeFromAnchor(this.cellAnchor, { row: currentRow, col: currentCol });\n const span = this.#spanRange;\n if (span && span.range === this.activeRange) {\n newRange =\n span.axis === 'row'\n ? { ...newRange, startCol: 0, endCol: this.visibleColumns.length - 1 }\n : { ...newRange, startRow: 0, endRow: this.rows.length - 1 };\n span.range = newRange;\n }\n this.ranges = [newRange];\n this.activeRange = newRange;\n } else if (!shiftKey) {\n // Without shift, clear selection (cell-focus will show instead)\n this.ranges = [];\n this.activeRange = null;\n this.cellAnchor = { row: currentRow, col: currentCol }; // Reset anchor to current position\n }\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n }\n\n // Sync selection to grid's focus position.\n // This ensures selection follows keyboard navigation (Tab, arrows, etc.)\n // regardless of which plugin moved the focus.\n this.#syncSelectionToFocus(mode);\n\n // Set data attribute on host for CSS variable scoping\n this.gridElement.setAttribute('data-selection-mode', mode);\n\n // Toggle .selecting class during drag to prevent text selection\n if (container) {\n container.classList.toggle('selecting', this.isDragging);\n }\n\n this.#applySelectionClasses();\n this.#renderTouchChrome(container as HTMLElement | null);\n }\n\n /**\n * Called after scroll-triggered row rendering.\n * Reapplies selection classes to recycled DOM elements.\n * @internal\n */\n override onScrollRender(): void {\n // Skip rendering selection classes if disabled\n if (!this.isSelectionEnabled()) return;\n\n this.#applySelectionClasses();\n }\n\n // #endregion\n\n // #region Public API\n\n /**\n * Get the current selection as a unified result.\n * Works for all selection modes and always returns ranges.\n *\n * @example\n * ```ts\n * const selection = plugin.getSelection();\n * if (selection.ranges.length > 0) {\n * const { from, to } = selection.ranges[0];\n * // For cell mode: from === to (single cell)\n * // For row mode: from.col = 0, to.col = lastCol (full row)\n * // For range mode: rectangular selection\n * }\n * ```\n */\n getSelection(): SelectionResult {\n const event = this.#buildEvent();\n return {\n mode: this.config.mode,\n activeAxis: event.activeAxis,\n ranges: event.ranges,\n selectedColumns: event.selectedColumns,\n anchor: this.cellAnchor,\n };\n }\n\n /**\n * Get all selected cells across all ranges.\n */\n getSelectedCells(): Array<{ row: number; col: number }> {\n return getAllCellsInRanges(this.ranges);\n }\n\n /**\n * Check if a specific cell is in range selection.\n */\n isCellSelected(row: number, col: number): boolean {\n return isCellInAnyRange(row, col, this.ranges);\n }\n\n /**\n * Select all selectable rows (row mode) or all cells (range mode).\n *\n * In row mode, selects every row where `isSelectable` returns true (or all rows if no callback).\n * In range mode, creates a single range spanning all rows and visible columns.\n * Array modes resolve to their row/range axis. Has no effect in cell mode.\n *\n * @example\n * ```ts\n * const plugin = grid.getPluginByName('selection');\n * plugin.selectAll(); // Selects everything in current mode\n * ```\n */\n selectAll(): void {\n const mode = this.#mode.primary;\n\n // Single-select mode: selectAll is a no-op\n if (this.config.multiSelect === false) return;\n\n if (mode === 'row') {\n this.selected.clear();\n for (let i = 0; i < this.rows.length; i++) {\n if (this.isRowSelectable(i)) {\n this.selected.add(i);\n }\n }\n this.explicitSelection = true;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n } else if (mode === 'range') {\n const rowCount = this.rows.length;\n const colCount = this.visibleColumns.length;\n if (rowCount > 0 && colCount > 0) {\n const allRange: InternalCellRange = {\n startRow: 0,\n startCol: 0,\n endRow: rowCount - 1,\n endCol: colCount - 1,\n };\n this.ranges = [allRange];\n this.activeRange = allRange;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n }\n }\n\n /**\n * Select specific rows by index (row mode only).\n * Replaces the current selection with the provided row indices.\n * Indices that are out of bounds or fail the `isSelectable` check are ignored.\n *\n * @param indices - Array of row indices to select\n *\n * @example\n * ```ts\n * const plugin = grid.getPluginByName('selection');\n * plugin.selectRows([0, 2, 4]); // Select rows 0, 2, and 4\n * ```\n */\n selectRows(indices: number[]): void {\n if (this.#mode.primary !== 'row') return;\n // In single-select mode, only use the last index\n const effectiveIndices =\n this.config.multiSelect === false && indices.length > 1 ? [indices[indices.length - 1]] : indices;\n this.selected.clear();\n for (const idx of effectiveIndices) {\n if (idx >= 0 && idx < this.rows.length && this.isRowSelectable(idx)) {\n this.selected.add(idx);\n }\n }\n this.anchor = effectiveIndices.length > 0 ? effectiveIndices[effectiveIndices.length - 1] : null;\n this.explicitSelection = true;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Get the indices of all rows touched by the current selection.\n * Returns indices sorted in ascending order.\n *\n * Works across all selection modes:\n * - **Row mode**: The selected row indices.\n * - **Cell mode**: The row index of the selected cell, or `[]`.\n * - **Range mode**: The unique row indices that intersect any selected range.\n *\n * Indices refer to the grid's processed (sorted/filtered) row array.\n *\n * @example\n * ```ts\n * const plugin = grid.getPluginByName('selection');\n * const rows = plugin.getSelectedRowIndices(); // [0, 2, 4]\n * ```\n */\n getSelectedRowIndices(): number[] {\n const mode = this.#mode.primary;\n\n if (mode === 'row') {\n return [...this.selected].sort((a, b) => a - b);\n }\n\n const rowCount = this.rows.length;\n\n if (mode === 'cell' && this.selectedCell) {\n const { row } = this.selectedCell;\n return row >= 0 && row < rowCount ? [row] : [];\n }\n\n if (mode === 'range' && this.ranges.length > 0) {\n // Merge clamped row intervals instead of Set + sort — a select-all range on a\n // large grid is read on every context-menu invocation / drag start (#541).\n const intervals: Array<[number, number]> = [];\n for (const range of this.ranges) {\n const minRow = Math.max(0, Math.min(range.startRow, range.endRow));\n const maxRow = Math.min(rowCount - 1, Math.max(range.startRow, range.endRow));\n if (minRow <= maxRow) intervals.push([minRow, maxRow]);\n }\n intervals.sort((a, b) => a[0] - b[0]);\n const result: number[] = [];\n let next = 0;\n for (const [minRow, maxRow] of intervals) {\n for (let r = Math.max(minRow, next); r <= maxRow; r++) result.push(r);\n next = Math.max(next, maxRow + 1);\n }\n return result;\n }\n\n return [];\n }\n\n /**\n * Get the actual row objects for the current selection.\n *\n * Works across all selection modes:\n * - **Row mode**: Returns the row objects for all selected rows.\n * - **Cell mode**: Returns the single row containing the selected cell, or `[]`.\n * - **Range mode**: Returns the unique row objects that intersect any selected range.\n *\n * Row objects are resolved from the grid's processed (sorted/filtered) row array,\n * so they always reflect the current visual order.\n *\n * @example\n * ```ts\n * const plugin = grid.getPluginByName('selection');\n * const selected = plugin.getSelectedRows(); // [{ id: 1, name: 'Alice' }, ...]\n * ```\n */\n getSelectedRows<T = unknown>(): T[] {\n const rows = this.rows;\n return this.getSelectedRowIndices()\n .filter((i) => i >= 0 && i < rows.length)\n .map((i) => rows[i]) as T[];\n }\n\n /**\n * Replace the entire column-axis selection with `fields` in a single\n * batched operation. Filters out unknown / utility / hidden fields against\n * the current visible columns, updates `selectedColumns` once, sets the\n * anchor/head to the last accepted field (or null when empty), emits\n * `selection-change` exactly once, and schedules a single render.\n *\n * Used by the `selectColumns` plugin query so external callers wiring\n * many fields at once don't pay N×emit + N×requestAfterRender.\n */\n #setColumnSelection(fields: readonly string[]): void {\n if (!this.#mode.columnEnabled) return;\n\n const visible = selectableColumnFields(this.visibleColumns);\n const allowed = new Set(visible);\n // Preserve caller order but de-duplicate and filter unknowns/utility cols.\n const accepted: string[] = [];\n const seen = new Set<string>();\n for (const f of fields) {\n if (!allowed.has(f) || seen.has(f)) continue;\n seen.add(f);\n accepted.push(f);\n }\n\n this.#enforceMutualExclusion('column');\n\n this.selectedColumns.clear();\n for (const f of accepted) this.selectedColumns.add(f);\n const last = accepted.length > 0 ? accepted[accepted.length - 1] : null;\n this.columnAnchor = last;\n this.columnHead = last;\n this.activeAxis = this.selectedColumns.size > 0 ? 'column' : 'none';\n\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Toggle, add, or replace a column in the column-axis selection.\n *\n * Column selection is identified by **field name**, so it survives column\n * pinning, reordering, and virtualization recycling. The column must be\n * present in the grid's visible columns and must not be a utility column.\n *\n * Only available when `mode` includes `'column'`. With `multiSelect: false`,\n * `range`/`toggle` options are ignored and the call always replaces the\n * current selection with the single column.\n *\n * @param field - The column field name to select.\n * @param options.range - When true and a `columnAnchor` exists, selects\n * every column from anchor to `field` inclusive (Ctrl+Shift+Click semantics).\n * @param options.toggle - When true, removes `field` if already selected;\n * otherwise adds it. Without `toggle`, plain calls replace the selection.\n * @since 2.8.0\n */\n selectColumn(field: string, options: { range?: boolean; toggle?: boolean } = {}): void {\n if (!this.#mode.columnEnabled) return;\n const fields = selectableColumnFields(this.visibleColumns);\n if (!fields.includes(field)) return;\n\n this.#enforceMutualExclusion('column');\n\n const multiSelect = this.config.multiSelect !== false;\n if (!multiSelect) {\n this.selectedColumns.clear();\n this.selectedColumns.add(field);\n this.columnAnchor = field;\n this.columnHead = field;\n } else if (options.range && this.columnAnchor) {\n const range = fieldsBetween(this.columnAnchor, field, fields);\n this.selectedColumns.clear();\n for (const f of range) this.selectedColumns.add(f);\n this.columnHead = field;\n } else if (options.toggle) {\n if (this.selectedColumns.has(field)) {\n this.selectedColumns.delete(field);\n } else {\n this.selectedColumns.add(field);\n }\n this.columnAnchor = field;\n this.columnHead = field;\n } else {\n this.selectedColumns.clear();\n this.selectedColumns.add(field);\n this.columnAnchor = field;\n this.columnHead = field;\n }\n\n this.activeAxis = this.selectedColumns.size > 0 ? 'column' : 'none';\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Remove a column from the column-axis selection. No-op if `field` isn't selected.\n * @since 2.8.0\n */\n deselectColumn(field: string): void {\n if (!this.#mode.columnEnabled) return;\n if (!this.selectedColumns.delete(field)) return;\n if (this.selectedColumns.size === 0) {\n this.columnAnchor = null;\n this.columnHead = null;\n if (this.activeAxis === 'column') this.activeAxis = 'none';\n }\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Select every selectable column. No-op when `multiSelect: false` or column\n * mode isn't enabled.\n * @since 2.8.0\n */\n selectAllColumns(): void {\n if (!this.#mode.columnEnabled) return;\n if (this.config.multiSelect === false) return;\n const fields = selectableColumnFields(this.visibleColumns);\n if (fields.length === 0) return;\n this.#enforceMutualExclusion('column');\n this.selectedColumns.clear();\n for (const f of fields) this.selectedColumns.add(f);\n this.columnAnchor = fields[0];\n this.columnHead = fields[fields.length - 1];\n this.activeAxis = 'column';\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Clear column-axis selection only. Leaves any row/cell/range selection intact.\n * @since 2.8.0\n */\n clearColumnSelection(): void {\n if (this.selectedColumns.size === 0) return;\n this.selectedColumns.clear();\n this.columnAnchor = null;\n this.columnHead = null;\n if (this.activeAxis === 'column') this.activeAxis = 'none';\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Get the field names of all currently selected columns, in visible-column\n * order. Returns an empty array when the column axis is inactive or empty.\n * @since 2.8.0\n */\n getSelectedColumns(): readonly string[] {\n if (this.selectedColumns.size === 0) return [];\n const fields = selectableColumnFields(this.visibleColumns);\n return fields.filter((f) => this.selectedColumns.has(f));\n }\n\n /**\n * Clear all selection (every axis).\n */\n clearSelection(): void {\n this.selectedCell = null;\n this.selected.clear();\n this.anchor = null;\n this.ranges = [];\n this.activeRange = null;\n this.cellAnchor = null;\n this.selectedColumns.clear();\n this.columnAnchor = null;\n this.columnHead = null;\n this.activeAxis = 'none';\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n /**\n * Set selected ranges programmatically.\n */\n setRanges(ranges: CellRange[]): void {\n this.ranges = ranges.map((r) => ({\n startRow: r.from.row,\n startCol: r.from.col,\n endRow: r.to.row,\n endCol: r.to.col,\n }));\n this.activeRange = this.ranges.length > 0 ? this.ranges[this.ranges.length - 1] : null;\n this.emit<SelectionChangeDetail>('selection-change', this.#buildEvent());\n this.requestAfterRender();\n }\n\n // #endregion\n\n // #region Private Helpers\n\n #buildEvent(): SelectionChangeDetail {\n // Derive the axis from current state so all existing in-row code paths\n // (which mutate state then emit) report the correct axis without needing\n // to pre-set `this.activeAxis` themselves. Mutual exclusion is enforced\n // separately in {@link #enforceMutualExclusion}.\n const primary = this.#mode.primary;\n const inRowPopulated =\n (primary === 'row' && this.selected.size > 0) ||\n (primary === 'cell' && this.selectedCell !== null) ||\n (primary === 'range' && this.ranges.length > 0);\n\n // Mutual exclusion: in `bothAxes` mode, the user just mutated the in-row\n // axis (we know because `#buildEvent` is called from the in-row code paths\n // immediately after state changes) — so clear stale column selection. The\n // column-axis code paths call `#enforceMutualExclusion('column')`\n // explicitly BEFORE mutating; they then update `activeAxis` to 'column'\n // so the in-row state seen here is empty and this branch doesn't trigger.\n if (this.#mode.bothAxes && inRowPopulated && this.selectedColumns.size > 0) {\n this.selectedColumns.clear();\n this.columnAnchor = null;\n this.columnHead = null;\n if (this.gridElement) {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'selectionAxisChanged', 'row'));\n }\n }\n\n let axis: SelectionAxis;\n if (inRowPopulated) {\n // In-row state always wins when populated — column-axis paths clear\n // in-row state via #enforceMutualExclusion before mutating columns.\n if (primary === 'row') axis = 'row';\n else if (primary === 'cell') axis = 'cell';\n else axis = 'range';\n } else if (this.selectedColumns.size > 0) {\n axis = 'column';\n } else {\n axis = 'none';\n }\n this.activeAxis = axis;\n\n const event = buildSelectionEvent(\n this.config.mode,\n axis,\n primary,\n {\n selectedCell: this.selectedCell,\n selected: this.selected,\n ranges: this.ranges,\n selectedColumns: this.selectedColumns,\n },\n this.columns.length,\n selectableColumnFields(this.visibleColumns),\n );\n // Debounced screen reader announcement for selection changes\n const span = this.#pendingSpanAnnouncement;\n this.#pendingSpanAnnouncement = null;\n if (this.announceTimer) clearTimeout(this.announceTimer);\n this.announceTimer = setTimeout(() => {\n if (span) {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'rangeSpanSelected', span.axis, span.count));\n } else if (event.activeAxis === 'column') {\n const cols = event.selectedColumns;\n if (cols.length === 1) {\n const field = cols[0];\n const col = this.columns.find((c) => c.field === field);\n const label = (typeof col?.header === 'string' && col.header) || field;\n announce(this.gridElement, getA11yMessage(this.gridElement, 'columnSelected', label));\n } else if (cols.length > 1) {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'columnSelectionChanged', cols.length));\n } else {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'columnSelectionCleared'));\n }\n } else {\n const count = event.activeAxis === 'row' ? this.selected.size : event.ranges.length;\n if (count > 0) {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'selectionChanged', count));\n }\n }\n }, 150);\n return event;\n }\n\n /**\n * Enforce row↔column mutual exclusion when both axes are configured\n * (`mode: ['row', 'column']` etc.). Call BEFORE mutating the destination\n * axis so its data won't be wiped along with the inactive axis.\n *\n * Single-string-mode configs are no-ops (the inactive axis can't have data\n * because there's no UI path to populate it). The in-row → column path is\n * called explicitly by the column-axis code; the column → in-row path is\n * handled automatically inside {@link #buildEvent} (which runs on every\n * in-row state change immediately before emitting).\n */\n #enforceMutualExclusion(toAxis: 'row' | 'cell' | 'range' | 'column'): void {\n if (!this.#mode.bothAxes) return;\n if (toAxis === 'column') {\n const hadInRow = this.selected.size > 0 || this.selectedCell !== null || this.ranges.length > 0;\n if (!hadInRow) return;\n this.selected.clear();\n this.lastSelected = null;\n this.anchor = null;\n this.selectedCell = null;\n this.ranges = [];\n this.activeRange = null;\n this.cellAnchor = null;\n if (this.gridElement) {\n announce(this.gridElement, getA11yMessage(this.gridElement, 'selectionAxisChanged', 'column'));\n }\n }\n // Column → in-row flip is handled inside #buildEvent (auto-detected by\n // observing populated in-row state with stale columns).\n }\n\n // #endregion\n}\n"],"mappings":"yB,kGAoCA,IAAaK,EAoBD,WCwJZ,SAAgBC,EAASC,EAAqBC,GAG5C,IAAKD,EAAQ,OAKb,IAAoC,KAHlC,oBAAqBA,EAChBA,EAA0DE,qBAC3D,IACMC,MAAMC,cAAyB,OAE3C,MAAMC,EAAKL,EAAOM,gBAAgB,gBAC7BD,IAELA,EAAGE,YAAc,GAIoB,mBAA1BC,sBACTA,sBAAA,KACEH,EAAGE,YAAcN,IAGnBI,EAAGE,YAAcN,EAErB,CAUA,SAAgBQ,EACdT,EACAU,KACGC,GAOH,MAAMC,GAHJZ,G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