@kumix/ui 0.4.1 → 0.4.2

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 (224) hide show
  1. package/README.md +37 -30
  2. package/dist/{cascader-types-DVT-znZ-.d.ts → cascader-types-zhnUQ4sP.d.ts} +11 -3
  3. package/dist/cascader-types-zhnUQ4sP.d.ts.map +1 -0
  4. package/dist/components/agents/agent-code.js +1 -1
  5. package/dist/components/charts/candlestick-chart/context.d.ts.map +1 -1
  6. package/dist/components/charts/donut-chart/context.d.ts.map +1 -1
  7. package/dist/components/charts/liquidity-heatmap.d.ts.map +1 -1
  8. package/dist/components/charts/order-book.d.ts.map +1 -1
  9. package/dist/components/charts/treemap.d.ts.map +1 -1
  10. package/dist/components/charts/volume-profile.d.ts.map +1 -1
  11. package/dist/components/motion/action-swap.d.ts +1 -1
  12. package/dist/components/motion/action-swap.d.ts.map +1 -1
  13. package/dist/components/motion/action-swap.js +43 -20
  14. package/dist/components/motion/action-swap.js.map +1 -1
  15. package/dist/components/motion/animated-badge.d.ts +1 -1
  16. package/dist/components/motion/animated-badge.d.ts.map +1 -1
  17. package/dist/components/motion/animated-badge.js +60 -101
  18. package/dist/components/motion/animated-badge.js.map +1 -1
  19. package/dist/components/motion/animated-sidebar.js +1 -1
  20. package/dist/components/motion/animated-toast-stack.js +1 -1
  21. package/dist/components/motion/attachment-upload.js +1 -1
  22. package/dist/components/motion/availability-scheduler/copy-menu.js +1 -1
  23. package/dist/components/motion/availability-scheduler/day-row.js +1 -1
  24. package/dist/components/motion/availability-scheduler/index.js +1 -1
  25. package/dist/components/motion/bloom-menu.d.ts.map +1 -1
  26. package/dist/components/motion/bloom-menu.js +73 -8
  27. package/dist/components/motion/bloom-menu.js.map +1 -1
  28. package/dist/components/motion/bottom-sheet.d.ts.map +1 -1
  29. package/dist/components/motion/bottom-sheet.js +6 -10
  30. package/dist/components/motion/bottom-sheet.js.map +1 -1
  31. package/dist/components/motion/bouncy-accordion.d.ts.map +1 -1
  32. package/dist/components/motion/bouncy-accordion.js +35 -22
  33. package/dist/components/motion/bouncy-accordion.js.map +1 -1
  34. package/dist/components/motion/center-morph-modal.js +1 -1
  35. package/dist/components/motion/color-picker.d.ts.map +1 -1
  36. package/dist/components/motion/command-palette.js +1 -1
  37. package/dist/components/motion/context-menu.js +1 -1
  38. package/dist/components/motion/date-range-picker.d.ts.map +1 -1
  39. package/dist/components/motion/drawer.d.ts +1 -1
  40. package/dist/components/motion/drawer.d.ts.map +1 -1
  41. package/dist/components/motion/drawer.js +10 -10
  42. package/dist/components/motion/drawer.js.map +1 -1
  43. package/dist/components/motion/expandable-action-bar.d.ts.map +1 -1
  44. package/dist/components/motion/feedback-widget.js +4 -1
  45. package/dist/components/motion/feedback-widget.js.map +1 -1
  46. package/dist/components/motion/morphing-lightbox.d.ts.map +1 -1
  47. package/dist/components/motion/morphing-lightbox.js +1 -1
  48. package/dist/components/motion/morphing-modal.d.ts +6 -1
  49. package/dist/components/motion/morphing-modal.d.ts.map +1 -1
  50. package/dist/components/motion/morphing-modal.js +37 -5
  51. package/dist/components/motion/morphing-modal.js.map +1 -1
  52. package/dist/components/motion/morphing-search.js +1 -1
  53. package/dist/components/motion/morphing-tabs.js +1 -1
  54. package/dist/components/motion/otp-input.js +19 -11
  55. package/dist/components/motion/otp-input.js.map +1 -1
  56. package/dist/components/motion/popover-morph.d.ts +4 -3
  57. package/dist/components/motion/popover-morph.d.ts.map +1 -1
  58. package/dist/components/motion/popover-morph.js +47 -55
  59. package/dist/components/motion/popover-morph.js.map +1 -1
  60. package/dist/components/motion/popover.js +7 -1
  61. package/dist/components/motion/popover.js.map +1 -1
  62. package/dist/components/motion/prediction-market-card.js +1 -1
  63. package/dist/components/motion/prediction-market.js +1 -1
  64. package/dist/components/motion/project-folder.js +1 -1
  65. package/dist/components/motion/radio.d.ts +5 -1
  66. package/dist/components/motion/radio.d.ts.map +1 -1
  67. package/dist/components/motion/radio.js +53 -5
  68. package/dist/components/motion/radio.js.map +1 -1
  69. package/dist/components/motion/select-morph.d.ts +1 -1
  70. package/dist/components/motion/select-morph.d.ts.map +1 -1
  71. package/dist/components/motion/select-morph.js +89 -21
  72. package/dist/components/motion/select-morph.js.map +1 -1
  73. package/dist/components/motion/select.d.ts.map +1 -1
  74. package/dist/components/motion/select.js +153 -135
  75. package/dist/components/motion/select.js.map +1 -1
  76. package/dist/components/motion/shader-background.d.ts +3 -2
  77. package/dist/components/motion/shader-background.d.ts.map +1 -1
  78. package/dist/components/motion/shader-background.js +9 -3
  79. package/dist/components/motion/shader-background.js.map +1 -1
  80. package/dist/components/motion/shared-layout-bg.d.ts.map +1 -1
  81. package/dist/components/motion/shared-layout-bg.js +17 -3
  82. package/dist/components/motion/shared-layout-bg.js.map +1 -1
  83. package/dist/components/motion/swipeable-list.d.ts.map +1 -1
  84. package/dist/components/motion/swipeable-list.js +61 -4
  85. package/dist/components/motion/swipeable-list.js.map +1 -1
  86. package/dist/components/motion/table/row-handle.js +1 -1
  87. package/dist/components/motion/table/table-header.js +1 -1
  88. package/dist/components/motion/tabs.d.ts +12 -3
  89. package/dist/components/motion/tabs.d.ts.map +1 -1
  90. package/dist/components/motion/tabs.js +248 -26
  91. package/dist/components/motion/tabs.js.map +1 -1
  92. package/dist/components/motion/theme-toggle.js +1 -1
  93. package/dist/components/reui/alert.d.ts +1 -1
  94. package/dist/components/reui/autocomplete.d.ts +1 -1
  95. package/dist/components/reui/autocomplete.d.ts.map +1 -1
  96. package/dist/components/reui/autocomplete.js +1 -1
  97. package/dist/components/reui/autocomplete.js.map +1 -1
  98. package/dist/components/reui/badge.d.ts +2 -2
  99. package/dist/components/reui/cascader/cascader-async.d.ts +21 -5
  100. package/dist/components/reui/cascader/cascader-async.d.ts.map +1 -1
  101. package/dist/components/reui/cascader/cascader-async.js +61 -34
  102. package/dist/components/reui/cascader/cascader-async.js.map +1 -1
  103. package/dist/components/reui/cascader/cascader-columns.d.ts.map +1 -1
  104. package/dist/components/reui/cascader/cascader-columns.js +5 -2
  105. package/dist/components/reui/cascader/cascader-columns.js.map +1 -1
  106. package/dist/components/reui/cascader/cascader-context.d.ts +3 -1
  107. package/dist/components/reui/cascader/cascader-context.d.ts.map +1 -1
  108. package/dist/components/reui/cascader/cascader-context.js.map +1 -1
  109. package/dist/components/reui/cascader/cascader-i18n.d.ts +1 -1
  110. package/dist/components/reui/cascader/cascader-item.d.ts +1 -1
  111. package/dist/components/reui/cascader/cascader-lib.d.ts +34 -8
  112. package/dist/components/reui/cascader/cascader-lib.d.ts.map +1 -1
  113. package/dist/components/reui/cascader/cascader-lib.js +145 -29
  114. package/dist/components/reui/cascader/cascader-lib.js.map +1 -1
  115. package/dist/components/reui/cascader/cascader-nav.d.ts +1 -1
  116. package/dist/components/reui/cascader/cascader-types.d.ts +1 -1
  117. package/dist/components/reui/cascader/cascader.d.ts +13 -8
  118. package/dist/components/reui/cascader/cascader.d.ts.map +1 -1
  119. package/dist/components/reui/cascader/cascader.js +31 -16
  120. package/dist/components/reui/cascader/cascader.js.map +1 -1
  121. package/dist/components/reui/code-block/code-block.d.ts.map +1 -1
  122. package/dist/components/reui/color-picker.js +1 -1
  123. package/dist/components/reui/data-grid/data-grid-cell-selection.d.ts.map +1 -1
  124. package/dist/components/reui/data-grid/data-grid-cell-selection.js +1 -0
  125. package/dist/components/reui/data-grid/data-grid-cell-selection.js.map +1 -1
  126. package/dist/components/reui/data-grid/data-grid-column-filter.d.ts.map +1 -1
  127. package/dist/components/reui/data-grid/data-grid-column-filter.js +1 -0
  128. package/dist/components/reui/data-grid/data-grid-column-filter.js.map +1 -1
  129. package/dist/components/reui/data-grid/data-grid-column-header.d.ts +6 -8
  130. package/dist/components/reui/data-grid/data-grid-column-header.d.ts.map +1 -1
  131. package/dist/components/reui/data-grid/data-grid-column-header.js +7 -8
  132. package/dist/components/reui/data-grid/data-grid-column-header.js.map +1 -1
  133. package/dist/components/reui/data-grid/data-grid-column-visibility.d.ts.map +1 -1
  134. package/dist/components/reui/data-grid/data-grid-column-visibility.js +1 -0
  135. package/dist/components/reui/data-grid/data-grid-column-visibility.js.map +1 -1
  136. package/dist/components/reui/data-grid/data-grid-pagination.d.ts.map +1 -1
  137. package/dist/components/reui/data-grid/data-grid-pagination.js +1 -0
  138. package/dist/components/reui/data-grid/data-grid-pagination.js.map +1 -1
  139. package/dist/components/reui/data-grid/data-grid-scroll-area.d.ts.map +1 -1
  140. package/dist/components/reui/data-grid/data-grid-scroll-area.js +1 -0
  141. package/dist/components/reui/data-grid/data-grid-scroll-area.js.map +1 -1
  142. package/dist/components/reui/data-grid/data-grid-table-dnd-rows.d.ts.map +1 -1
  143. package/dist/components/reui/data-grid/data-grid-table-dnd-rows.js +3 -2
  144. package/dist/components/reui/data-grid/data-grid-table-dnd-rows.js.map +1 -1
  145. package/dist/components/reui/data-grid/data-grid-table-dnd.d.ts.map +1 -1
  146. package/dist/components/reui/data-grid/data-grid-table-dnd.js +2 -1
  147. package/dist/components/reui/data-grid/data-grid-table-dnd.js.map +1 -1
  148. package/dist/components/reui/data-grid/data-grid-table-virtual.d.ts.map +1 -1
  149. package/dist/components/reui/data-grid/data-grid-table-virtual.js +2 -1
  150. package/dist/components/reui/data-grid/data-grid-table-virtual.js.map +1 -1
  151. package/dist/components/reui/data-grid/data-grid-table.d.ts +6 -11
  152. package/dist/components/reui/data-grid/data-grid-table.d.ts.map +1 -1
  153. package/dist/components/reui/data-grid/data-grid-table.js +22 -22
  154. package/dist/components/reui/data-grid/data-grid-table.js.map +1 -1
  155. package/dist/components/reui/data-grid/data-grid.d.ts +16 -1
  156. package/dist/components/reui/data-grid/data-grid.d.ts.map +1 -1
  157. package/dist/components/reui/data-grid/data-grid.js +80 -22
  158. package/dist/components/reui/data-grid/data-grid.js.map +1 -1
  159. package/dist/components/reui/date-selector.d.ts.map +1 -1
  160. package/dist/components/reui/date-selector.js +21 -15
  161. package/dist/components/reui/date-selector.js.map +1 -1
  162. package/dist/components/reui/event-calendar/event-calendar-agenda-view.js +3 -5
  163. package/dist/components/reui/event-calendar/event-calendar-agenda-view.js.map +1 -1
  164. package/dist/components/reui/event-calendar/event-calendar-nav.d.ts.map +1 -1
  165. package/dist/components/reui/event-calendar/event-calendar-nav.js +2 -2
  166. package/dist/components/reui/event-calendar/event-calendar-nav.js.map +1 -1
  167. package/dist/components/reui/event-calendar/event-calendar.d.ts.map +1 -1
  168. package/dist/components/reui/event-calendar/event-calendar.js +34 -31
  169. package/dist/components/reui/event-calendar/event-calendar.js.map +1 -1
  170. package/dist/components/reui/file-type.d.ts +302 -6
  171. package/dist/components/reui/file-type.d.ts.map +1 -1
  172. package/dist/components/reui/file-type.js +416 -13
  173. package/dist/components/reui/file-type.js.map +1 -1
  174. package/dist/components/reui/filters/filters-builder.d.ts +1 -1
  175. package/dist/components/reui/filters/filters-lib.d.ts +1 -1
  176. package/dist/components/reui/frame.d.ts +1 -1
  177. package/dist/components/reui/gantt/gantt-nav.d.ts.map +1 -1
  178. package/dist/components/reui/gantt/gantt-nav.js +2 -2
  179. package/dist/components/reui/gantt/gantt-nav.js.map +1 -1
  180. package/dist/components/reui/gantt/gantt.d.ts.map +1 -1
  181. package/dist/components/reui/gantt/gantt.js +5 -2
  182. package/dist/components/reui/gantt/gantt.js.map +1 -1
  183. package/dist/components/reui/icon-tile.d.ts +2 -2
  184. package/dist/components/reui/number-field.d.ts +3 -3
  185. package/dist/components/reui/phone-input.js +30 -27
  186. package/dist/components/reui/phone-input.js.map +1 -1
  187. package/dist/components/reui/rating.d.ts +1 -1
  188. package/dist/components/reui/time-picker.js +1 -1
  189. package/dist/components/ui/attachment.d.ts +2 -2
  190. package/dist/components/ui/badge.d.ts +1 -1
  191. package/dist/components/ui/bubble.d.ts +1 -1
  192. package/dist/components/ui/button.d.ts +2 -2
  193. package/dist/components/ui/chart.d.ts.map +1 -1
  194. package/dist/components/ui/code-block.d.ts +29 -0
  195. package/dist/components/ui/code-block.d.ts.map +1 -0
  196. package/dist/components/ui/code-block.js +124 -0
  197. package/dist/components/ui/code-block.js.map +1 -0
  198. package/dist/components/ui/empty.d.ts +1 -1
  199. package/dist/components/ui/item.d.ts +2 -2
  200. package/dist/components/ui/marker.d.ts +1 -1
  201. package/dist/components/ui/sidebar.d.ts +1 -1
  202. package/dist/components/ui/toggle.d.ts +1 -1
  203. package/dist/components/ui/trace.d.ts +21 -0
  204. package/dist/components/ui/trace.d.ts.map +1 -0
  205. package/dist/components/ui/trace.js +77 -0
  206. package/dist/components/ui/trace.js.map +1 -0
  207. package/dist/context-BYXeJQnz.d.ts.map +1 -1
  208. package/dist/{copy-menu-BXUh52bu.js → copy-menu-DOg9Jh-U.js} +2 -2
  209. package/dist/{copy-menu-BXUh52bu.js.map → copy-menu-DOg9Jh-U.js.map} +1 -1
  210. package/dist/hooks/use-focus-trap.d.ts +22 -0
  211. package/dist/hooks/use-focus-trap.d.ts.map +1 -0
  212. package/dist/hooks/use-focus-trap.js +80 -0
  213. package/dist/hooks/use-focus-trap.js.map +1 -0
  214. package/dist/hooks/use-highlighted-code.d.ts +5 -0
  215. package/dist/hooks/use-highlighted-code.d.ts.map +1 -0
  216. package/dist/hooks/use-highlighted-code.js +128 -0
  217. package/dist/hooks/use-highlighted-code.js.map +1 -0
  218. package/dist/hooks/use-listbox.d.ts +29 -0
  219. package/dist/hooks/use-listbox.d.ts.map +1 -0
  220. package/dist/hooks/use-listbox.js +75 -0
  221. package/dist/hooks/use-listbox.js.map +1 -0
  222. package/dist/tooltip-C01qUgsW.d.ts.map +1 -1
  223. package/package.json +8 -8
  224. package/dist/cascader-types-DVT-znZ-.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"data-grid-cell-selection.js","names":[],"sources":["../../../../src/components/reui/data-grid/data-grid-cell-selection.tsx"],"sourcesContent":["\"use client\";\n\nimport type {\n CSSProperties,\n KeyboardEvent as ReactKeyboardEvent,\n ReactNode,\n RefObject,\n} from \"react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { Subscribe } from \"@tanstack/react-table\";\nimport { createPortal } from \"react-dom\";\n\nimport { cn } from \"@kumix/utils\";\nimport { Button } from \"../../ui/button\";\nimport type {\n DataGridCellChange,\n DataGridCellRejection,\n DataGridCellsChangeDetails,\n DataGridColumnCellEdit,\n DataGridTableInstance,\n} from \"./data-grid\";\nimport { useDataGrid } from \"./data-grid\";\n\n/** Where a finished edit sends the focused cell, or null to stay. */\ntype DataGridEditorAdvance = \"down\" | \"up\" | \"right\" | \"left\" | null;\n\ninterface DataGridFocusCellOptions {\n /** Also open the cell's editor, the way Enter would. */\n edit?: boolean;\n}\n\n/** Imperative surface of the cell-selection controller. */\ninterface DataGridCellSelectionApi {\n /**\n * Moves the grid's cell focus AND the document focus together, retrying\n * briefly while the row mounts, so a freshly created row is typeable\n * without an extra click. `edit: true` also opens the cell's editor the\n * way Enter would. Registered once the controller is wired; null while\n * cell selection is off.\n */\n focusCell: (rowId: string, columnId: string, options?: DataGridFocusCellOptions) => void;\n /** Clears every range and the focused cell. */\n clearSelection: () => void;\n /** Scrolls a rendered cell into view without moving focus. */\n scrollToCell: (rowId: string, columnId: string) => void;\n}\n\n/** One open built-in editor: which cell, which control, and its text. */\ninterface DataGridEditorSession {\n rowId: string;\n columnId: string;\n control: \"text\" | \"textarea\";\n /** What the editor opens with: the typed seed or the formatted value. */\n initialValue: string;\n /** The formatted current value; an unchanged commit dispatches nothing. */\n baseline: string;\n /** Accessible name for the overlay control, from the column's header. */\n label: string;\n}\n\n/* ------------------------------------------------------------------------- *\n * Clipboard text: pure, node-testable.\n * ------------------------------------------------------------------------- */\n\nfunction serializeDataGridClipboardField(field: string): string {\n // Excel and Sheets quote a field containing a delimiter and double inner\n // quotes; everything else ships bare.\n return /[\\t\\n\\r\"]/.test(field) ? `\"${field.replaceAll('\"', '\"\"')}\"` : field;\n}\n\n/** Row-major grid to TSV, CRLF rows, Excel-style quoting. */\nfunction serializeDataGridClipboardText(grid: string[][]): string {\n return grid.map((line) => line.map(serializeDataGridClipboardField).join(\"\\t\")).join(\"\\r\\n\");\n}\n\n/**\n * TSV to a row-major grid. A stateful scan, not a split: a quoted field may\n * contain tabs, quotes and both newline flavors, which is exactly what Excel\n * emits for a multi-line cell.\n */\nfunction parseDataGridClipboardText(text: string): string[][] {\n const rows: string[][] = [];\n let row: string[] = [];\n let field = \"\";\n let quoted = false;\n let i = 0;\n\n while (i < text.length) {\n const ch = text[i]!;\n if (quoted) {\n if (ch === '\"') {\n if (text[i + 1] === '\"') {\n field += '\"';\n i += 2;\n continue;\n }\n quoted = false;\n i += 1;\n continue;\n }\n field += ch;\n i += 1;\n continue;\n }\n if (ch === '\"' && field === \"\") {\n quoted = true;\n i += 1;\n continue;\n }\n if (ch === \"\\t\") {\n row.push(field);\n field = \"\";\n i += 1;\n continue;\n }\n if (ch === \"\\r\" || ch === \"\\n\") {\n if (ch === \"\\r\" && text[i + 1] === \"\\n\") i += 1;\n row.push(field);\n rows.push(row);\n row = [];\n field = \"\";\n i += 1;\n continue;\n }\n field += ch;\n i += 1;\n }\n row.push(field);\n rows.push(row);\n\n // Excel terminates the payload with one newline; that final empty line is\n // an artifact of the format, not a data row.\n const last = rows[rows.length - 1];\n if (rows.length > 1 && last?.length === 1 && last[0] === \"\") rows.pop();\n\n return rows;\n}\n\n/** Repeats a block cyclically to fill rowCount x columnCount. */\nfunction tileDataGridClipboardBlock(\n block: string[][],\n rowCount: number,\n columnCount: number,\n): string[][] {\n const tiled: string[][] = [];\n for (let r = 0; r < rowCount; r++) {\n const source = block[r % block.length] ?? [];\n const line: string[] = [];\n for (let c = 0; c < columnCount; c++) {\n line.push(source[c % (source.length || 1)] ?? \"\");\n }\n tiled.push(line);\n }\n return tiled;\n}\n\nfunction escapeDataGridClipboardHtml(value: string): string {\n return value.replaceAll(\"&\", \"&amp;\").replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\");\n}\n\n// A minimal text/html flavor alongside the TSV keeps type fidelity when the\n// paste target is Excel or Sheets. Newlines inside a field become <br>, the\n// HTML representation of a multi-line cell; raw newlines would collapse to\n// spaces on paste.\nfunction renderDataGridClipboardHtml(grid: string[][]): string {\n const body = grid\n .map(\n (line) =>\n \"<tr>\" +\n line\n .map(\n (field) =>\n `<td>${escapeDataGridClipboardHtml(field).replace(/\\r\\n|\\r|\\n/g, \"<br>\")}</td>`,\n )\n .join(\"\") +\n \"</tr>\",\n )\n .join(\"\");\n return `<table><tbody>${body}</tbody></table>`;\n}\n\n/* ------------------------------------------------------------------------- *\n * Selection geometry: walks in the feature's own index space.\n * ------------------------------------------------------------------------- */\n\n/**\n * Columns in render order, the same [start, center, end] space\n * cellSelectionFeature resolves its bounds against.\n */\nfunction getDataGridDisplayOrderedColumns<TData extends object>(\n table: DataGridTableInstance<TData>,\n) {\n return [\n ...table.getStartVisibleLeafColumns(),\n ...table.getCenterVisibleLeafColumns(),\n ...table.getEndVisibleLeafColumns(),\n ];\n}\n\nfunction getDataGridWritableCellEdit<TData extends object>(\n column: {\n columnDef: { meta?: { cellEdit?: DataGridColumnCellEdit<TData> } };\n },\n /**\n * The row a write targets. Function-form `editable` is evaluated against\n * it; without a row the column counts as writable in principle, the\n * coarse check the fill preview's column filter uses.\n */\n row?: TData,\n): DataGridColumnCellEdit<TData> | null {\n const cellEdit = column.columnDef.meta?.cellEdit;\n if (!cellEdit || cellEdit.editable === false) return null;\n if (typeof cellEdit.editable === \"function\" && row !== undefined && !cellEdit.editable(row)) {\n return null;\n }\n return cellEdit;\n}\n\n/**\n * Ids of the rows the view can actually show: the page slice plus rows the\n * DOM renders outside it (pinned rows under keepPinnedRows). Selection\n * bounds live in pre-paginated display order, so a range whose corners are\n * both visible can still span off-page rows in between - a page-boundary\n * range to a bottom-pinned draft is the standing example. Every batch walk\n * (copy, clear, paste, fill) filters rows through this set so the cells a\n * batch touches are exactly the cells the selection paints.\n */\nfunction getDataGridRenderedRowIds<TData extends object>(\n table: DataGridTableInstance<TData>,\n viewport: HTMLElement | null | undefined,\n): Set<string> | null {\n if (!viewport) return null;\n // When the page slice covers the whole display order (manual pagination,\n // virtualization, no pagination) no row can be off-page: skip the walk.\n if (table.getRowModel().rows.length === table.getRowsInDisplayOrder().length) {\n return null;\n }\n const rendered = new Set<string>(table.getRowModel().rows.map((row: { id: string }) => row.id));\n for (const rowEl of Array.from(viewport.querySelectorAll(\"tbody tr[data-row-id]\"))) {\n const id = rowEl.getAttribute(\"data-row-id\");\n if (id) rendered.add(id);\n }\n return rendered;\n}\n\n/**\n * Cells of the current selection the view can actually show, under the\n * same row filter the batch builders use, so a count shown next to the\n * selection always matches what is painted and what a batch will touch.\n * The feature's own getSelectedCellCount spans off-page rows instead.\n */\nfunction getDataGridVisibleSelectedCellCount<TData extends object>(\n table: DataGridTableInstance<TData>,\n /** The grid's body viewport; null falls back to the full-range count. */\n viewport: HTMLElement | null,\n): number {\n const bounds = table.getCellSelectionBounds();\n if (!bounds.length) return 0;\n const rows = table.getRowsInDisplayOrder();\n const columns = getDataGridDisplayOrderedColumns(table);\n const rendered = getDataGridRenderedRowIds(table, viewport);\n let count = 0;\n for (const bound of bounds) {\n let rowCount = 0;\n for (let r = bound.minRowIndex; r <= bound.maxRowIndex; r++) {\n const row = rows[r];\n if (row && (!rendered || rendered.has(row.id))) rowCount += 1;\n }\n let columnCount = 0;\n for (let c = bound.minColumnIndex; c <= bound.maxColumnIndex; c++) {\n const column = columns[c];\n if (column && column.columnDef.enableCellSelection !== false) {\n columnCount += 1;\n }\n }\n count += rowCount * columnCount;\n }\n return count;\n}\n\n/**\n * The bound of the ACTIVE (most recent) region. getCellSelectionBounds()\n * sorts geometrically, so its last entry is merely the bottom-right\n * rectangle; the focused cell anchors the newest range, so the bound\n * containing it is the active one. Falls back to the geometric last when\n * the focused cell sits in no bound (the newest range was an exclude).\n */\nfunction getDataGridActiveBound<TData extends object>(table: DataGridTableInstance<TData>) {\n const bounds = table.getCellSelectionBounds();\n if (!bounds.length) return null;\n const focused = table.getFocusedCell();\n if (focused) {\n // O(1): v9 caches the display index on the row itself.\n const rowIndex = focused.row.getDisplayIndex();\n const columnIndex = getDataGridDisplayOrderedColumns(table).findIndex(\n (column) => column.id === focused.column.id,\n );\n const containing = bounds.find(\n (bound) =>\n rowIndex >= bound.minRowIndex &&\n rowIndex <= bound.maxRowIndex &&\n columnIndex >= bound.minColumnIndex &&\n columnIndex <= bound.maxColumnIndex,\n );\n if (containing) return containing;\n }\n return bounds[bounds.length - 1] ?? null;\n}\n\n/**\n * Resolves the cell one visual step away from a given cell: selectable\n * columns for horizontal, RENDERED row order for vertical. The feature's\n * own move/extend resolve rows through the page slice and stall on pinned\n * rows (a bottom-pinned draft), while id-addressed cells work everywhere.\n * \"edge\" means the step is at the grid boundary; null means the position\n * is not resolvable here and the caller should use the feature's move.\n */\nfunction getDataGridStepTarget<TData extends object>(\n table: DataGridTableInstance<TData>,\n viewport: HTMLElement,\n from: { rowId: string; columnId: string },\n direction: \"up\" | \"down\" | \"left\" | \"right\",\n): { rowId: string; columnId: string } | \"edge\" | null {\n if (direction === \"left\" || direction === \"right\") {\n const selectable = getDataGridDisplayOrderedColumns(table).filter(\n (column) => column.columnDef.enableCellSelection !== false,\n );\n const index = selectable.findIndex((column) => column.id === from.columnId);\n if (index === -1) return null;\n const next = selectable[index + (direction === \"right\" ? 1 : -1)];\n return next ? { rowId: from.rowId, columnId: next.id } : \"edge\";\n }\n const renderedIds = Array.from(viewport.querySelectorAll(\"tbody tr[data-row-id]\")).map((row) =>\n row.getAttribute(\"data-row-id\"),\n );\n const index = renderedIds.indexOf(from.rowId);\n if (index === -1) return null;\n const nextId = renderedIds[index + (direction === \"down\" ? 1 : -1)];\n return nextId ? { rowId: nextId, columnId: from.columnId } : \"edge\";\n}\n\n/**\n * Shift+Arrow: the feature keeps focus on the anchor and grows the range\n * from its active corner. When its own extend cannot resolve the step\n * (the active corner sits on a pinned row, or the next visual row is a\n * pinned row outside the page slice), re-derive the active corner from\n * the bounds and step it in visual space through selectCellRange.\n */\nfunction extendDataGridSelection<TData extends object>(\n table: DataGridTableInstance<TData>,\n viewport: HTMLElement,\n direction: \"up\" | \"down\" | \"left\" | \"right\",\n): { rowId: string; columnId: string } | null {\n // The range's active corner: focus stays the anchor, so the corner is\n // the bound's opposite one. Returned to the caller so the view can\n // follow the growing edge rather than the anchor.\n const activeCorner = () => {\n const focused = table.getFocusedCell();\n if (!focused) return null;\n const bound = getDataGridActiveBound(table);\n if (!bound) return null;\n const rows = table.getRowsInDisplayOrder();\n const allColumns = getDataGridDisplayOrderedColumns(table);\n const rowIndex = focused.row.getDisplayIndex();\n const columnIndex = allColumns.findIndex((column) => column.id === focused.column.id);\n return {\n rowId:\n rows[rowIndex === bound.minRowIndex ? bound.maxRowIndex : bound.minRowIndex]?.id ??\n focused.row.id,\n columnId:\n allColumns[\n columnIndex === bound.minColumnIndex ? bound.maxColumnIndex : bound.minColumnIndex\n ]?.id ?? focused.column.id,\n };\n };\n const boundKey = () => {\n const bounds = table.getCellSelectionBounds();\n const bound = bounds[bounds.length - 1];\n return bound\n ? `${bounds.length}:${bound.minRowIndex}-${bound.maxRowIndex}:${bound.minColumnIndex}-${bound.maxColumnIndex}`\n : \"none\";\n };\n const before = boundKey();\n table.extendCellSelection(direction);\n if (boundKey() !== before) return activeCorner();\n const focused = table.getFocusedCell();\n if (!focused) return null;\n const active = activeCorner() ?? {\n rowId: focused.row.id,\n columnId: focused.column.id,\n };\n const target = getDataGridStepTarget(table, viewport, active, direction);\n if (!target || target === \"edge\") return null;\n table.selectCellRange(\n {\n anchorRowId: focused.row.id,\n anchorColumnId: focused.column.id,\n focusRowId: target.rowId,\n focusColumnId: target.columnId,\n },\n { mode: \"replace\" },\n );\n return target;\n}\n\n/**\n * The active region as formatted strings, row-major. Columns opted out of\n * selection are compacted away, matching the feature's own ranges-data\n * behavior, and rows the view cannot show are skipped when a viewport is\n * given. Null when nothing is selected.\n */\nfunction getDataGridActiveRegionGrid<TData extends object>(\n table: DataGridTableInstance<TData>,\n viewport?: HTMLElement | null,\n): string[][] | null {\n const bound = getDataGridActiveBound(table);\n if (!bound) return null;\n\n const rows = table.getRowsInDisplayOrder();\n const columns = getDataGridDisplayOrderedColumns(table);\n const rendered = getDataGridRenderedRowIds(table, viewport);\n const grid: string[][] = [];\n\n for (let r = bound.minRowIndex; r <= bound.maxRowIndex; r++) {\n const row = rows[r];\n if (!row || (rendered && !rendered.has(row.id))) continue;\n const cells = row.getAllCellsByColumnId();\n const line: string[] = [];\n for (let c = bound.minColumnIndex; c <= bound.maxColumnIndex; c++) {\n const column = columns[c];\n if (!column || column.columnDef.enableCellSelection === false) continue;\n const value = cells[column.id]?.getValue();\n const format = column.columnDef.meta?.cellEdit?.format;\n line.push(format ? format(value, row.original) : String(value ?? \"\"));\n }\n grid.push(line);\n }\n\n return grid.length ? grid : null;\n}\n\n/**\n * A clear/cut batch over the selection's writable cells. Non-writable columns\n * are skipped silently: clearing is an intent over what the grid owns, and a\n * rejection per read-only cell would be noise. Null when nothing clears.\n */\nfunction buildDataGridClearDetails<TData extends object>(\n table: DataGridTableInstance<TData>,\n source: \"clear\" | \"cut\",\n activeRegionOnly: boolean,\n viewport?: HTMLElement | null,\n): DataGridCellsChangeDetails<TData> | null {\n const allBounds = table.getCellSelectionBounds();\n const activeBound = getDataGridActiveBound(table);\n const bounds = activeRegionOnly ? (activeBound ? [activeBound] : []) : allBounds;\n if (!bounds.length) return null;\n\n const rows = table.getRowsInDisplayOrder();\n const columns = getDataGridDisplayOrderedColumns(table);\n const rendered = getDataGridRenderedRowIds(table, viewport);\n const changes: DataGridCellChange<TData>[] = [];\n\n for (const bound of bounds) {\n for (let r = bound.minRowIndex; r <= bound.maxRowIndex; r++) {\n const row = rows[r];\n if (!row || (rendered && !rendered.has(row.id))) continue;\n const cells = row.getAllCellsByColumnId();\n for (let c = bound.minColumnIndex; c <= bound.maxColumnIndex; c++) {\n const column = columns[c];\n if (!column || column.columnDef.enableCellSelection === false) continue;\n const cellEdit = getDataGridWritableCellEdit<TData>(column, row.original);\n if (!cellEdit) continue;\n changes.push({\n rowId: row.id,\n columnId: column.id,\n row: row.original,\n previousValue: cells[column.id]?.getValue(),\n value: cellEdit.clearValue ?? null,\n });\n }\n }\n }\n\n return changes.length ? { source, changes, rejected: [] } : null;\n}\n\ntype DataGridPasteTarget = {\n /** Display indexes of the pasted region's first and last row. */\n startRowIndex: number;\n endRowIndex: number;\n /** How many rows a paste actually wrote (hidden rows are skipped). */\n rowCount?: number;\n /** Display indexes of the pasted region's first and last column. */\n startColumnIndex: number;\n endColumnIndex: number;\n};\n\n/**\n * Resolves a parsed clipboard block into a paste batch, Excel semantics:\n * a 1x1 block fills the whole selected region; a block tiles when the region\n * is an exact multiple of it; otherwise it pastes once from the region's\n * top-left, clamped at the grid edges (rows are never grown).\n */\nfunction buildDataGridPasteDetails<TData extends object>(\n table: DataGridTableInstance<TData>,\n block: string[][],\n viewport?: HTMLElement | null,\n): {\n details: DataGridCellsChangeDetails<TData>;\n target: DataGridPasteTarget;\n} | null {\n if (!block.length) return null;\n const bound = getDataGridActiveBound(table);\n if (!bound) return null;\n\n const rows = table.getRowsInDisplayOrder();\n const columns = getDataGridDisplayOrderedColumns(table);\n const rendered = getDataGridRenderedRowIds(table, viewport);\n\n // Copy COMPACTS opt-out columns away, so paste maps block columns over the\n // same compacted space: selectable columns only, starting at the region's\n // first selectable column and running past the region for a wider block,\n // clamped at the grid edge. Walking raw display offsets instead would let\n // an interior opt-out column swallow a block column silently.\n const targetColumns: Array<{\n column: (typeof columns)[number];\n displayIndex: number;\n }> = [];\n let regionColumns = 0;\n for (let c = bound.minColumnIndex; c < columns.length; c++) {\n const column = columns[c];\n if (!column || column.columnDef.enableCellSelection === false) continue;\n targetColumns.push({ column, displayIndex: c });\n if (c <= bound.maxColumnIndex) regionColumns += 1;\n }\n if (!regionColumns) return null;\n\n const blockRows = block.length;\n const blockColumns = block.reduce((max, line) => Math.max(max, line.length), 1);\n const regionRows = bound.maxRowIndex - bound.minRowIndex + 1;\n\n let rowCount: number;\n let columnCount: number;\n if (blockRows === 1 && blockColumns === 1) {\n rowCount = regionRows;\n columnCount = regionColumns;\n } else if (regionRows % blockRows === 0 && regionColumns % blockColumns === 0) {\n rowCount = regionRows;\n columnCount = regionColumns;\n } else {\n rowCount = blockRows;\n columnCount = blockColumns;\n }\n\n const tiled = tileDataGridClipboardBlock(block, rowCount, columnCount);\n const startRowIndex = bound.minRowIndex;\n\n // Rows the block maps onto: the next rowCount rows the view can show,\n // starting at the region's top. Off-page rows between a page's tail and\n // a pinned draft are skipped rather than silently written.\n const targetRows: Array<{ row: (typeof rows)[number]; displayIndex: number }> = [];\n for (let r = startRowIndex; r < rows.length; r++) {\n if (targetRows.length === rowCount) break;\n const row = rows[r];\n if (!row || (rendered && !rendered.has(row.id))) continue;\n targetRows.push({ row, displayIndex: r });\n }\n\n const changes: DataGridCellChange<TData>[] = [];\n const rejected: DataGridCellRejection[] = [];\n\n for (let r = 0; r < targetRows.length; r++) {\n const row = targetRows[r]!.row;\n const cells = row.getAllCellsByColumnId();\n for (let c = 0; c < columnCount; c++) {\n const column = targetColumns[c]?.column;\n if (!column) continue;\n const raw = tiled[r]?.[c] ?? \"\";\n const cellEdit = getDataGridWritableCellEdit<TData>(column, row.original);\n if (!cellEdit) {\n rejected.push({\n rowId: row.id,\n columnId: column.id,\n raw,\n reason: \"readonly\",\n });\n continue;\n }\n const value = cellEdit.parse ? cellEdit.parse(raw, row.original) : raw;\n if (value === undefined) {\n rejected.push({\n rowId: row.id,\n columnId: column.id,\n raw,\n reason: \"invalid\",\n });\n continue;\n }\n changes.push({\n rowId: row.id,\n columnId: column.id,\n row: row.original,\n previousValue: cells[column.id]?.getValue(),\n value,\n });\n }\n }\n\n if (!changes.length && !rejected.length) return null;\n const lastTarget = targetColumns[Math.min(columnCount, targetColumns.length) - 1];\n return {\n details: { source: \"paste\", changes, rejected },\n target: {\n startRowIndex,\n endRowIndex: targetRows[targetRows.length - 1]?.displayIndex ?? startRowIndex,\n rowCount: targetRows.length,\n startColumnIndex: targetColumns[0]!.displayIndex,\n endColumnIndex: lastTarget!.displayIndex,\n },\n };\n}\n\n/**\n * The inverse batch: every change's value and previousValue swapped and\n * rejections dropped. Feed it through the same state update onCellsChange\n * uses to implement undo; inverting the inverse is redo.\n */\nfunction invertDataGridCellsChange<TData extends object>(\n details: DataGridCellsChangeDetails<TData>,\n): DataGridCellsChangeDetails<TData> {\n return {\n source: details.source,\n changes: details.changes.map((change) => ({\n ...change,\n value: change.previousValue,\n previousValue: change.value,\n })),\n rejected: [],\n };\n}\n\nfunction selectDataGridRegion<TData extends object>(\n table: DataGridTableInstance<TData>,\n target: DataGridPasteTarget,\n) {\n const rows = table.getRowsInDisplayOrder();\n const columns = getDataGridDisplayOrderedColumns(table);\n const anchorRow = rows[target.startRowIndex];\n const anchorColumn = columns[target.startColumnIndex];\n const focusRow = rows[Math.min(target.endRowIndex, rows.length - 1)];\n const focusColumn = columns[target.endColumnIndex];\n if (!anchorRow || !anchorColumn || !focusRow || !focusColumn) return;\n table.selectCellRange(\n {\n anchorRowId: anchorRow.id,\n anchorColumnId: anchorColumn.id,\n focusRowId: focusRow.id,\n focusColumnId: focusColumn.id,\n },\n { mode: \"replace\" },\n );\n}\n\n/* ------------------------------------------------------------------------- *\n * Fill handle drag session.\n * ------------------------------------------------------------------------- */\n\n/**\n * Imperative document-level session, the column-resize pattern: preview state\n * is written as `data-cell-fill-target` attributes outside React, so the drag\n * costs zero re-renders until release. v1 fills down or right (dominant axis)\n * by repeating the source region's values; rows outside the rendered\n * viewport of a virtualized body cannot be targeted mid-drag.\n *\n * Vertical distance is measured over the rows the view can show, so a drag\n * onto a pinned draft fills exactly the rows the preview marked and never\n * the off-page rows between. A cross-column fill round-trips through the\n * source's format and the target's parse - the paste contract - because\n * adjacent grid columns are heterogeneous; a parse rejection lands in the\n * batch's rejected list, while cells that cannot be written are skipped\n * and never tinted by the preview.\n */\n// The fill drag's feedback: ONE dashed border (the Sheets fill marquee)\n// around the whole pending region - the source PLUS the extension - so the\n// drag reads as one growing region, never as a second box glued under the\n// source. While the session runs\n// the viewport carries data-cell-filling and the source cells' own\n// selection chrome rests, so this element is the only painter and nothing\n// can double at the junction. z-[35]: above the sticky pinned cells\n// (z 30) so the border survives crossing a pinned column; below the\n// sticky header (z-40).\nconst dataGridGestureOutlineClasses =\n \"outline-primary pointer-events-none absolute z-[35] outline-1 outline-dashed -outline-offset-1\";\n\nfunction startDataGridFillSession<TData extends object>(options: {\n table: DataGridTableInstance<TData>;\n viewport: HTMLElement;\n onCellsChange: ((details: DataGridCellsChangeDetails<TData>) => void) | null;\n}) {\n const { table, viewport, onCellsChange } = options;\n // Fill over a multi-region selection is undefined territory; Excel refuses\n // it too.\n if (table.getCellSelectionBounds().length > 1) return;\n const bound = getDataGridActiveBound(table);\n if (!bound) return;\n\n const rows = table.getRowsInDisplayOrder();\n const columns = getDataGridDisplayOrderedColumns(table);\n // The vertical walk space: rows the view can show, in display order. The\n // DOM ids seed it (a drag can only target rendered rows), and one pass\n // over the cached display array resolves them without building per-row\n // wrappers for a 50k-row model.\n const domRowIds = new Set<string>();\n for (const rowEl of Array.from(viewport.querySelectorAll(\"tbody tr[data-row-id]\"))) {\n const id = rowEl.getAttribute(\"data-row-id\");\n if (id) domRowIds.add(id);\n }\n const visibleRows: Array<{ row: (typeof rows)[number]; displayIndex: number }> = [];\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i]!;\n if (domRowIds.has(row.id)) {\n visibleRows.push({ row, displayIndex: i });\n }\n }\n const visibleIndexById = new Map(visibleRows.map((entry, index) => [entry.row.id, index]));\n // The source region and its last row, both in visible space.\n const sourceRows = visibleRows.filter(\n ({ displayIndex }) => displayIndex >= bound.minRowIndex && displayIndex <= bound.maxRowIndex,\n );\n const sourceEndVisibleIndex = sourceRows.length\n ? visibleIndexById.get(sourceRows[sourceRows.length - 1]!.row.id)!\n : -1;\n if (sourceEndVisibleIndex === -1) return;\n const columnIndexById = new Map(columns.map((column, index) => [column.id, index]));\n const isFillableColumn = (column: (typeof columns)[number]) =>\n column.columnDef.enableCellSelection !== false && !!getDataGridWritableCellEdit<TData>(column);\n\n let extension: { axis: \"row\" | \"column\"; count: number } | null = null;\n let previewCells: Element[] = [];\n\n const previewOutline = viewport.ownerDocument.createElement(\"div\");\n previewOutline.setAttribute(\"data-slot\", \"data-grid-cell-fill-preview\");\n previewOutline.className = dataGridGestureOutlineClasses;\n previewOutline.style.display = \"none\";\n viewport.appendChild(previewOutline);\n viewport.setAttribute(\"data-cell-filling\", \"\");\n\n // The region border wraps source plus extension: its corners are the\n // source region's first cell and the farthest cell the drag reaches\n // (the source's own last cell while nothing is extended).\n const sourceCorner = (rowId: string, columnId: string | undefined) =>\n columnId\n ? viewport.querySelector(\n `tr[data-row-id=\"${CSS.escape(rowId)}\"] td[data-col-id=\"${CSS.escape(columnId)}\"]`,\n )\n : null;\n const positionPreviewOutline = () => {\n const first = sourceRows.length\n ? sourceCorner(sourceRows[0]!.row.id, columns[bound.minColumnIndex]?.id)\n : null;\n const lastSource = sourceRows.length\n ? sourceCorner(sourceRows[sourceRows.length - 1]!.row.id, columns[bound.maxColumnIndex]?.id)\n : null;\n const far = previewCells.length ? previewCells[previewCells.length - 1]! : lastSource;\n if (!first || !far) {\n previewOutline.style.display = \"none\";\n return;\n }\n const firstRect = first.getBoundingClientRect();\n const farRect = far.getBoundingClientRect();\n const viewportRect = viewport.getBoundingClientRect();\n const left = Math.min(firstRect.left, farRect.left);\n const top = Math.min(firstRect.top, farRect.top);\n previewOutline.style.display = \"block\";\n previewOutline.style.left = `${left - viewportRect.left + viewport.scrollLeft}px`;\n previewOutline.style.top = `${top - viewportRect.top + viewport.scrollTop}px`;\n previewOutline.style.width = `${Math.max(firstRect.right, farRect.right) - left}px`;\n previewOutline.style.height = `${Math.max(firstRect.bottom, farRect.bottom) - top}px`;\n };\n\n const clearPreview = () => {\n for (const cell of previewCells) cell.removeAttribute(\"data-cell-fill-target\");\n previewCells = [];\n positionPreviewOutline();\n };\n\n // Target rows and columns for the current extension: rows in visible\n // space, and only the columns the commit would actually write, so the\n // preview never tints a cell the release will skip.\n const getExtensionTargets = () => {\n if (!extension) return null;\n const columnEntries = columns.map((column, displayIndex) => ({\n column,\n displayIndex,\n }));\n return extension.axis === \"row\"\n ? {\n rowEntries: visibleRows.slice(\n sourceEndVisibleIndex + 1,\n sourceEndVisibleIndex + 1 + extension.count,\n ),\n columnEntries: columnEntries\n .slice(bound.minColumnIndex, bound.maxColumnIndex + 1)\n .filter(({ column }) => isFillableColumn(column)),\n }\n : {\n rowEntries: sourceRows,\n columnEntries: columnEntries\n .slice(bound.maxColumnIndex + 1, bound.maxColumnIndex + 1 + extension.count)\n .filter(({ column }) => isFillableColumn(column)),\n };\n };\n\n const applyPreview = () => {\n clearPreview();\n const targets = getExtensionTargets();\n if (!targets) return;\n for (const { row } of targets.rowEntries) {\n const rowElement = viewport.querySelector(`tr[data-row-id=\"${CSS.escape(row.id)}\"]`);\n if (!rowElement) continue;\n for (const { column } of targets.columnEntries) {\n if (!getDataGridWritableCellEdit<TData>(column, row.original)) continue;\n const cellElement = rowElement.querySelector(`td[data-col-id=\"${CSS.escape(column.id)}\"]`);\n if (!cellElement) continue;\n cellElement.setAttribute(\"data-cell-fill-target\", \"true\");\n previewCells.push(cellElement);\n }\n }\n\n positionPreviewOutline();\n };\n\n const handleMove = (event: MouseEvent) => {\n const element = document.elementFromPoint(event.clientX, event.clientY);\n const cellElement = element?.closest?.(\"td[data-col-id]\");\n const rowElement = cellElement?.closest?.(\"tr[data-row-id]\");\n if (!cellElement || !rowElement || !viewport.contains(cellElement)) return;\n\n const rowVisibleIndex = visibleIndexById.get(rowElement.getAttribute(\"data-row-id\") ?? \"\");\n const columnIndex = columnIndexById.get(cellElement.getAttribute(\"data-col-id\") ?? \"\");\n if (rowVisibleIndex === undefined || columnIndex === undefined) return;\n\n const rowsDelta = Math.max(0, rowVisibleIndex - sourceEndVisibleIndex);\n const columnsDelta = Math.max(0, columnIndex - bound.maxColumnIndex);\n const next: typeof extension =\n rowsDelta === 0 && columnsDelta === 0\n ? null\n : rowsDelta >= columnsDelta\n ? { axis: \"row\", count: rowsDelta }\n : { axis: \"column\", count: columnsDelta };\n\n if (next?.axis === extension?.axis && next?.count === extension?.count) {\n return;\n }\n extension = next;\n applyPreview();\n };\n\n const finish = (commit: boolean) => {\n document.removeEventListener(\"mousemove\", handleMove);\n document.removeEventListener(\"mouseup\", handleUp);\n document.removeEventListener(\"keydown\", handleKey, true);\n clearPreview();\n previewOutline.remove();\n viewport.removeAttribute(\"data-cell-filling\");\n if (!commit || !extension || !onCellsChange) return;\n const targets = getExtensionTargets();\n if (!targets?.rowEntries.length) return;\n\n const changes: DataGridCellChange<TData>[] = [];\n const rejected: DataGridCellRejection[] = [];\n\n if (extension.axis === \"row\") {\n for (let offset = 0; offset < targets.rowEntries.length; offset++) {\n const targetRow = targets.rowEntries[offset]!.row;\n const sourceRow = sourceRows[offset % sourceRows.length]!.row;\n const targetCells = targetRow.getAllCellsByColumnId();\n const sourceCells = sourceRow.getAllCellsByColumnId();\n for (const { column } of targets.columnEntries) {\n if (!getDataGridWritableCellEdit<TData>(column, targetRow.original)) {\n continue;\n }\n changes.push({\n rowId: targetRow.id,\n columnId: column.id,\n row: targetRow.original,\n previousValue: targetCells[column.id]?.getValue(),\n value: sourceCells[column.id]?.getValue(),\n });\n }\n }\n } else {\n const regionColumns = bound.maxColumnIndex - bound.minColumnIndex + 1;\n for (const { row } of targets.rowEntries) {\n const cells = row.getAllCellsByColumnId();\n for (const { column: targetColumn, displayIndex } of targets.columnEntries) {\n const offset = displayIndex - (bound.maxColumnIndex + 1);\n const sourceColumn = columns[bound.minColumnIndex + (offset % regionColumns)];\n if (!sourceColumn) continue;\n const targetEdit = getDataGridWritableCellEdit<TData>(targetColumn, row.original);\n if (!targetEdit) continue;\n const sourceValue = cells[sourceColumn.id]?.getValue();\n let value: unknown = sourceValue;\n // Crossing columns is a type boundary: round-trip through the\n // source's format and the target's parse, exactly what pasting\n // the same cells would do. Same-column fills keep raw values.\n if (targetColumn.id !== sourceColumn.id && targetEdit.parse) {\n const sourceFormat = sourceColumn.columnDef.meta?.cellEdit?.format;\n const raw = sourceFormat\n ? sourceFormat(sourceValue, row.original)\n : String(sourceValue ?? \"\");\n const parsed = targetEdit.parse(raw, row.original);\n if (parsed === undefined) {\n rejected.push({\n rowId: row.id,\n columnId: targetColumn.id,\n raw,\n reason: \"invalid\",\n });\n continue;\n }\n value = parsed;\n }\n changes.push({\n rowId: row.id,\n columnId: targetColumn.id,\n row: row.original,\n previousValue: cells[targetColumn.id]?.getValue(),\n value,\n });\n }\n }\n }\n\n if (changes.length || rejected.length) {\n onCellsChange({ source: \"fill\", changes, rejected });\n }\n\n // Grow the selection over source plus filled cells, Excel's post-fill\n // shape.\n selectDataGridRegion(table, {\n startRowIndex: bound.minRowIndex,\n endRowIndex:\n extension.axis === \"row\"\n ? targets.rowEntries[targets.rowEntries.length - 1]!.displayIndex\n : bound.maxRowIndex,\n startColumnIndex: bound.minColumnIndex,\n endColumnIndex: bound.maxColumnIndex + (extension.axis === \"column\" ? extension.count : 0),\n });\n };\n\n const handleUp = () => finish(true);\n // Capture phase so a cancel cannot also reach the grid's own Escape\n // handling and clear the selection underneath the drag.\n const handleKey = (event: KeyboardEvent) => {\n if (event.key !== \"Escape\") return;\n event.stopPropagation();\n finish(false);\n };\n\n document.addEventListener(\"mousemove\", handleMove);\n document.addEventListener(\"mouseup\", handleUp);\n document.addEventListener(\"keydown\", handleKey, true);\n}\n\n/* ------------------------------------------------------------------------- *\n * Controller.\n * ------------------------------------------------------------------------- */\n\nfunction isDataGridEditableTarget(target: EventTarget | null): boolean {\n // data-cell-interactive is the same opt-out the mousedown guard honors, so\n // a custom widget keeps its own keys and clipboard as well as its clicks.\n return (\n target instanceof Element &&\n target.closest(\"input, textarea, select, [contenteditable], [data-cell-interactive]\") != null\n );\n}\n\n// Keys belong to a focused in-cell control the same way clicks do: the\n// button, link and checkbox set the mousedown guard exempts must keep its\n// native Enter, Space and Tab, or an in-cell button is keyboard-dead.\n// Clipboard stays on the narrower guard: copying the grid selection while a\n// button happens to hold focus is what a spreadsheet user expects.\nfunction isDataGridInteractiveKeyTarget(target: EventTarget | null): boolean {\n return (\n isDataGridEditableTarget(target) ||\n (target instanceof Element && target.closest('button, a, [role=\"checkbox\"]') != null)\n );\n}\n\n/**\n * Headless spreadsheet controller: keyboard navigation, clipboard, clear and\n * the fill-handle drag. Mount once inside `<DataGrid>`, next to the table.\n * Renders only a hidden anchor; the real listeners attach to the grid's own\n * body viewport, which also receives focus (container-focus model), so a\n * virtualized row unmounting can never strand `document.activeElement`.\n */\nfunction DataGridCellSelection<TData extends object>({\n apiRef,\n clipboard = true,\n keyboard = true,\n}: {\n /** Receives the controller's imperative API, e.g. for create-row flows. */\n apiRef?: RefObject<DataGridCellSelectionApi | null>;\n /** Native copy, cut and paste handling. Defaults to true. */\n clipboard?: boolean;\n /**\n * Arrows (with Ctrl/Cmd edge jumps), Home/End, PageUp/PageDown, Enter,\n * F2, type-to-edit, Tab, Ctrl/Cmd+A, Delete, Escape. Defaults to true.\n */\n keyboard?: boolean;\n}) {\n // The context value serves `table` and `props` through getters over the\n // provider's own refs, so a context object captured at mount keeps handing\n // out the CURRENT instances; no ref mirror is needed here.\n const context = useDataGrid<TData>();\n\n const anchorRef = useRef<HTMLSpanElement | null>(null);\n // The body viewport, once the wiring effect resolves it; the built-in\n // editor overlay portals into it so it scrolls with the cells.\n const [viewportEl, setViewportEl] = useState<HTMLElement | null>(null);\n const [editorSession, setEditorSession] = useState<DataGridEditorSession | null>(null);\n const { table } = context;\n const enabled = !!context.props.tableLayout?.cellSelection && table.atoms.cellSelection != null;\n\n useEffect(() => {\n if (!enabled) return;\n const anchor = anchorRef.current;\n if (!anchor) return;\n\n const root = (anchor.closest('[data-slot=\"data-grid\"]') ??\n anchor.parentElement) as HTMLElement | null;\n if (!root) return;\n\n // Split header/body grids render two viewports; the body one owns focus.\n const viewports = Array.from(\n root.querySelectorAll<HTMLElement>('[data-slot=\"data-grid-table-viewport\"]'),\n );\n const viewport =\n viewports.find((node) => node.querySelector('[data-slot=\"data-grid-table-body\"]')) ??\n viewports[0];\n if (!viewport) return;\n\n const getTable = () => context.table;\n const getOnCellsChange = () => context.props.onCellsChange ?? null;\n // \"single\" collapses every grow gesture to the focused cell.\n const isRangeSelectionEnabled = () => context.props.tableLayout?.cellSelectionMode !== \"single\";\n\n // The focusable element of the container-focus model. The table carries\n // role=\"grid\", so putting DOM focus (and aria-activedescendant) on it is\n // what lets a screen reader follow the focused cell.\n const focusTarget =\n viewport.querySelector<HTMLElement>('table[data-slot=\"data-grid-table\"]') ?? viewport;\n\n const scrollTdIntoView = (cell: Element | null) =>\n // Optional call: jsdom and some embedded contexts ship elements\n // without scrollIntoView.\n cell?.scrollIntoView?.({\n block: \"nearest\",\n inline: \"nearest\",\n behavior: \"instant\",\n });\n\n // Points assistive tech at the virtually focused cell.\n const syncActiveDescendant = () => {\n const cell = viewport.querySelector<HTMLElement>(\"td[data-cell-focused]\");\n if (cell?.id) focusTarget.setAttribute(\"aria-activedescendant\", cell.id);\n else focusTarget.removeAttribute(\"aria-activedescendant\");\n };\n\n const scrollFocusedIntoView = (\n targetRowIndex?: number,\n rowCount?: number,\n // A Shift-extend grows away from the focused cell, which stays the\n // anchor; the caller names the range's active corner so the view\n // follows the growing edge instead of snapping back to the anchor.\n explicitCell?: { rowId: string; columnId: string },\n ) => {\n const queryScrollCell = () =>\n explicitCell\n ? viewport.querySelector(\n `tr[data-row-id=\"${CSS.escape(explicitCell.rowId)}\"] td[data-col-id=\"${CSS.escape(explicitCell.columnId)}\"]`,\n )\n : viewport.querySelector(\"td[data-cell-focused]\");\n // After the atom write React still has to commit the data attributes;\n // rAF lands after that commit. Instant, because the app-level\n // scroll-smooth would otherwise animate every keystroke.\n requestAnimationFrame(() => {\n const cell = queryScrollCell();\n syncActiveDescendant();\n if (cell || targetRowIndex == null || !rowCount) {\n scrollTdIntoView(cell);\n return;\n }\n // Virtualization: the jump target is not mounted, so there is no td\n // to scroll to. The spacer rows keep scrollHeight proportional to\n // the row count, so estimate the offset, let the virtualizer mount\n // the region, then finish with a precise nearest-scroll.\n let scroller: HTMLElement | null = viewport;\n while (scroller && scroller.scrollHeight <= scroller.clientHeight) {\n scroller = scroller.parentElement;\n }\n if (!scroller) return;\n scroller.scrollTop =\n ((targetRowIndex + 0.5) / rowCount) * scroller.scrollHeight - scroller.clientHeight / 2;\n requestAnimationFrame(() => {\n scrollTdIntoView(queryScrollCell());\n syncActiveDescendant();\n });\n });\n };\n\n // Opens an editor for the focused writable cell: the grid's own overlay\n // for a column with a built-in `control`, the consumer's via\n // `onCellEditRequest` otherwise, and as a last resort the cell's own\n // interactive content (activated the way a mouse would). Returns false\n // when nothing can open so the caller falls back to plain navigation.\n const requestCellEdit = (initialText?: string): boolean => {\n const table = getTable();\n const cell = table.getFocusedCell();\n if (!cell) return false;\n const cellEdit = getDataGridWritableCellEdit<TData>(cell.column, cell.row.original);\n if (cellEdit?.control) {\n const baseline = cellEdit.format\n ? cellEdit.format(cell.getValue(), cell.row.original)\n : String(cell.getValue() ?? \"\");\n const headerTitle = cell.column.columnDef.meta?.headerTitle;\n const header = cell.column.columnDef.header;\n setEditorSession({\n rowId: cell.row.id,\n columnId: cell.column.id,\n control: cellEdit.control,\n initialValue: initialText ?? baseline,\n baseline,\n label:\n typeof headerTitle === \"string\"\n ? headerTitle\n : typeof header === \"string\"\n ? header\n : cell.column.id,\n });\n return true;\n }\n const onCellEditRequest = context.props.onCellEditRequest;\n if (cellEdit && onCellEditRequest) {\n onCellEditRequest({\n rowId: cell.row.id,\n columnId: cell.column.id,\n row: cell.row.original,\n previousValue: cell.getValue(),\n initialText,\n });\n return true;\n }\n // Generic activation: a custom control rendered in the cell (a\n // select trigger, a combobox input, a button) toggles from the\n // keyboard without any consumer wiring - focus it and click it,\n // the same gesture the mouse performs. The lookup is ORDERED so an\n // incidental button (a chip's remove button before a combobox\n // input) never outranks the cell's primary control.\n // Deliberate activation only (Enter, F2, double-click): typing a\n // printable character must never toggle a control it cannot type\n // into, and there is nowhere to put the character.\n if (initialText !== undefined) return false;\n const focusedCell = viewport.querySelector(\"td[data-cell-focused]\");\n const control = focusedCell\n ? [\n '[role=\"combobox\"]',\n \"select\",\n \"input, textarea\",\n 'button, a, [role=\"checkbox\"], [tabindex]:not([tabindex=\"-1\"])',\n ]\n .map((candidate) => focusedCell.querySelector<HTMLElement>(candidate))\n .find(Boolean)\n : null;\n if (!control) return false;\n control.focus();\n control.click();\n return true;\n };\n\n // The imperative surface. A consumer that creates a row cannot focus\n // its cell through state alone: setFocusedCell needs the row in the\n // table model, DOM focus needs the focus target, and both race the\n // commit that mounts the row. One bounded timer retry (timers, unlike\n // animation frames, run in background tabs) settles all of it in order.\n let focusRetryTimer: ReturnType<typeof setTimeout> | undefined;\n const focusCell: DataGridCellSelectionApi[\"focusCell\"] = (rowId, columnId, options) => {\n // A newer call supersedes any chain still polling for an older row.\n clearTimeout(focusRetryTimer);\n let attempts = 12;\n const attempt = () => {\n // The grid can unmount mid-retry; a stale timer must go quiet.\n if (!viewport.isConnected) return;\n const cell = viewport.querySelector<HTMLElement>(\n `tr[data-row-id=\"${CSS.escape(rowId)}\"] td[data-col-id=\"${CSS.escape(columnId)}\"]`,\n );\n if (!cell) {\n if (attempts-- > 0) focusRetryTimer = setTimeout(attempt, 32);\n return;\n }\n getTable().setFocusedCell(rowId, columnId);\n focusTarget.focus();\n // The cell's id is static, so assistive tech can point at it ahead\n // of the data-cell-focused commit the rAF sync waits for.\n if (cell.id) focusTarget.setAttribute(\"aria-activedescendant\", cell.id);\n scrollTdIntoView(cell);\n if (!options?.edit) return;\n // The built-in overlay measures td[data-cell-focused], so the edit\n // request waits for that attribute to land.\n let editAttempts = 12;\n const attemptEdit = () => {\n if (!cell.isConnected) return;\n if (cell.hasAttribute(\"data-cell-focused\")) requestCellEdit();\n else if (editAttempts-- > 0) {\n focusRetryTimer = setTimeout(attemptEdit, 32);\n }\n };\n attemptEdit();\n };\n attempt();\n };\n const clearSelection = () => {\n getTable().resetCellSelection(true);\n requestAnimationFrame(syncActiveDescendant);\n };\n const scrollToCell = (rowId: string, columnId: string) => {\n scrollTdIntoView(\n viewport.querySelector(\n `tr[data-row-id=\"${CSS.escape(rowId)}\"] td[data-col-id=\"${CSS.escape(columnId)}\"]`,\n ),\n );\n };\n if (apiRef) apiRef.current = { focusCell, clearSelection, scrollToCell };\n\n // Resolves jump targets (Home, End, Ctrl+Arrows, PageUp/PageDown) in the\n // feature's display-index space and lands them through the range API:\n // plain jumps collapse to the target cell, Shift jumps keep the active\n // range's opposite corner as the anchor, the Excel model.\n const jumpFocus = (\n rowTarget: \"first\" | \"last\" | \"same\" | { delta: number },\n columnTarget: \"first\" | \"last\" | \"same\",\n extend: boolean,\n ): boolean => {\n const table = getTable();\n const focused = table.getFocusedCell();\n if (!focused) return false;\n const rows = table.getRowsInDisplayOrder();\n const allColumns = getDataGridDisplayOrderedColumns(table);\n const selectable = allColumns.filter(\n (column) => column.columnDef.enableCellSelection !== false,\n );\n if (!rows.length || !selectable.length) return false;\n const rowIndex = focused.row.getDisplayIndex();\n const targetRowIndex =\n rowTarget === \"first\"\n ? 0\n : rowTarget === \"last\"\n ? rows.length - 1\n : rowTarget === \"same\"\n ? rowIndex\n : Math.min(rows.length - 1, Math.max(0, rowIndex + rowTarget.delta));\n // Pagination renders a window of the display order; walk the target\n // back toward the focus until it lands on a rendered row, so a jump\n // can never focus an off-page row the view cannot show. DOM rows\n // join the set so pinned rows outside the page slice stay reachable.\n let clampedRowIndex = targetRowIndex;\n // With the whole display order in the page slice nothing is off-page\n // and the clamp cannot move, so skip building the id set.\n if (table.getRowModel().rows.length !== rows.length) {\n const rendered = new Set<string | null>(\n table.getRowModel().rows.map((row: { id: string }) => row.id),\n );\n for (const rowEl of Array.from(viewport.querySelectorAll(\"tbody tr[data-row-id]\"))) {\n rendered.add(rowEl.getAttribute(\"data-row-id\"));\n }\n const step = clampedRowIndex >= rowIndex ? -1 : 1;\n while (\n clampedRowIndex !== rowIndex &&\n rows[clampedRowIndex] &&\n !rendered.has(rows[clampedRowIndex].id)\n ) {\n clampedRowIndex += step;\n }\n }\n const targetRow = rows[clampedRowIndex];\n const targetColumn =\n columnTarget === \"first\"\n ? selectable[0]\n : columnTarget === \"last\"\n ? selectable[selectable.length - 1]\n : focused.column;\n if (!targetRow || !targetColumn) return false;\n if (extend) {\n const bound = getDataGridActiveBound(table);\n const columnIndex = allColumns.findIndex((column) => column.id === focused.column.id);\n let anchorRowId = focused.row.id;\n let anchorColumnId = focused.column.id;\n if (bound) {\n anchorRowId =\n rows[rowIndex === bound.minRowIndex ? bound.maxRowIndex : bound.minRowIndex]?.id ??\n anchorRowId;\n anchorColumnId =\n allColumns[\n columnIndex === bound.minColumnIndex ? bound.maxColumnIndex : bound.minColumnIndex\n ]?.id ?? anchorColumnId;\n }\n table.selectCellRange(\n {\n anchorRowId,\n anchorColumnId,\n focusRowId: targetRow.id,\n focusColumnId: targetColumn.id,\n },\n { mode: \"replace\" },\n );\n } else {\n table.setFocusedCell(targetRow.id, targetColumn.id);\n }\n scrollFocusedIntoView(\n clampedRowIndex,\n rows.length,\n // The extend keeps focus on the anchor; follow the jump target.\n extend ? { rowId: targetRow.id, columnId: targetColumn.id } : undefined,\n );\n return true;\n };\n\n // One visual-space focus step with the feature's move as the fallback\n // for unresolvable positions; at an edge the focus stays put.\n const moveFocusVisual = (direction: \"up\" | \"down\" | \"left\" | \"right\"): void => {\n const table = getTable();\n const focused = table.getFocusedCell();\n const target = focused\n ? getDataGridStepTarget(\n table,\n viewport,\n { rowId: focused.row.id, columnId: focused.column.id },\n direction,\n )\n : null;\n if (target === \"edge\") return;\n if (target) {\n table.setFocusedCell(target.rowId, target.columnId);\n return;\n }\n table.moveCellSelection(direction);\n };\n\n // One viewport's worth of rows for PageUp/PageDown, measured from the\n // live layout; 10 when nothing is measurable (jsdom). Data rows only:\n // the virtual table's spacer rows carry the whole scroll offset as\n // height and would collapse the page size to a single row.\n const getPageJumpSize = (): number => {\n const row = viewport.querySelector(\"tbody tr[data-row-id]\");\n // The nearest ancestor that actually scrolls; in the scroll-area\n // layout the viewport's parent is a full-height content wrapper\n // whose clientHeight would make the page span the whole table.\n let scroller: HTMLElement | null = viewport;\n while (scroller && scroller.scrollHeight <= scroller.clientHeight) {\n scroller = scroller.parentElement;\n }\n const rowHeight = row?.getBoundingClientRect().height || 0;\n const viewHeight = scroller?.clientHeight || viewport.clientHeight;\n if (!rowHeight || !viewHeight) return 10;\n return Math.max(1, Math.floor(viewHeight / rowHeight) - 1);\n };\n\n // The rows appended after the data rows: the add-row affordance and a\n // consumer appendRow draft. Positional, because an id-less tr is not\n // enough - expanded-detail rows interleave BETWEEN data rows and the\n // empty-state row stands alone, and neither belongs to this region.\n // Virtual spacer rows are aria-hidden and never match.\n const getAppendedRows = (): HTMLElement[] => {\n const body = viewport.querySelector(\"tbody\");\n const appended: HTMLElement[] = [];\n // Backwards from the end, stopping at the first data row: O(appended)\n // instead of an array of every rendered row per keystroke.\n let rowEl = body?.lastElementChild;\n while (rowEl && !rowEl.hasAttribute(\"data-row-id\")) {\n if (rowEl instanceof HTMLElement && !rowEl.hasAttribute(\"aria-hidden\")) {\n appended.unshift(rowEl);\n }\n rowEl = rowEl.previousElementSibling;\n }\n return appended;\n };\n\n const focusFirstIn = (row: HTMLElement | undefined): boolean => {\n const focusable = row?.querySelector<HTMLElement>(\n 'button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])',\n );\n if (!focusable) return false;\n focusable.focus();\n // A control that refuses focus (hidden, inert) must not report\n // success, or the arrow key that called this dead-ends.\n return row!.ownerDocument.activeElement === focusable;\n };\n\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.defaultPrevented) return;\n\n // Unified keyboard for the appended region: ArrowDown/ArrowUp walk\n // between its rows, and ArrowUp from its first row returns to the\n // grid's cell navigation. Every other key stays native there.\n const appendedRow =\n event.target instanceof Element\n ? (event.target.closest(\"tbody > tr:not([data-row-id])\") as HTMLElement | null)\n : null;\n if (appendedRow && viewport.contains(appendedRow)) {\n const appended = getAppendedRows();\n const index = appended.indexOf(appendedRow);\n // An id-less row that is NOT appended (expanded detail content,\n // the empty-state row) keeps every key native.\n if (index === -1) return;\n if (event.key !== \"ArrowUp\" && event.key !== \"ArrowDown\") return;\n if (event.key === \"ArrowDown\") {\n if (focusFirstIn(appended[index + 1])) event.preventDefault();\n return;\n }\n if (index > 0 && focusFirstIn(appended[index - 1])) {\n event.preventDefault();\n return;\n }\n // Back into the grid, on whatever cell was focused last.\n focusTarget.focus();\n syncActiveDescendant();\n event.preventDefault();\n return;\n }\n\n if (isDataGridInteractiveKeyTarget(event.target)) {\n // The ARIA grid pattern's exit gesture: Escape on an in-cell\n // control hands DOM focus back to the grid so navigation resumes.\n // A control that consumed the key first (closing its own popup)\n // never lets it reach here unprevented, and portal-rendered\n // popups keep their Escape entirely outside the viewport.\n if (event.key === \"Escape\") {\n const cell = (event.target as Element).closest?.(\"td[data-col-id]\");\n if (cell && viewport.contains(cell)) {\n event.preventDefault();\n event.stopPropagation();\n focusTarget.focus();\n syncActiveDescendant();\n }\n }\n return;\n }\n const table = getTable();\n const rtl = getComputedStyle(viewport).direction === \"rtl\";\n const horizontal = (direction: \"left\" | \"right\") =>\n rtl ? (direction === \"left\" ? \"right\" : \"left\") : direction;\n\n // Ahead of the switch so plain letters still reach the type-to-edit\n // fall-through below. Matched by code as well as key, so non-Latin\n // layouts (where the key is the layout's own character) still work.\n if (\n (event.key === \"a\" || event.key === \"A\" || event.code === \"KeyA\") &&\n (event.metaKey || event.ctrlKey) &&\n // AltGr arrives as Ctrl+Alt; that chord types a character on\n // central-European layouts and is not a select-all.\n !event.altKey\n ) {\n if (isRangeSelectionEnabled()) {\n table.selectAllCells();\n // Select-all moves the feature's focus to the range corner,\n // which can sit off-page; keep assistive tech pointed right.\n requestAnimationFrame(syncActiveDescendant);\n }\n event.preventDefault();\n return;\n }\n\n // Explicit copy and cut chords; see writeSelectionToClipboard for\n // why the native copy event cannot carry these. Paste stays on the\n // native event, which browsers do fire at the focused element.\n if ((event.metaKey || event.ctrlKey) && !event.altKey && clipboard) {\n const isCopy = event.key === \"c\" || event.key === \"C\" || event.code === \"KeyC\";\n const isCut = event.key === \"x\" || event.key === \"X\" || event.code === \"KeyX\";\n if (isCopy || isCut) {\n event.preventDefault();\n void writeSelectionToClipboard().then((written) => {\n if (!written) return;\n context.props.onCellsCopy?.({ ...written, cut: isCut });\n if (!isCut) return;\n const onCellsChange = getOnCellsChange();\n if (!onCellsChange) return;\n const details = buildDataGridClearDetails<TData>(getTable(), \"cut\", true, viewport);\n if (details) onCellsChange(details);\n });\n return;\n }\n }\n\n switch (event.key) {\n case \"ArrowUp\":\n case \"ArrowDown\":\n case \"ArrowLeft\":\n case \"ArrowRight\": {\n const direction =\n event.key === \"ArrowUp\"\n ? (\"up\" as const)\n : event.key === \"ArrowDown\"\n ? (\"down\" as const)\n : horizontal(event.key === \"ArrowLeft\" ? \"left\" : \"right\");\n if (event.metaKey || event.ctrlKey) {\n // Ctrl/Cmd+Arrow jumps to the grid edge in that direction.\n const jumped =\n direction === \"up\"\n ? jumpFocus(\"first\", \"same\", event.shiftKey && isRangeSelectionEnabled())\n : direction === \"down\"\n ? jumpFocus(\"last\", \"same\", event.shiftKey && isRangeSelectionEnabled())\n : jumpFocus(\n \"same\",\n direction === \"left\" ? \"first\" : \"last\",\n event.shiftKey && isRangeSelectionEnabled(),\n );\n if (jumped) event.preventDefault();\n return;\n }\n // ArrowDown on the last rendered row steps into the appended\n // region (a draft row, or the add-row affordance), keeping one\n // keyboard model across the whole table.\n if (direction === \"down\" && !event.shiftKey) {\n const focused = table.getFocusedCell();\n const renderedRows = viewport.querySelectorAll(\"tbody tr[data-row-id]\");\n const lastRenderedId =\n renderedRows[renderedRows.length - 1]?.getAttribute(\"data-row-id\");\n if (\n focused &&\n lastRenderedId &&\n focused.row.id === lastRenderedId &&\n focusFirstIn(getAppendedRows()[0])\n ) {\n event.preventDefault();\n return;\n }\n }\n if (event.shiftKey && isRangeSelectionEnabled()) {\n const corner = extendDataGridSelection(table, viewport, direction);\n event.preventDefault();\n scrollFocusedIntoView(undefined, undefined, corner ?? undefined);\n return;\n }\n // Plain arrows step in visual space so navigation crosses\n // pinned rows and pagination windows the feature's own move\n // cannot resolve; at a visual edge the focus stays put.\n const focused = table.getFocusedCell();\n const target = focused\n ? getDataGridStepTarget(\n table,\n viewport,\n { rowId: focused.row.id, columnId: focused.column.id },\n direction,\n )\n : null;\n if (target === \"edge\") {\n event.preventDefault();\n return;\n }\n if (target) {\n table.setFocusedCell(target.rowId, target.columnId);\n event.preventDefault();\n scrollFocusedIntoView();\n return;\n }\n table.moveCellSelection(direction);\n event.preventDefault();\n scrollFocusedIntoView();\n return;\n }\n case \"Home\":\n case \"End\": {\n // Home/End: row start or end; with Ctrl/Cmd, the grid's corners.\n const edge = event.key === \"Home\" ? (\"first\" as const) : (\"last\" as const);\n const jumped =\n event.metaKey || event.ctrlKey\n ? jumpFocus(edge, edge, event.shiftKey && isRangeSelectionEnabled())\n : jumpFocus(\"same\", edge, event.shiftKey && isRangeSelectionEnabled());\n if (jumped) event.preventDefault();\n return;\n }\n case \"PageUp\":\n case \"PageDown\": {\n const delta = (event.key === \"PageUp\" ? -1 : 1) * getPageJumpSize();\n if (jumpFocus({ delta }, \"same\", event.shiftKey && isRangeSelectionEnabled())) {\n event.preventDefault();\n }\n return;\n }\n case \"Enter\": {\n // The Notion/Airtable flow: Enter opens the editor when one is\n // wired; the Excel move-down stays the fallback.\n if (!event.shiftKey && requestCellEdit()) {\n event.preventDefault();\n return;\n }\n moveFocusVisual(event.shiftKey ? \"up\" : \"down\");\n event.preventDefault();\n scrollFocusedIntoView();\n return;\n }\n case \"F2\": {\n if (requestCellEdit()) event.preventDefault();\n return;\n }\n case \"Tab\": {\n const before = table.getFocusedCell();\n // Logical directions, no RTL swap: Tab means \"next cell\" in both\n // reading directions, exactly like DOM tab order.\n moveFocusVisual(event.shiftKey ? \"left\" : \"right\");\n const after = table.getFocusedCell();\n // Trap Tab only while it moved; at the edges focus leaves the grid,\n // which keyboard users need to escape it at all.\n if (after && after.id !== before?.id) {\n event.preventDefault();\n scrollFocusedIntoView();\n }\n return;\n }\n case \"Delete\":\n case \"Backspace\": {\n const onCellsChange = getOnCellsChange();\n if (!onCellsChange) return;\n const details = buildDataGridClearDetails<TData>(table, \"clear\", false, viewport);\n if (details) onCellsChange(details);\n event.preventDefault();\n return;\n }\n case \"Escape\": {\n // Consume the key only while it has a selection to clear, so a\n // grid inside a dialog still lets Escape close the dialog.\n if (table.getCellSelectionBounds().length) {\n table.resetCellSelection(true);\n // The focused-cell attribute is gone after the commit;\n // aria-activedescendant must not keep naming it.\n requestAnimationFrame(syncActiveDescendant);\n event.preventDefault();\n event.stopPropagation();\n }\n return;\n }\n }\n\n // Space on a cell whose content is a checkbox toggles it, the\n // row-select idiom, so the selection column works by keyboard too.\n if (event.key === \" \") {\n const checkbox = viewport\n .querySelector(\"td[data-cell-focused]\")\n ?.querySelector<HTMLElement>('[role=\"checkbox\"], input[type=\"checkbox\"]');\n if (checkbox) {\n checkbox.click();\n event.preventDefault();\n return;\n }\n }\n\n // Type-to-edit: a printable character on the focused cell opens the\n // editor seeded with it, replacing the value the way Notion and\n // Airtable do. Plain Ctrl/Cmd chords stay shortcuts, but Ctrl+Alt is\n // AltGr and bare Alt is the macOS Option layer - both type characters.\n if (\n event.key.length === 1 &&\n !event.metaKey &&\n !(event.ctrlKey && !event.altKey) &&\n requestCellEdit(event.key)\n ) {\n event.preventDefault();\n return;\n }\n\n // Space that opened nothing (read-only cell) must not scroll the page\n // out from under the focused cell.\n if (event.key === \" \" && table.getFocusedCell()) {\n event.preventDefault();\n }\n };\n\n // Writes the active region to the system clipboard in both flavors.\n // Needed because a native copy event only fires for a text selection\n // or an editable target, and a focused grid is neither - Cmd/Ctrl+C\n // would silently do nothing on macOS, Windows and Linux alike. The\n // async API needs a secure context; the execCommand fallback covers\n // the rest with the TSV flavor alone.\n const writeSelectionToClipboard = async (): Promise<{\n text: string;\n grid: string[][];\n } | null> => {\n const grid = getDataGridActiveRegionGrid(getTable(), viewport);\n if (!grid) return null;\n const text = serializeDataGridClipboardText(grid);\n try {\n if (typeof ClipboardItem !== \"undefined\" && navigator.clipboard?.write) {\n await navigator.clipboard.write([\n new ClipboardItem({\n \"text/plain\": new Blob([text], { type: \"text/plain\" }),\n \"text/html\": new Blob([renderDataGridClipboardHtml(grid)], {\n type: \"text/html\",\n }),\n }),\n ]);\n return { text, grid };\n }\n if (navigator.clipboard?.writeText) {\n await navigator.clipboard.writeText(text);\n return { text, grid };\n }\n } catch {\n // Denied or unavailable; the legacy path below still applies.\n }\n const doc = viewport.ownerDocument;\n const scratch = doc.createElement(\"textarea\");\n scratch.value = text;\n scratch.style.position = \"fixed\";\n scratch.style.opacity = \"0\";\n doc.body.appendChild(scratch);\n scratch.select();\n let copied = false;\n try {\n copied = doc.execCommand(\"copy\");\n } catch {\n copied = false;\n }\n scratch.remove();\n focusTarget.focus();\n return copied ? { text, grid } : null;\n };\n\n const copySelection = (event: ClipboardEvent, cut: boolean): boolean => {\n const grid = getDataGridActiveRegionGrid(getTable(), viewport);\n if (!grid || !event.clipboardData) return false;\n event.preventDefault();\n const text = serializeDataGridClipboardText(grid);\n event.clipboardData.setData(\"text/plain\", text);\n event.clipboardData.setData(\"text/html\", renderDataGridClipboardHtml(grid));\n context.props.onCellsCopy?.({ text, grid, cut });\n return true;\n };\n\n const handleCopy = (event: ClipboardEvent) => {\n if (isDataGridEditableTarget(event.target)) return;\n copySelection(event, false);\n };\n\n const handleCut = (event: ClipboardEvent) => {\n if (isDataGridEditableTarget(event.target)) return;\n if (!copySelection(event, true)) return;\n const onCellsChange = getOnCellsChange();\n if (!onCellsChange) return;\n const details = buildDataGridClearDetails<TData>(getTable(), \"cut\", true, viewport);\n if (details) onCellsChange(details);\n };\n\n const handlePaste = (event: ClipboardEvent) => {\n if (isDataGridEditableTarget(event.target)) return;\n const onCellsChange = getOnCellsChange();\n if (!onCellsChange) return;\n const text = event.clipboardData?.getData(\"text/plain\");\n if (!text) return;\n event.preventDefault();\n const table = getTable();\n const result = buildDataGridPasteDetails<TData>(\n table,\n parseDataGridClipboardText(text),\n viewport,\n );\n if (!result) return;\n onCellsChange(result.details);\n // The pasted region becomes the selection, the documented contract;\n // single mode keeps just the focused cell instead.\n if (isRangeSelectionEnabled()) {\n selectDataGridRegion(table, result.target);\n }\n };\n\n // Custom-control cells follow the same two-step gesture as editor\n // cells: the first click on an UNFOCUSED cell only focuses it, the\n // second activates the control, so moving the focus around can never\n // fire actions. Radix triggers open on pointerdown and Base UI ones\n // on click, so the press is intercepted at both; checkboxes keep\n // their one-click toggle (the row-select idiom), data-cell-interactive\n // widgets own all their gestures, and single-click edit mode skips\n // the interception outright.\n let pressedUnfocusedControl = false;\n const getTwoStepControl = (target: EventTarget | null): Element | null => {\n if (!(target instanceof Element)) return null;\n if (target.closest(\"[data-cell-interactive]\")) return null;\n if (target.closest('[role=\"checkbox\"], input[type=\"checkbox\"]')) {\n return null;\n }\n // Opt-in for widgets whose ACTIVE surface is bigger than any generic\n // selector can know - a combobox whose whole blank chips strip opens\n // it, a canvas editor. Marking the wrapper data-cell-control makes a\n // press anywhere on it two-step, exactly like a bare button.\n const marked = target.closest(\"[data-cell-control]\");\n if (marked) return marked;\n return target.closest(\n 'button, a, select, input, textarea, [contenteditable], [role=\"combobox\"]',\n );\n };\n const handleControlPointerDown = (event: PointerEvent) => {\n pressedUnfocusedControl = false;\n if (event.button !== 0) return;\n if (event.shiftKey || event.ctrlKey || event.metaKey) return;\n if (context.props.tableLayout?.cellEditMode === \"click\") return;\n const control = getTwoStepControl(event.target);\n const cell = control?.closest(\"td[data-col-id]\");\n if (!control || !cell || !viewport.contains(cell)) return;\n if (cell.hasAttribute(\"data-cell-focused\")) return;\n const column = getTable().getColumn(cell.getAttribute(\"data-col-id\") ?? \"\");\n if (!column || column.columnDef.enableCellSelection === false) return;\n pressedUnfocusedControl = true;\n // Stops a Radix trigger's pointerdown open before React's root\n // delegation sees it; the mouse events that focus the cell ride on.\n event.stopPropagation();\n };\n const handleControlClick = (event: MouseEvent) => {\n if (!pressedUnfocusedControl) return;\n pressedUnfocusedControl = false;\n // Swallows the activation click a Base UI trigger listens for.\n event.preventDefault();\n event.stopPropagation();\n };\n const handleControlMouseDown = (event: MouseEvent) => {\n if (!pressedUnfocusedControl) return;\n // A Base UI trigger opens on the React-delegated mousedown, and all\n // root-delegated handlers die together when the event stops here -\n // including the td's own focus logic, so the selection start runs\n // imperatively: same feature handler, same drag session.\n event.stopPropagation();\n event.preventDefault();\n const cell = (event.target as Element | null)?.closest?.(\"td[data-col-id]\");\n const rowId = cell?.closest(\"tr[data-row-id]\")?.getAttribute(\"data-row-id\");\n const columnId = cell?.getAttribute(\"data-col-id\");\n if (!rowId || !columnId) return;\n const tableNow = getTable();\n const cellApi = tableNow\n .getRowsInDisplayOrder()\n .find((row) => row.id === rowId)\n ?.getAllCellsByColumnId()[columnId];\n if (!cellApi) return;\n if (isRangeSelectionEnabled()) {\n cellApi.getSelectionStartHandler()(event);\n } else {\n tableNow.setFocusedCell(rowId, columnId);\n }\n focusTarget.focus();\n requestAnimationFrame(syncActiveDescendant);\n };\n\n // Drag-to-select outranks in-cell controls: when a drag grew the\n // range, the click that fires on release is swallowed in capture so a\n // trigger under the pointer never opens. The selection key comparison\n // is what distinguishes a drag from a motionless click made while a\n // multi-cell selection already exists (a press on \"+ Add row\" or an\n // in-cell control changes nothing, and its click must go through).\n let dragStartedOnCell = false;\n let dragStartSelectionKey = \"\";\n const getSelectionKey = () => {\n const table = getTable();\n const bounds = table.getCellSelectionBounds();\n const bound = bounds[bounds.length - 1];\n return `${table.getSelectedCellCount()}:${bounds.length}:${\n bound\n ? `${bound.minRowIndex},${bound.minColumnIndex},${bound.maxRowIndex},${bound.maxColumnIndex}`\n : \"\"\n }`;\n };\n const handleDragMouseUp = () => {\n const wasDrag =\n dragStartedOnCell &&\n getTable().getSelectedCellCount() > 1 &&\n getSelectionKey() !== dragStartSelectionKey;\n dragStartedOnCell = false;\n viewport.removeAttribute(\"data-cell-selecting\");\n if (!wasDrag) return;\n const squelch = (clickEvent: MouseEvent) => {\n clickEvent.stopPropagation();\n clickEvent.preventDefault();\n };\n viewport.addEventListener(\"click\", squelch, { capture: true });\n setTimeout(() => viewport.removeEventListener(\"click\", squelch, true), 0);\n };\n\n const handleMouseDown = (event: MouseEvent) => {\n if (event.button !== 0) return;\n // The cell a click focuses reaches assistive tech once React commits.\n requestAnimationFrame(syncActiveDescendant);\n const target = event.target as Element | null;\n // A modifier press is a selection gesture all the way through, the\n // Sheets contract: extending must not hand the keyboard to whatever\n // control sits under the pointer, or the follow-up Shift+arrows land\n // in a date button or a combobox input instead of growing the range.\n // The extension itself runs through the cell's own React handlers, so\n // the event must NOT be defaultPrevented - the delegated handlers\n // treat that as consumed and the extension never happens. Only the\n // browser's focus default is unwanted; it runs after the listeners,\n // so the grid reclaims focus one task later.\n if (\n (event.shiftKey || event.metaKey || event.ctrlKey) &&\n isRangeSelectionEnabled() &&\n target?.closest?.(\"td[data-col-id]\")\n ) {\n setTimeout(() => focusTarget.focus(), 0);\n }\n // Any td press can become a drag; the squelch only arms when the\n // range actually grew by release time. The attribute hides the fill\n // handle for the session, so its overhang never sits in the drag\n // path or churns from cell to cell while the range grows.\n dragStartedOnCell = !!target?.closest?.(\"td\");\n if (dragStartedOnCell) {\n dragStartSelectionKey = getSelectionKey();\n viewport.setAttribute(\"data-cell-selecting\", \"\");\n }\n if (!target?.closest?.('[data-slot=\"data-grid-cell-fill-handle\"]')) return;\n // Ahead of React's root delegation, so the td underneath never starts a\n // plain range drag from the handle.\n event.preventDefault();\n event.stopPropagation();\n startDataGridFillSession<TData>({\n table: getTable(),\n viewport,\n onCellsChange: getOnCellsChange(),\n });\n };\n\n // Single-click editing, the opt-in mode: a plain click that landed\n // on the (now) focused cell opens its editor immediately. Drags were\n // squelched in capture before this bubble listener, and modifier\n // clicks are selection gestures.\n const handleClickToEdit = (event: MouseEvent) => {\n if (context.props.tableLayout?.cellEditMode !== \"click\") return;\n if (event.shiftKey || event.ctrlKey || event.metaKey) return;\n if (isDataGridInteractiveKeyTarget(event.target)) return;\n const cell = (event.target as HTMLElement | null)?.closest?.(\"td\");\n if (!cell?.hasAttribute(\"data-cell-focused\")) return;\n requestCellEdit();\n };\n\n // Double-click opens the editor on the cell the first click focused,\n // matching Sheets. Interactive content keeps its own double-clicks, and\n // the clicked cell must BE the focused one, or a double-click on a\n // non-selectable cell would edit whichever cell held focus before.\n const handleDoubleClick = (event: MouseEvent) => {\n if (isDataGridInteractiveKeyTarget(event.target)) return;\n const target = event.target as HTMLElement | null;\n const cell = target?.closest?.(\"td\");\n if (!cell?.hasAttribute(\"data-cell-focused\")) return;\n requestCellEdit();\n };\n\n const previousTabIndex = focusTarget.getAttribute(\"tabindex\");\n const previousOutline = focusTarget.style.outline;\n if (keyboard) {\n focusTarget.tabIndex = 0;\n // The focused CELL ring is the indicator; the browser's outline around\n // the whole grid on focus() would double it.\n focusTarget.style.outline = \"none\";\n viewport.addEventListener(\"keydown\", handleKeyDown);\n }\n if (clipboard) {\n viewport.addEventListener(\"copy\", handleCopy);\n viewport.addEventListener(\"cut\", handleCut);\n viewport.addEventListener(\"paste\", handlePaste);\n }\n viewport.addEventListener(\"pointerdown\", handleControlPointerDown);\n viewport.addEventListener(\"mousedown\", handleControlMouseDown);\n viewport.addEventListener(\"click\", handleControlClick);\n viewport.addEventListener(\"mousedown\", handleMouseDown);\n viewport.addEventListener(\"click\", handleClickToEdit);\n viewport.addEventListener(\"dblclick\", handleDoubleClick);\n viewport.ownerDocument.addEventListener(\"mouseup\", handleDragMouseUp);\n // Selection-change notifications, read through the context getter so\n // the latest callback fires without re-running this effect. The\n // snapshot is only built when a callback is actually wired.\n const toBound = (bound: {\n minRowIndex: number;\n maxRowIndex: number;\n minColumnIndex: number;\n maxColumnIndex: number;\n }) => ({\n minRowIndex: bound.minRowIndex,\n maxRowIndex: bound.maxRowIndex,\n minColumnIndex: bound.minColumnIndex,\n maxColumnIndex: bound.maxColumnIndex,\n });\n const selectionSubscription = table.atoms.cellSelection?.subscribe(() => {\n const onCellSelectionChange = context.props.onCellSelectionChange;\n if (!onCellSelectionChange) return;\n const tableNow = getTable();\n const focusedCell = tableNow.getFocusedCell();\n const activeBound = getDataGridActiveBound(tableNow);\n onCellSelectionChange({\n focused: focusedCell\n ? { rowId: focusedCell.row.id, columnId: focusedCell.column.id }\n : null,\n bounds: tableNow.getCellSelectionBounds().map(toBound),\n activeBound: activeBound ? toBound(activeBound) : null,\n visibleCellCount: getDataGridVisibleSelectedCellCount(tableNow, viewport),\n });\n });\n setViewportEl(viewport);\n\n return () => {\n if (keyboard) {\n if (previousTabIndex === null) focusTarget.removeAttribute(\"tabindex\");\n else focusTarget.setAttribute(\"tabindex\", previousTabIndex);\n focusTarget.style.outline = previousOutline;\n focusTarget.removeAttribute(\"aria-activedescendant\");\n viewport.removeEventListener(\"keydown\", handleKeyDown);\n }\n if (clipboard) {\n viewport.removeEventListener(\"copy\", handleCopy);\n viewport.removeEventListener(\"cut\", handleCut);\n viewport.removeEventListener(\"paste\", handlePaste);\n }\n viewport.removeEventListener(\"pointerdown\", handleControlPointerDown);\n viewport.removeEventListener(\"mousedown\", handleControlMouseDown);\n viewport.removeEventListener(\"click\", handleControlClick);\n viewport.removeEventListener(\"mousedown\", handleMouseDown);\n viewport.removeEventListener(\"click\", handleClickToEdit);\n viewport.removeEventListener(\"dblclick\", handleDoubleClick);\n viewport.ownerDocument.removeEventListener(\"mouseup\", handleDragMouseUp);\n viewport.removeAttribute(\"data-cell-selecting\");\n selectionSubscription?.unsubscribe();\n clearTimeout(focusRetryTimer);\n if (apiRef) apiRef.current = null;\n setViewportEl(null);\n setEditorSession(null);\n };\n // Context getters serve fresh table/props inside every handler, so the\n // effect re-runs only when the table itself is replaced. apiRef is only\n // read and written here: keeping it out of the deps means an inline ref\n // object cannot tear the listeners down every render.\n }, [\n enabled,\n keyboard,\n clipboard,\n table.atoms.cellSelection?.subscribe,\n context.props.tableLayout?.cellEditMode,\n context.table,\n context.props.onCellsCopy,\n context.props.onCellEditRequest,\n context.props.tableLayout?.cellSelectionMode,\n context.props.onCellsChange,\n context.props.onCellSelectionChange,\n apiRef,\n ]);\n\n // The editor overlay covers the cell but not the fill handle's\n // straddling half, which would poke out beneath it; the viewport flags\n // the session so the handle hides, as it does during a drag.\n useEffect(() => {\n if (!viewportEl || !editorSession) return;\n viewportEl.setAttribute(\"data-cell-editing\", \"\");\n return () => viewportEl.removeAttribute(\"data-cell-editing\");\n }, [viewportEl, editorSession]);\n\n // Closing an editor the user finished with keys hands focus back to the\n // viewport so navigation continues where the edit left off; a commit can\n // advance first (Tab across, and Enter down or up when\n // cellEditEnterAdvance opts into the Sheets flow). A blur-initiated close\n // must NOT refocus: the browser already moved focus where the user\n // clicked, and yanking it back would reroute their next keystrokes into\n // the grid.\n const closeEditorSession = (advance: DataGridEditorAdvance, refocus = true) => {\n setEditorSession(null);\n if (advance) {\n // Same visual-space step as keyboard navigation, so a commit on a\n // pinned row advances like any other row.\n const tableNow = context.table;\n const focused = tableNow.getFocusedCell();\n const target =\n focused && viewportEl\n ? getDataGridStepTarget(\n tableNow,\n viewportEl,\n { rowId: focused.row.id, columnId: focused.column.id },\n advance,\n )\n : null;\n if (target && target !== \"edge\") {\n tableNow.setFocusedCell(target.rowId, target.columnId);\n } else if (!target) {\n tableNow.moveCellSelection(advance);\n }\n }\n if (!refocus) return;\n requestAnimationFrame(() => {\n const focusEl =\n viewportEl?.querySelector<HTMLElement>('table[data-slot=\"data-grid-table\"]') ?? viewportEl;\n focusEl?.focus();\n const cell = viewportEl?.querySelector<HTMLElement>(\"td[data-cell-focused]\");\n if (cell?.id) focusEl?.setAttribute(\"aria-activedescendant\", cell.id);\n cell?.scrollIntoView?.({\n block: \"nearest\",\n inline: \"nearest\",\n behavior: \"instant\",\n });\n });\n };\n\n // An unchanged commit dispatches nothing, the Excel model; a parse\n // rejection reports through the batch's rejected list instead of writing.\n const commitEditorSession = (raw: string, advance: DataGridEditorAdvance, refocus = true) => {\n const session = editorSession;\n closeEditorSession(advance, refocus);\n const onCellsChange = context.props.onCellsChange;\n if (!session || !onCellsChange || raw === session.baseline) return;\n const tableNow = context.table;\n const row = tableNow\n .getRowsInDisplayOrder()\n .find((candidate) => candidate.id === session.rowId);\n const column = tableNow.getColumn(session.columnId);\n const cellEdit =\n column && row ? getDataGridWritableCellEdit<TData>(column, row.original) : null;\n if (!row || !column || !cellEdit) return;\n const previousValue = row.getAllCellsByColumnId()[column.id]?.getValue();\n let value: unknown = raw;\n if (cellEdit.parse) {\n const parsed = cellEdit.parse(raw, row.original);\n if (parsed === undefined) {\n onCellsChange({\n source: \"edit\",\n changes: [],\n rejected: [\n {\n rowId: session.rowId,\n columnId: session.columnId,\n raw,\n reason: \"invalid\",\n },\n ],\n });\n return;\n }\n value = parsed;\n }\n onCellsChange({\n source: \"edit\",\n changes: [\n {\n rowId: session.rowId,\n columnId: session.columnId,\n row: row.original,\n previousValue,\n value,\n },\n ],\n rejected: [],\n });\n };\n\n return (\n <>\n <span ref={anchorRef} hidden data-slot=\"data-grid-cell-selection\" />\n {enabled && viewportEl && editorSession ? (\n <DataGridCellEditorOverlay\n key={`${editorSession.rowId}:${editorSession.columnId}`}\n viewport={viewportEl}\n session={editorSession}\n enterAdvance={context.props.tableLayout?.cellEditEnterAdvance === true}\n onCommit={commitEditorSession}\n onCancel={() => closeEditorSession(null)}\n />\n ) : null}\n </>\n );\n}\n\n/**\n * The built-in free-text editor: a portal into the body viewport, positioned\n * flush over the focused cell with the cell's own font, alignment and\n * padding, so the text keeps its exact place - the Sheets model. The\n * `textarea` control grows downward over the rows below as the text wraps.\n */\nfunction measureDataGridCellEditorStyle(viewport: HTMLElement): CSSProperties | null {\n const cell = viewport.querySelector<HTMLElement>(\"td[data-cell-focused]\");\n if (!cell) return null;\n const cellRect = cell.getBoundingClientRect();\n const viewportRect = viewport.getBoundingClientRect();\n const cellStyle = getComputedStyle(cell);\n // The td centers its one line vertically (align-middle); the editor must\n // put the text in exactly the same place or opening it shifts the value.\n // Symmetric block padding sized to center one line does that for the\n // textarea too, and keeps holding as it grows line by line.\n const lineHeight =\n Number.parseFloat(cellStyle.lineHeight) || Number.parseFloat(cellStyle.fontSize) * 1.5 || 20;\n const centeredBlockPadding = Math.max(\n Number.parseFloat(cellStyle.paddingTop) || 0,\n (cellRect.height - lineHeight) / 2,\n );\n return {\n // Rect deltas are visual; when the viewport itself is the scroll\n // container (the standalone virtual layout), absolute children live in\n // content coordinates, so the scroll offset must be added back. The box\n // matches the cell exactly - editing must not change the cell's\n // geometry - and the cell's own overlay chrome hides for the session\n // (data-cell-editing), so the editor's outline is the ONE border.\n left: cellRect.left - viewportRect.left + viewport.scrollLeft,\n top: cellRect.top - viewportRect.top + viewport.scrollTop,\n width: cellRect.width,\n minHeight: cellRect.height,\n // The font shorthand can serialize empty (Firefox); the longhands after\n // it win where set and cover that case.\n font: cellStyle.font || undefined,\n fontFamily: cellStyle.fontFamily,\n fontSize: cellStyle.fontSize,\n fontWeight: cellStyle.fontWeight,\n fontStyle: cellStyle.fontStyle,\n lineHeight: cellStyle.lineHeight,\n letterSpacing: cellStyle.letterSpacing,\n textAlign: cellStyle.textAlign as CSSProperties[\"textAlign\"],\n paddingLeft: cellStyle.paddingLeft,\n paddingRight: cellStyle.paddingRight,\n paddingTop: centeredBlockPadding,\n paddingBottom: centeredBlockPadding,\n };\n}\n\nfunction DataGridCellEditorOverlay({\n viewport,\n session,\n enterAdvance,\n onCommit,\n onCancel,\n}: {\n viewport: HTMLElement;\n session: DataGridEditorSession;\n enterAdvance: boolean;\n onCommit: (raw: string, advance: DataGridEditorAdvance, refocus?: boolean) => void;\n onCancel: () => void;\n}) {\n // Measured lazily at first render: the focused td was committed before the\n // session opened, and the overlay remounts per cell via its key, so one\n // measurement holds for the editor's lifetime.\n const [style] = useState<CSSProperties | null>(() => measureDataGridCellEditorStyle(viewport));\n const finishedRef = useRef(false);\n\n // The caret belongs at the END of the value (the Excel F2 convention);\n // a textarea would otherwise open with it at position 0. Set on mount,\n // before autoFocus lands, so the stored selection is already right.\n const placeCaretAtEnd = (element: HTMLInputElement | HTMLTextAreaElement | null) => {\n if (!element) return;\n const end = element.value.length;\n element.setSelectionRange?.(end, end);\n };\n\n useEffect(() => {\n if (!style) onCancel();\n }, [style, onCancel]);\n\n // External row changes mid-edit (a live update, a re-sort) move or remove\n // the cell underneath the overlay; the measured position is then a lie and\n // a commit could land visually elsewhere. Cancel instead: predictable, and\n // nothing is written that the user cannot see.\n useEffect(() => {\n const body = viewport.querySelector(\"tbody\");\n if (!body) return;\n const observer = new MutationObserver(() => {\n if (!finishedRef.current) onCancel();\n });\n observer.observe(body, { childList: true, subtree: true });\n return () => observer.disconnect();\n }, [viewport, onCancel]);\n\n if (!style) return null;\n\n const finish = (\n element: HTMLInputElement | HTMLTextAreaElement,\n commit: boolean,\n advance: DataGridEditorAdvance = null,\n refocus = true,\n ) => {\n // One finish per session: an Enter commit can be chased by the blur the\n // unmount produces, and a doubled commit would write twice.\n if (finishedRef.current) return;\n finishedRef.current = true;\n if (commit) onCommit(element.value, advance, refocus);\n else onCancel();\n };\n\n const handleKeyDown = (event: ReactKeyboardEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n const element = event.currentTarget;\n if (event.key === \"Escape\") {\n event.preventDefault();\n event.stopPropagation();\n finish(element, false);\n return;\n }\n if (event.key === \"Tab\") {\n event.preventDefault();\n finish(element, true, event.shiftKey ? \"left\" : \"right\");\n return;\n }\n if (event.key !== \"Enter\") return;\n // A textarea keeps Shift/Alt+Enter as a newline, the Sheets convention.\n if (session.control === \"textarea\" && (event.shiftKey || event.altKey)) {\n return;\n }\n event.preventDefault();\n // The default keeps focus on the edited cell, so a corrected value can\n // be reviewed in place; enterAdvance restores the Sheets move-down.\n finish(element, true, enterAdvance ? (event.shiftKey ? \"up\" : \"down\") : null);\n };\n\n // z-[35]: above the sticky pinned cells (zIndex 30), or editing a pinned\n // cell renders invisibly underneath them; below the sticky header (z-40).\n // Primary outline at the same 1px weight as the focused cell's box: with\n // the overlay covering that box, opening the editor reads as the same\n // border becoming editable.\n const sharedClassName =\n \"text-foreground bg-background outline-primary absolute z-[35] box-border resize-none outline-1 outline-solid -outline-offset-1\";\n\n return createPortal(\n session.control === \"textarea\" ? (\n <textarea\n data-slot=\"data-grid-cell-editor\"\n ref={placeCaretAtEnd}\n autoFocus\n aria-label={session.label}\n defaultValue={session.initialValue}\n rows={1}\n style={style}\n className={cn(sharedClassName, \"field-sizing-content overflow-hidden\")}\n onKeyDown={handleKeyDown}\n onBlur={(event) => finish(event.currentTarget, true, null, false)}\n />\n ) : (\n <input\n data-slot=\"data-grid-cell-editor\"\n ref={placeCaretAtEnd}\n autoFocus\n aria-label={session.label}\n defaultValue={session.initialValue}\n style={style}\n className={sharedClassName}\n onKeyDown={handleKeyDown}\n onBlur={(event) => finish(event.currentTarget, true, null, false)}\n />\n ),\n viewport,\n );\n}\n\n/* ------------------------------------------------------------------------- *\n * Bulk edit bar.\n * ------------------------------------------------------------------------- */\n\n/**\n * Thin shell over row selection for bulk actions: selected count, a slot for\n * the consumer's controls, and a clear action. Hidden while nothing is\n * selected. What the controls do stays consumer-owned.\n *\n * Presented as a floating toolbar, the Google Sheets way: auto width,\n * centered, elevated, and sticky to the viewport bottom with breathing room,\n * so bulk actions stay reachable while the grid scrolls.\n */\nfunction DataGridSelectionBar({\n children,\n className,\n label,\n clearLabel = \"Clear\",\n onClear,\n}: {\n children?: ReactNode;\n className?: string;\n label?: (count: number) => ReactNode;\n clearLabel?: ReactNode;\n onClear?: () => void;\n}) {\n const context = useDataGrid();\n const rowSelectionAtom = context.table.atoms.rowSelection;\n if (rowSelectionAtom == null) return null;\n\n return (\n <Subscribe source={rowSelectionAtom}>\n {() => {\n // Read through the context getter: this closure re-runs on atom\n // writes without re-rendering the component, and a captured v9\n // wrapper would keep reporting the state it was built with.\n const table = context.table;\n const count = table.getSelectedRowModel().rows.length;\n if (count === 0) return null;\n return (\n <div\n data-slot=\"data-grid-selection-bar\"\n className={cn(\n \"sticky inset-x-0 bottom-4 z-40 mx-auto flex w-fit max-w-[calc(100%-2rem)] flex-wrap items-center gap-3 rounded-lg border bg-background px-4 py-2.5 shadow-lg\",\n className,\n )}\n >\n <span className=\"font-medium text-foreground text-sm\">\n {label ? label(count) : `${count} selected`}\n </span>\n <div className=\"flex flex-1 flex-wrap items-center justify-end gap-2.5\">\n {children}\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => {\n context.table.resetRowSelection();\n onClear?.();\n }}\n >\n {clearLabel}\n </Button>\n </div>\n </div>\n );\n }}\n </Subscribe>\n );\n}\n\nexport type { DataGridCellSelectionApi, DataGridFocusCellOptions, DataGridPasteTarget };\nexport {\n buildDataGridClearDetails,\n buildDataGridPasteDetails,\n DataGridCellSelection,\n DataGridSelectionBar,\n getDataGridActiveRegionGrid,\n getDataGridVisibleSelectedCellCount,\n invertDataGridCellsChange,\n parseDataGridClipboardText,\n serializeDataGridClipboardText,\n tileDataGridClipboardBlock,\n};\n"],"mappings":";;;;;;;;;AAgEA,SAAS,gCAAgC,OAAuB;CAG9D,OAAO,YAAY,KAAK,KAAK,IAAI,IAAI,MAAM,WAAW,MAAK,MAAI,EAAE,KAAK;AACxE;;AAGA,SAAS,+BAA+B,MAA0B;CAChE,OAAO,KAAK,KAAK,SAAS,KAAK,IAAI,+BAA+B,CAAC,CAAC,KAAK,GAAI,CAAC,CAAC,CAAC,KAAK,MAAM;AAC7F;;;;;;AAOA,SAAS,2BAA2B,MAA0B;CAC5D,MAAM,OAAmB,CAAC;CAC1B,IAAI,MAAgB,CAAC;CACrB,IAAI,QAAQ;CACZ,IAAI,SAAS;CACb,IAAI,IAAI;CAER,OAAO,IAAI,KAAK,QAAQ;EACtB,MAAM,KAA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B,cAAc,QAAQ;EACf;EACP,WAAW;EACX,WAAW;EACX,SAAS,UAAU,OAAO,MAAM,eAAe,MAAM,MAAM,KAAK;CACjE,CAAA,GAEH,QACF;AACF;;;;;;;;;;AAeA,SAAS,qBAAqB,EAC5B,UACA,WACA,OACA,aAAa,SACb,WAOC;CACD,MAAM,UAAU,YAAY;CAC5B,MAAM,mBAAmB,QAAQ,MAAM,MAAM;CAC7C,IAAI,oBAAoB,MAAM,OAAO;CAErC,OACE,oBAAC,WAAD;EAAW,QAAQ;EACV,gBAAA;GAKL,MAAM,QADQ,QAAQ,MACF,oBAAoB,CAAC,CAAC,KAAK;GAC/C,IAAI,UAAU,GAAG,OAAO;GACxB,OACE,qBAAC,OAAD;IACE,aAAU;IACV,WAAW,GACT,gKACA,SACF;IALF,UAAA,CAOE,oBAAC,QAAD;KAAM,WAAU;KACb,UAAA,QAAQ,MAAM,KAAK,IAAI,GAAG,MAAM;IAC7B,CAAA,GACN,qBAAC,OAAD;KAAK,WAAU;KAAf,UAAA,CACG,UACD,oBAAC,QAAD;MACE,SAAQ;MACR,MAAK;MACL,eAAe;OACb,QAAQ,MAAM,kBAAkB;OAChC,UAAU;MACZ;MAEC,UAAA;KACK,CAAA,CACL;IACF,CAAA,CAAA;;EAET;CACS,CAAA;AAEf"}
1
+ {"version":3,"file":"data-grid-cell-selection.js","names":[],"sources":["../../../../src/components/reui/data-grid/data-grid-cell-selection.tsx"],"sourcesContent":["\"use client\";\n\n// Opted out of React Compiler with the rest of the grid (see data-grid.tsx).\n\"use no memo\";\n\nimport type {\n CSSProperties,\n KeyboardEvent as ReactKeyboardEvent,\n ReactNode,\n RefObject,\n} from \"react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { Subscribe } from \"@tanstack/react-table\";\nimport { createPortal } from \"react-dom\";\n\nimport { cn } from \"@kumix/utils\";\nimport { Button } from \"../../ui/button\";\nimport type {\n DataGridCellChange,\n DataGridCellRejection,\n DataGridCellsChangeDetails,\n DataGridColumnCellEdit,\n DataGridTableInstance,\n} from \"./data-grid\";\nimport { useDataGrid } from \"./data-grid\";\n\n/** Where a finished edit sends the focused cell, or null to stay. */\ntype DataGridEditorAdvance = \"down\" | \"up\" | \"right\" | \"left\" | null;\n\ninterface DataGridFocusCellOptions {\n /** Also open the cell's editor, the way Enter would. */\n edit?: boolean;\n}\n\n/** Imperative surface of the cell-selection controller. */\ninterface DataGridCellSelectionApi {\n /**\n * Moves the grid's cell focus AND the document focus together, retrying\n * briefly while the row mounts, so a freshly created row is typeable\n * without an extra click. `edit: true` also opens the cell's editor the\n * way Enter would. Registered once the controller is wired; null while\n * cell selection is off.\n */\n focusCell: (rowId: string, columnId: string, options?: DataGridFocusCellOptions) => void;\n /** Clears every range and the focused cell. */\n clearSelection: () => void;\n /** Scrolls a rendered cell into view without moving focus. */\n scrollToCell: (rowId: string, columnId: string) => void;\n}\n\n/** One open built-in editor: which cell, which control, and its text. */\ninterface DataGridEditorSession {\n rowId: string;\n columnId: string;\n control: \"text\" | \"textarea\";\n /** What the editor opens with: the typed seed or the formatted value. */\n initialValue: string;\n /** The formatted current value; an unchanged commit dispatches nothing. */\n baseline: string;\n /** Accessible name for the overlay control, from the column's header. */\n label: string;\n}\n\n/* ------------------------------------------------------------------------- *\n * Clipboard text: pure, node-testable.\n * ------------------------------------------------------------------------- */\n\nfunction serializeDataGridClipboardField(field: string): string {\n // Excel and Sheets quote a field containing a delimiter and double inner\n // quotes; everything else ships bare.\n return /[\\t\\n\\r\"]/.test(field) ? `\"${field.replaceAll('\"', '\"\"')}\"` : field;\n}\n\n/** Row-major grid to TSV, CRLF rows, Excel-style quoting. */\nfunction serializeDataGridClipboardText(grid: string[][]): string {\n return grid.map((line) => line.map(serializeDataGridClipboardField).join(\"\\t\")).join(\"\\r\\n\");\n}\n\n/**\n * TSV to a row-major grid. A stateful scan, not a split: a quoted field may\n * contain tabs, quotes and both newline flavors, which is exactly what Excel\n * emits for a multi-line cell.\n */\nfunction parseDataGridClipboardText(text: string): string[][] {\n const rows: string[][] = [];\n let row: string[] = [];\n let field = \"\";\n let quoted = false;\n let i = 0;\n\n while (i < text.length) {\n const ch = text[i]!;\n if (quoted) {\n if (ch === '\"') {\n if (text[i + 1] === '\"') {\n field += '\"';\n i += 2;\n continue;\n }\n quoted = false;\n i += 1;\n continue;\n }\n field += ch;\n i += 1;\n continue;\n }\n if (ch === '\"' && field === \"\") {\n quoted = true;\n i += 1;\n continue;\n }\n if (ch === \"\\t\") {\n row.push(field);\n field = \"\";\n i += 1;\n continue;\n }\n if (ch === \"\\r\" || ch === \"\\n\") {\n if (ch === \"\\r\" && text[i + 1] === \"\\n\") i += 1;\n row.push(field);\n rows.push(row);\n row = [];\n field = \"\";\n i += 1;\n continue;\n }\n field += ch;\n i += 1;\n }\n row.push(field);\n rows.push(row);\n\n // Excel terminates the payload with one newline; that final empty line is\n // an artifact of the format, not a data row.\n const last = rows[rows.length - 1];\n if (rows.length > 1 && last?.length === 1 && last[0] === \"\") rows.pop();\n\n return rows;\n}\n\n/** Repeats a block cyclically to fill rowCount x columnCount. */\nfunction tileDataGridClipboardBlock(\n block: string[][],\n rowCount: number,\n columnCount: number,\n): string[][] {\n const tiled: string[][] = [];\n for (let r = 0; r < rowCount; r++) {\n const source = block[r % block.length] ?? [];\n const line: string[] = [];\n for (let c = 0; c < columnCount; c++) {\n line.push(source[c % (source.length || 1)] ?? \"\");\n }\n tiled.push(line);\n }\n return tiled;\n}\n\nfunction escapeDataGridClipboardHtml(value: string): string {\n return value.replaceAll(\"&\", \"&amp;\").replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\");\n}\n\n// A minimal text/html flavor alongside the TSV keeps type fidelity when the\n// paste target is Excel or Sheets. Newlines inside a field become <br>, the\n// HTML representation of a multi-line cell; raw newlines would collapse to\n// spaces on paste.\nfunction renderDataGridClipboardHtml(grid: string[][]): string {\n const body = grid\n .map(\n (line) =>\n \"<tr>\" +\n line\n .map(\n (field) =>\n `<td>${escapeDataGridClipboardHtml(field).replace(/\\r\\n|\\r|\\n/g, \"<br>\")}</td>`,\n )\n .join(\"\") +\n \"</tr>\",\n )\n .join(\"\");\n return `<table><tbody>${body}</tbody></table>`;\n}\n\n/* ------------------------------------------------------------------------- *\n * Selection geometry: walks in the feature's own index space.\n * ------------------------------------------------------------------------- */\n\n/**\n * Columns in render order, the same [start, center, end] space\n * cellSelectionFeature resolves its bounds against.\n */\nfunction getDataGridDisplayOrderedColumns<TData extends object>(\n table: DataGridTableInstance<TData>,\n) {\n return [\n ...table.getStartVisibleLeafColumns(),\n ...table.getCenterVisibleLeafColumns(),\n ...table.getEndVisibleLeafColumns(),\n ];\n}\n\nfunction getDataGridWritableCellEdit<TData extends object>(\n column: {\n columnDef: { meta?: { cellEdit?: DataGridColumnCellEdit<TData> } };\n },\n /**\n * The row a write targets. Function-form `editable` is evaluated against\n * it; without a row the column counts as writable in principle, the\n * coarse check the fill preview's column filter uses.\n */\n row?: TData,\n): DataGridColumnCellEdit<TData> | null {\n const cellEdit = column.columnDef.meta?.cellEdit;\n if (!cellEdit || cellEdit.editable === false) return null;\n if (typeof cellEdit.editable === \"function\" && row !== undefined && !cellEdit.editable(row)) {\n return null;\n }\n return cellEdit;\n}\n\n/**\n * Ids of the rows the view can actually show: the page slice plus rows the\n * DOM renders outside it (pinned rows under keepPinnedRows). Selection\n * bounds live in pre-paginated display order, so a range whose corners are\n * both visible can still span off-page rows in between - a page-boundary\n * range to a bottom-pinned draft is the standing example. Every batch walk\n * (copy, clear, paste, fill) filters rows through this set so the cells a\n * batch touches are exactly the cells the selection paints.\n */\nfunction getDataGridRenderedRowIds<TData extends object>(\n table: DataGridTableInstance<TData>,\n viewport: HTMLElement | null | undefined,\n): Set<string> | null {\n if (!viewport) return null;\n // When the page slice covers the whole display order (manual pagination,\n // virtualization, no pagination) no row can be off-page: skip the walk.\n if (table.getRowModel().rows.length === table.getRowsInDisplayOrder().length) {\n return null;\n }\n const rendered = new Set<string>(table.getRowModel().rows.map((row: { id: string }) => row.id));\n for (const rowEl of Array.from(viewport.querySelectorAll(\"tbody tr[data-row-id]\"))) {\n const id = rowEl.getAttribute(\"data-row-id\");\n if (id) rendered.add(id);\n }\n return rendered;\n}\n\n/**\n * Cells of the current selection the view can actually show, under the\n * same row filter the batch builders use, so a count shown next to the\n * selection always matches what is painted and what a batch will touch.\n * The feature's own getSelectedCellCount spans off-page rows instead.\n */\nfunction getDataGridVisibleSelectedCellCount<TData extends object>(\n table: DataGridTableInstance<TData>,\n /** The grid's body viewport; null falls back to the full-range count. */\n viewport: HTMLElement | null,\n): number {\n const bounds = table.getCellSelectionBounds();\n if (!bounds.length) return 0;\n const rows = table.getRowsInDisplayOrder();\n const columns = getDataGridDisplayOrderedColumns(table);\n const rendered = getDataGridRenderedRowIds(table, viewport);\n let count = 0;\n for (const bound of bounds) {\n let rowCount = 0;\n for (let r = bound.minRowIndex; r <= bound.maxRowIndex; r++) {\n const row = rows[r];\n if (row && (!rendered || rendered.has(row.id))) rowCount += 1;\n }\n let columnCount = 0;\n for (let c = bound.minColumnIndex; c <= bound.maxColumnIndex; c++) {\n const column = columns[c];\n if (column && column.columnDef.enableCellSelection !== false) {\n columnCount += 1;\n }\n }\n count += rowCount * columnCount;\n }\n return count;\n}\n\n/**\n * The bound of the ACTIVE (most recent) region. getCellSelectionBounds()\n * sorts geometrically, so its last entry is merely the bottom-right\n * rectangle; the focused cell anchors the newest range, so the bound\n * containing it is the active one. Falls back to the geometric last when\n * the focused cell sits in no bound (the newest range was an exclude).\n */\nfunction getDataGridActiveBound<TData extends object>(table: DataGridTableInstance<TData>) {\n const bounds = table.getCellSelectionBounds();\n if (!bounds.length) return null;\n const focused = table.getFocusedCell();\n if (focused) {\n // O(1): v9 caches the display index on the row itself.\n const rowIndex = focused.row.getDisplayIndex();\n const columnIndex = getDataGridDisplayOrderedColumns(table).findIndex(\n (column) => column.id === focused.column.id,\n );\n const containing = bounds.find(\n (bound) =>\n rowIndex >= bound.minRowIndex &&\n rowIndex <= bound.maxRowIndex &&\n columnIndex >= bound.minColumnIndex &&\n columnIndex <= bound.maxColumnIndex,\n );\n if (containing) return containing;\n }\n return bounds[bounds.length - 1] ?? null;\n}\n\n/**\n * Resolves the cell one visual step away from a given cell: selectable\n * columns for horizontal, RENDERED row order for vertical. The feature's\n * own move/extend resolve rows through the page slice and stall on pinned\n * rows (a bottom-pinned draft), while id-addressed cells work everywhere.\n * \"edge\" means the step is at the grid boundary; null means the position\n * is not resolvable here and the caller should use the feature's move.\n */\nfunction getDataGridStepTarget<TData extends object>(\n table: DataGridTableInstance<TData>,\n viewport: HTMLElement,\n from: { rowId: string; columnId: string },\n direction: \"up\" | \"down\" | \"left\" | \"right\",\n): { rowId: string; columnId: string } | \"edge\" | null {\n if (direction === \"left\" || direction === \"right\") {\n const selectable = getDataGridDisplayOrderedColumns(table).filter(\n (column) => column.columnDef.enableCellSelection !== false,\n );\n const index = selectable.findIndex((column) => column.id === from.columnId);\n if (index === -1) return null;\n const next = selectable[index + (direction === \"right\" ? 1 : -1)];\n return next ? { rowId: from.rowId, columnId: next.id } : \"edge\";\n }\n const renderedIds = Array.from(viewport.querySelectorAll(\"tbody tr[data-row-id]\")).map((row) =>\n row.getAttribute(\"data-row-id\"),\n );\n const index = renderedIds.indexOf(from.rowId);\n if (index === -1) return null;\n const nextId = renderedIds[index + (direction === \"down\" ? 1 : -1)];\n return nextId ? { rowId: nextId, columnId: from.columnId } : \"edge\";\n}\n\n/**\n * Shift+Arrow: the feature keeps focus on the anchor and grows the range\n * from its active corner. When its own extend cannot resolve the step\n * (the active corner sits on a pinned row, or the next visual row is a\n * pinned row outside the page slice), re-derive the active corner from\n * the bounds and step it in visual space through selectCellRange.\n */\nfunction extendDataGridSelection<TData extends object>(\n table: DataGridTableInstance<TData>,\n viewport: HTMLElement,\n direction: \"up\" | \"down\" | \"left\" | \"right\",\n): { rowId: string; columnId: string } | null {\n // The range's active corner: focus stays the anchor, so the corner is\n // the bound's opposite one. Returned to the caller so the view can\n // follow the growing edge rather than the anchor.\n const activeCorner = () => {\n const focused = table.getFocusedCell();\n if (!focused) return null;\n const bound = getDataGridActiveBound(table);\n if (!bound) return null;\n const rows = table.getRowsInDisplayOrder();\n const allColumns = getDataGridDisplayOrderedColumns(table);\n const rowIndex = focused.row.getDisplayIndex();\n const columnIndex = allColumns.findIndex((column) => column.id === focused.column.id);\n return {\n rowId:\n rows[rowIndex === bound.minRowIndex ? bound.maxRowIndex : bound.minRowIndex]?.id ??\n focused.row.id,\n columnId:\n allColumns[\n columnIndex === bound.minColumnIndex ? bound.maxColumnIndex : bound.minColumnIndex\n ]?.id ?? focused.column.id,\n };\n };\n const boundKey = () => {\n const bounds = table.getCellSelectionBounds();\n const bound = bounds[bounds.length - 1];\n return bound\n ? `${bounds.length}:${bound.minRowIndex}-${bound.maxRowIndex}:${bound.minColumnIndex}-${bound.maxColumnIndex}`\n : \"none\";\n };\n const before = boundKey();\n table.extendCellSelection(direction);\n if (boundKey() !== before) return activeCorner();\n const focused = table.getFocusedCell();\n if (!focused) return null;\n const active = activeCorner() ?? {\n rowId: focused.row.id,\n columnId: focused.column.id,\n };\n const target = getDataGridStepTarget(table, viewport, active, direction);\n if (!target || target === \"edge\") return null;\n table.selectCellRange(\n {\n anchorRowId: focused.row.id,\n anchorColumnId: focused.column.id,\n focusRowId: target.rowId,\n focusColumnId: target.columnId,\n },\n { mode: \"replace\" },\n );\n return target;\n}\n\n/**\n * The active region as formatted strings, row-major. Columns opted out of\n * selection are compacted away, matching the feature's own ranges-data\n * behavior, and rows the view cannot show are skipped when a viewport is\n * given. Null when nothing is selected.\n */\nfunction getDataGridActiveRegionGrid<TData extends object>(\n table: DataGridTableInstance<TData>,\n viewport?: HTMLElement | null,\n): string[][] | null {\n const bound = getDataGridActiveBound(table);\n if (!bound) return null;\n\n const rows = table.getRowsInDisplayOrder();\n const columns = getDataGridDisplayOrderedColumns(table);\n const rendered = getDataGridRenderedRowIds(table, viewport);\n const grid: string[][] = [];\n\n for (let r = bound.minRowIndex; r <= bound.maxRowIndex; r++) {\n const row = rows[r];\n if (!row || (rendered && !rendered.has(row.id))) continue;\n const cells = row.getAllCellsByColumnId();\n const line: string[] = [];\n for (let c = bound.minColumnIndex; c <= bound.maxColumnIndex; c++) {\n const column = columns[c];\n if (!column || column.columnDef.enableCellSelection === false) continue;\n const value = cells[column.id]?.getValue();\n const format = column.columnDef.meta?.cellEdit?.format;\n line.push(format ? format(value, row.original) : String(value ?? \"\"));\n }\n grid.push(line);\n }\n\n return grid.length ? grid : null;\n}\n\n/**\n * A clear/cut batch over the selection's writable cells. Non-writable columns\n * are skipped silently: clearing is an intent over what the grid owns, and a\n * rejection per read-only cell would be noise. Null when nothing clears.\n */\nfunction buildDataGridClearDetails<TData extends object>(\n table: DataGridTableInstance<TData>,\n source: \"clear\" | \"cut\",\n activeRegionOnly: boolean,\n viewport?: HTMLElement | null,\n): DataGridCellsChangeDetails<TData> | null {\n const allBounds = table.getCellSelectionBounds();\n const activeBound = getDataGridActiveBound(table);\n const bounds = activeRegionOnly ? (activeBound ? [activeBound] : []) : allBounds;\n if (!bounds.length) return null;\n\n const rows = table.getRowsInDisplayOrder();\n const columns = getDataGridDisplayOrderedColumns(table);\n const rendered = getDataGridRenderedRowIds(table, viewport);\n const changes: DataGridCellChange<TData>[] = [];\n\n for (const bound of bounds) {\n for (let r = bound.minRowIndex; r <= bound.maxRowIndex; r++) {\n const row = rows[r];\n if (!row || (rendered && !rendered.has(row.id))) continue;\n const cells = row.getAllCellsByColumnId();\n for (let c = bound.minColumnIndex; c <= bound.maxColumnIndex; c++) {\n const column = columns[c];\n if (!column || column.columnDef.enableCellSelection === false) continue;\n const cellEdit = getDataGridWritableCellEdit<TData>(column, row.original);\n if (!cellEdit) continue;\n changes.push({\n rowId: row.id,\n columnId: column.id,\n row: row.original,\n previousValue: cells[column.id]?.getValue(),\n value: cellEdit.clearValue ?? null,\n });\n }\n }\n }\n\n return changes.length ? { source, changes, rejected: [] } : null;\n}\n\ntype DataGridPasteTarget = {\n /** Display indexes of the pasted region's first and last row. */\n startRowIndex: number;\n endRowIndex: number;\n /** How many rows a paste actually wrote (hidden rows are skipped). */\n rowCount?: number;\n /** Display indexes of the pasted region's first and last column. */\n startColumnIndex: number;\n endColumnIndex: number;\n};\n\n/**\n * Resolves a parsed clipboard block into a paste batch, Excel semantics:\n * a 1x1 block fills the whole selected region; a block tiles when the region\n * is an exact multiple of it; otherwise it pastes once from the region's\n * top-left, clamped at the grid edges (rows are never grown).\n */\nfunction buildDataGridPasteDetails<TData extends object>(\n table: DataGridTableInstance<TData>,\n block: string[][],\n viewport?: HTMLElement | null,\n): {\n details: DataGridCellsChangeDetails<TData>;\n target: DataGridPasteTarget;\n} | null {\n if (!block.length) return null;\n const bound = getDataGridActiveBound(table);\n if (!bound) return null;\n\n const rows = table.getRowsInDisplayOrder();\n const columns = getDataGridDisplayOrderedColumns(table);\n const rendered = getDataGridRenderedRowIds(table, viewport);\n\n // Copy COMPACTS opt-out columns away, so paste maps block columns over the\n // same compacted space: selectable columns only, starting at the region's\n // first selectable column and running past the region for a wider block,\n // clamped at the grid edge. Walking raw display offsets instead would let\n // an interior opt-out column swallow a block column silently.\n const targetColumns: Array<{\n column: (typeof columns)[number];\n displayIndex: number;\n }> = [];\n let regionColumns = 0;\n for (let c = bound.minColumnIndex; c < columns.length; c++) {\n const column = columns[c];\n if (!column || column.columnDef.enableCellSelection === false) continue;\n targetColumns.push({ column, displayIndex: c });\n if (c <= bound.maxColumnIndex) regionColumns += 1;\n }\n if (!regionColumns) return null;\n\n const blockRows = block.length;\n const blockColumns = block.reduce((max, line) => Math.max(max, line.length), 1);\n const regionRows = bound.maxRowIndex - bound.minRowIndex + 1;\n\n let rowCount: number;\n let columnCount: number;\n if (blockRows === 1 && blockColumns === 1) {\n rowCount = regionRows;\n columnCount = regionColumns;\n } else if (regionRows % blockRows === 0 && regionColumns % blockColumns === 0) {\n rowCount = regionRows;\n columnCount = regionColumns;\n } else {\n rowCount = blockRows;\n columnCount = blockColumns;\n }\n\n const tiled = tileDataGridClipboardBlock(block, rowCount, columnCount);\n const startRowIndex = bound.minRowIndex;\n\n // Rows the block maps onto: the next rowCount rows the view can show,\n // starting at the region's top. Off-page rows between a page's tail and\n // a pinned draft are skipped rather than silently written.\n const targetRows: Array<{ row: (typeof rows)[number]; displayIndex: number }> = [];\n for (let r = startRowIndex; r < rows.length; r++) {\n if (targetRows.length === rowCount) break;\n const row = rows[r];\n if (!row || (rendered && !rendered.has(row.id))) continue;\n targetRows.push({ row, displayIndex: r });\n }\n\n const changes: DataGridCellChange<TData>[] = [];\n const rejected: DataGridCellRejection[] = [];\n\n for (let r = 0; r < targetRows.length; r++) {\n const row = targetRows[r]!.row;\n const cells = row.getAllCellsByColumnId();\n for (let c = 0; c < columnCount; c++) {\n const column = targetColumns[c]?.column;\n if (!column) continue;\n const raw = tiled[r]?.[c] ?? \"\";\n const cellEdit = getDataGridWritableCellEdit<TData>(column, row.original);\n if (!cellEdit) {\n rejected.push({\n rowId: row.id,\n columnId: column.id,\n raw,\n reason: \"readonly\",\n });\n continue;\n }\n const value = cellEdit.parse ? cellEdit.parse(raw, row.original) : raw;\n if (value === undefined) {\n rejected.push({\n rowId: row.id,\n columnId: column.id,\n raw,\n reason: \"invalid\",\n });\n continue;\n }\n changes.push({\n rowId: row.id,\n columnId: column.id,\n row: row.original,\n previousValue: cells[column.id]?.getValue(),\n value,\n });\n }\n }\n\n if (!changes.length && !rejected.length) return null;\n const lastTarget = targetColumns[Math.min(columnCount, targetColumns.length) - 1];\n return {\n details: { source: \"paste\", changes, rejected },\n target: {\n startRowIndex,\n endRowIndex: targetRows[targetRows.length - 1]?.displayIndex ?? startRowIndex,\n rowCount: targetRows.length,\n startColumnIndex: targetColumns[0]!.displayIndex,\n endColumnIndex: lastTarget!.displayIndex,\n },\n };\n}\n\n/**\n * The inverse batch: every change's value and previousValue swapped and\n * rejections dropped. Feed it through the same state update onCellsChange\n * uses to implement undo; inverting the inverse is redo.\n */\nfunction invertDataGridCellsChange<TData extends object>(\n details: DataGridCellsChangeDetails<TData>,\n): DataGridCellsChangeDetails<TData> {\n return {\n source: details.source,\n changes: details.changes.map((change) => ({\n ...change,\n value: change.previousValue,\n previousValue: change.value,\n })),\n rejected: [],\n };\n}\n\nfunction selectDataGridRegion<TData extends object>(\n table: DataGridTableInstance<TData>,\n target: DataGridPasteTarget,\n) {\n const rows = table.getRowsInDisplayOrder();\n const columns = getDataGridDisplayOrderedColumns(table);\n const anchorRow = rows[target.startRowIndex];\n const anchorColumn = columns[target.startColumnIndex];\n const focusRow = rows[Math.min(target.endRowIndex, rows.length - 1)];\n const focusColumn = columns[target.endColumnIndex];\n if (!anchorRow || !anchorColumn || !focusRow || !focusColumn) return;\n table.selectCellRange(\n {\n anchorRowId: anchorRow.id,\n anchorColumnId: anchorColumn.id,\n focusRowId: focusRow.id,\n focusColumnId: focusColumn.id,\n },\n { mode: \"replace\" },\n );\n}\n\n/* ------------------------------------------------------------------------- *\n * Fill handle drag session.\n * ------------------------------------------------------------------------- */\n\n/**\n * Imperative document-level session, the column-resize pattern: preview state\n * is written as `data-cell-fill-target` attributes outside React, so the drag\n * costs zero re-renders until release. v1 fills down or right (dominant axis)\n * by repeating the source region's values; rows outside the rendered\n * viewport of a virtualized body cannot be targeted mid-drag.\n *\n * Vertical distance is measured over the rows the view can show, so a drag\n * onto a pinned draft fills exactly the rows the preview marked and never\n * the off-page rows between. A cross-column fill round-trips through the\n * source's format and the target's parse - the paste contract - because\n * adjacent grid columns are heterogeneous; a parse rejection lands in the\n * batch's rejected list, while cells that cannot be written are skipped\n * and never tinted by the preview.\n */\n// The fill drag's feedback: ONE dashed border (the Sheets fill marquee)\n// around the whole pending region - the source PLUS the extension - so the\n// drag reads as one growing region, never as a second box glued under the\n// source. While the session runs\n// the viewport carries data-cell-filling and the source cells' own\n// selection chrome rests, so this element is the only painter and nothing\n// can double at the junction. z-[35]: above the sticky pinned cells\n// (z 30) so the border survives crossing a pinned column; below the\n// sticky header (z-40).\nconst dataGridGestureOutlineClasses =\n \"outline-primary pointer-events-none absolute z-[35] outline-1 outline-dashed -outline-offset-1\";\n\nfunction startDataGridFillSession<TData extends object>(options: {\n table: DataGridTableInstance<TData>;\n viewport: HTMLElement;\n onCellsChange: ((details: DataGridCellsChangeDetails<TData>) => void) | null;\n}) {\n const { table, viewport, onCellsChange } = options;\n // Fill over a multi-region selection is undefined territory; Excel refuses\n // it too.\n if (table.getCellSelectionBounds().length > 1) return;\n const bound = getDataGridActiveBound(table);\n if (!bound) return;\n\n const rows = table.getRowsInDisplayOrder();\n const columns = getDataGridDisplayOrderedColumns(table);\n // The vertical walk space: rows the view can show, in display order. The\n // DOM ids seed it (a drag can only target rendered rows), and one pass\n // over the cached display array resolves them without building per-row\n // wrappers for a 50k-row model.\n const domRowIds = new Set<string>();\n for (const rowEl of Array.from(viewport.querySelectorAll(\"tbody tr[data-row-id]\"))) {\n const id = rowEl.getAttribute(\"data-row-id\");\n if (id) domRowIds.add(id);\n }\n const visibleRows: Array<{ row: (typeof rows)[number]; displayIndex: number }> = [];\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i]!;\n if (domRowIds.has(row.id)) {\n visibleRows.push({ row, displayIndex: i });\n }\n }\n const visibleIndexById = new Map(visibleRows.map((entry, index) => [entry.row.id, index]));\n // The source region and its last row, both in visible space.\n const sourceRows = visibleRows.filter(\n ({ displayIndex }) => displayIndex >= bound.minRowIndex && displayIndex <= bound.maxRowIndex,\n );\n const sourceEndVisibleIndex = sourceRows.length\n ? visibleIndexById.get(sourceRows[sourceRows.length - 1]!.row.id)!\n : -1;\n if (sourceEndVisibleIndex === -1) return;\n const columnIndexById = new Map(columns.map((column, index) => [column.id, index]));\n const isFillableColumn = (column: (typeof columns)[number]) =>\n column.columnDef.enableCellSelection !== false && !!getDataGridWritableCellEdit<TData>(column);\n\n let extension: { axis: \"row\" | \"column\"; count: number } | null = null;\n let previewCells: Element[] = [];\n\n const previewOutline = viewport.ownerDocument.createElement(\"div\");\n previewOutline.setAttribute(\"data-slot\", \"data-grid-cell-fill-preview\");\n previewOutline.className = dataGridGestureOutlineClasses;\n previewOutline.style.display = \"none\";\n viewport.appendChild(previewOutline);\n viewport.setAttribute(\"data-cell-filling\", \"\");\n\n // The region border wraps source plus extension: its corners are the\n // source region's first cell and the farthest cell the drag reaches\n // (the source's own last cell while nothing is extended).\n const sourceCorner = (rowId: string, columnId: string | undefined) =>\n columnId\n ? viewport.querySelector(\n `tr[data-row-id=\"${CSS.escape(rowId)}\"] td[data-col-id=\"${CSS.escape(columnId)}\"]`,\n )\n : null;\n const positionPreviewOutline = () => {\n const first = sourceRows.length\n ? sourceCorner(sourceRows[0]!.row.id, columns[bound.minColumnIndex]?.id)\n : null;\n const lastSource = sourceRows.length\n ? sourceCorner(sourceRows[sourceRows.length - 1]!.row.id, columns[bound.maxColumnIndex]?.id)\n : null;\n const far = previewCells.length ? previewCells[previewCells.length - 1]! : lastSource;\n if (!first || !far) {\n previewOutline.style.display = \"none\";\n return;\n }\n const firstRect = first.getBoundingClientRect();\n const farRect = far.getBoundingClientRect();\n const viewportRect = viewport.getBoundingClientRect();\n const left = Math.min(firstRect.left, farRect.left);\n const top = Math.min(firstRect.top, farRect.top);\n previewOutline.style.display = \"block\";\n previewOutline.style.left = `${left - viewportRect.left + viewport.scrollLeft}px`;\n previewOutline.style.top = `${top - viewportRect.top + viewport.scrollTop}px`;\n previewOutline.style.width = `${Math.max(firstRect.right, farRect.right) - left}px`;\n previewOutline.style.height = `${Math.max(firstRect.bottom, farRect.bottom) - top}px`;\n };\n\n const clearPreview = () => {\n for (const cell of previewCells) cell.removeAttribute(\"data-cell-fill-target\");\n previewCells = [];\n positionPreviewOutline();\n };\n\n // Target rows and columns for the current extension: rows in visible\n // space, and only the columns the commit would actually write, so the\n // preview never tints a cell the release will skip.\n const getExtensionTargets = () => {\n if (!extension) return null;\n const columnEntries = columns.map((column, displayIndex) => ({\n column,\n displayIndex,\n }));\n return extension.axis === \"row\"\n ? {\n rowEntries: visibleRows.slice(\n sourceEndVisibleIndex + 1,\n sourceEndVisibleIndex + 1 + extension.count,\n ),\n columnEntries: columnEntries\n .slice(bound.minColumnIndex, bound.maxColumnIndex + 1)\n .filter(({ column }) => isFillableColumn(column)),\n }\n : {\n rowEntries: sourceRows,\n columnEntries: columnEntries\n .slice(bound.maxColumnIndex + 1, bound.maxColumnIndex + 1 + extension.count)\n .filter(({ column }) => isFillableColumn(column)),\n };\n };\n\n const applyPreview = () => {\n clearPreview();\n const targets = getExtensionTargets();\n if (!targets) return;\n for (const { row } of targets.rowEntries) {\n const rowElement = viewport.querySelector(`tr[data-row-id=\"${CSS.escape(row.id)}\"]`);\n if (!rowElement) continue;\n for (const { column } of targets.columnEntries) {\n if (!getDataGridWritableCellEdit<TData>(column, row.original)) continue;\n const cellElement = rowElement.querySelector(`td[data-col-id=\"${CSS.escape(column.id)}\"]`);\n if (!cellElement) continue;\n cellElement.setAttribute(\"data-cell-fill-target\", \"true\");\n previewCells.push(cellElement);\n }\n }\n\n positionPreviewOutline();\n };\n\n const handleMove = (event: MouseEvent) => {\n const element = document.elementFromPoint(event.clientX, event.clientY);\n const cellElement = element?.closest?.(\"td[data-col-id]\");\n const rowElement = cellElement?.closest?.(\"tr[data-row-id]\");\n if (!cellElement || !rowElement || !viewport.contains(cellElement)) return;\n\n const rowVisibleIndex = visibleIndexById.get(rowElement.getAttribute(\"data-row-id\") ?? \"\");\n const columnIndex = columnIndexById.get(cellElement.getAttribute(\"data-col-id\") ?? \"\");\n if (rowVisibleIndex === undefined || columnIndex === undefined) return;\n\n const rowsDelta = Math.max(0, rowVisibleIndex - sourceEndVisibleIndex);\n const columnsDelta = Math.max(0, columnIndex - bound.maxColumnIndex);\n const next: typeof extension =\n rowsDelta === 0 && columnsDelta === 0\n ? null\n : rowsDelta >= columnsDelta\n ? { axis: \"row\", count: rowsDelta }\n : { axis: \"column\", count: columnsDelta };\n\n if (next?.axis === extension?.axis && next?.count === extension?.count) {\n return;\n }\n extension = next;\n applyPreview();\n };\n\n const finish = (commit: boolean) => {\n document.removeEventListener(\"mousemove\", handleMove);\n document.removeEventListener(\"mouseup\", handleUp);\n document.removeEventListener(\"keydown\", handleKey, true);\n clearPreview();\n previewOutline.remove();\n viewport.removeAttribute(\"data-cell-filling\");\n if (!commit || !extension || !onCellsChange) return;\n const targets = getExtensionTargets();\n if (!targets?.rowEntries.length) return;\n\n const changes: DataGridCellChange<TData>[] = [];\n const rejected: DataGridCellRejection[] = [];\n\n if (extension.axis === \"row\") {\n for (let offset = 0; offset < targets.rowEntries.length; offset++) {\n const targetRow = targets.rowEntries[offset]!.row;\n const sourceRow = sourceRows[offset % sourceRows.length]!.row;\n const targetCells = targetRow.getAllCellsByColumnId();\n const sourceCells = sourceRow.getAllCellsByColumnId();\n for (const { column } of targets.columnEntries) {\n if (!getDataGridWritableCellEdit<TData>(column, targetRow.original)) {\n continue;\n }\n changes.push({\n rowId: targetRow.id,\n columnId: column.id,\n row: targetRow.original,\n previousValue: targetCells[column.id]?.getValue(),\n value: sourceCells[column.id]?.getValue(),\n });\n }\n }\n } else {\n const regionColumns = bound.maxColumnIndex - bound.minColumnIndex + 1;\n for (const { row } of targets.rowEntries) {\n const cells = row.getAllCellsByColumnId();\n for (const { column: targetColumn, displayIndex } of targets.columnEntries) {\n const offset = displayIndex - (bound.maxColumnIndex + 1);\n const sourceColumn = columns[bound.minColumnIndex + (offset % regionColumns)];\n if (!sourceColumn) continue;\n const targetEdit = getDataGridWritableCellEdit<TData>(targetColumn, row.original);\n if (!targetEdit) continue;\n const sourceValue = cells[sourceColumn.id]?.getValue();\n let value: unknown = sourceValue;\n // Crossing columns is a type boundary: round-trip through the\n // source's format and the target's parse, exactly what pasting\n // the same cells would do. Same-column fills keep raw values.\n if (targetColumn.id !== sourceColumn.id && targetEdit.parse) {\n const sourceFormat = sourceColumn.columnDef.meta?.cellEdit?.format;\n const raw = sourceFormat\n ? sourceFormat(sourceValue, row.original)\n : String(sourceValue ?? \"\");\n const parsed = targetEdit.parse(raw, row.original);\n if (parsed === undefined) {\n rejected.push({\n rowId: row.id,\n columnId: targetColumn.id,\n raw,\n reason: \"invalid\",\n });\n continue;\n }\n value = parsed;\n }\n changes.push({\n rowId: row.id,\n columnId: targetColumn.id,\n row: row.original,\n previousValue: cells[targetColumn.id]?.getValue(),\n value,\n });\n }\n }\n }\n\n if (changes.length || rejected.length) {\n onCellsChange({ source: \"fill\", changes, rejected });\n }\n\n // Grow the selection over source plus filled cells, Excel's post-fill\n // shape.\n selectDataGridRegion(table, {\n startRowIndex: bound.minRowIndex,\n endRowIndex:\n extension.axis === \"row\"\n ? targets.rowEntries[targets.rowEntries.length - 1]!.displayIndex\n : bound.maxRowIndex,\n startColumnIndex: bound.minColumnIndex,\n endColumnIndex: bound.maxColumnIndex + (extension.axis === \"column\" ? extension.count : 0),\n });\n };\n\n const handleUp = () => finish(true);\n // Capture phase so a cancel cannot also reach the grid's own Escape\n // handling and clear the selection underneath the drag.\n const handleKey = (event: KeyboardEvent) => {\n if (event.key !== \"Escape\") return;\n event.stopPropagation();\n finish(false);\n };\n\n document.addEventListener(\"mousemove\", handleMove);\n document.addEventListener(\"mouseup\", handleUp);\n document.addEventListener(\"keydown\", handleKey, true);\n}\n\n/* ------------------------------------------------------------------------- *\n * Controller.\n * ------------------------------------------------------------------------- */\n\nfunction isDataGridEditableTarget(target: EventTarget | null): boolean {\n // data-cell-interactive is the same opt-out the mousedown guard honors, so\n // a custom widget keeps its own keys and clipboard as well as its clicks.\n return (\n target instanceof Element &&\n target.closest(\"input, textarea, select, [contenteditable], [data-cell-interactive]\") != null\n );\n}\n\n// Keys belong to a focused in-cell control the same way clicks do: the\n// button, link and checkbox set the mousedown guard exempts must keep its\n// native Enter, Space and Tab, or an in-cell button is keyboard-dead.\n// Clipboard stays on the narrower guard: copying the grid selection while a\n// button happens to hold focus is what a spreadsheet user expects.\nfunction isDataGridInteractiveKeyTarget(target: EventTarget | null): boolean {\n return (\n isDataGridEditableTarget(target) ||\n (target instanceof Element && target.closest('button, a, [role=\"checkbox\"]') != null)\n );\n}\n\n/**\n * Headless spreadsheet controller: keyboard navigation, clipboard, clear and\n * the fill-handle drag. Mount once inside `<DataGrid>`, next to the table.\n * Renders only a hidden anchor; the real listeners attach to the grid's own\n * body viewport, which also receives focus (container-focus model), so a\n * virtualized row unmounting can never strand `document.activeElement`.\n */\nfunction DataGridCellSelection<TData extends object>({\n apiRef,\n clipboard = true,\n keyboard = true,\n}: {\n /** Receives the controller's imperative API, e.g. for create-row flows. */\n apiRef?: RefObject<DataGridCellSelectionApi | null>;\n /** Native copy, cut and paste handling. Defaults to true. */\n clipboard?: boolean;\n /**\n * Arrows (with Ctrl/Cmd edge jumps), Home/End, PageUp/PageDown, Enter,\n * F2, type-to-edit, Tab, Ctrl/Cmd+A, Delete, Escape. Defaults to true.\n */\n keyboard?: boolean;\n}) {\n // The context value serves `table` and `props` through getters over the\n // provider's own refs, so a context object captured at mount keeps handing\n // out the CURRENT instances; no ref mirror is needed here.\n const context = useDataGrid<TData>();\n\n const anchorRef = useRef<HTMLSpanElement | null>(null);\n // The body viewport, once the wiring effect resolves it; the built-in\n // editor overlay portals into it so it scrolls with the cells.\n const [viewportEl, setViewportEl] = useState<HTMLElement | null>(null);\n const [editorSession, setEditorSession] = useState<DataGridEditorSession | null>(null);\n const { table } = context;\n const enabled = !!context.props.tableLayout?.cellSelection && table.atoms.cellSelection != null;\n\n useEffect(() => {\n if (!enabled) return;\n const anchor = anchorRef.current;\n if (!anchor) return;\n\n const root = (anchor.closest('[data-slot=\"data-grid\"]') ??\n anchor.parentElement) as HTMLElement | null;\n if (!root) return;\n\n // Split header/body grids render two viewports; the body one owns focus.\n const viewports = Array.from(\n root.querySelectorAll<HTMLElement>('[data-slot=\"data-grid-table-viewport\"]'),\n );\n const viewport =\n viewports.find((node) => node.querySelector('[data-slot=\"data-grid-table-body\"]')) ??\n viewports[0];\n if (!viewport) return;\n\n const getTable = () => context.table;\n const getOnCellsChange = () => context.props.onCellsChange ?? null;\n // \"single\" collapses every grow gesture to the focused cell.\n const isRangeSelectionEnabled = () => context.props.tableLayout?.cellSelectionMode !== \"single\";\n\n // The focusable element of the container-focus model. The table carries\n // role=\"grid\", so putting DOM focus (and aria-activedescendant) on it is\n // what lets a screen reader follow the focused cell.\n const focusTarget =\n viewport.querySelector<HTMLElement>('table[data-slot=\"data-grid-table\"]') ?? viewport;\n\n const scrollTdIntoView = (cell: Element | null) =>\n // Optional call: jsdom and some embedded contexts ship elements\n // without scrollIntoView.\n cell?.scrollIntoView?.({\n block: \"nearest\",\n inline: \"nearest\",\n behavior: \"instant\",\n });\n\n // Points assistive tech at the virtually focused cell.\n const syncActiveDescendant = () => {\n const cell = viewport.querySelector<HTMLElement>(\"td[data-cell-focused]\");\n if (cell?.id) focusTarget.setAttribute(\"aria-activedescendant\", cell.id);\n else focusTarget.removeAttribute(\"aria-activedescendant\");\n };\n\n const scrollFocusedIntoView = (\n targetRowIndex?: number,\n rowCount?: number,\n // A Shift-extend grows away from the focused cell, which stays the\n // anchor; the caller names the range's active corner so the view\n // follows the growing edge instead of snapping back to the anchor.\n explicitCell?: { rowId: string; columnId: string },\n ) => {\n const queryScrollCell = () =>\n explicitCell\n ? viewport.querySelector(\n `tr[data-row-id=\"${CSS.escape(explicitCell.rowId)}\"] td[data-col-id=\"${CSS.escape(explicitCell.columnId)}\"]`,\n )\n : viewport.querySelector(\"td[data-cell-focused]\");\n // After the atom write React still has to commit the data attributes;\n // rAF lands after that commit. Instant, because the app-level\n // scroll-smooth would otherwise animate every keystroke.\n requestAnimationFrame(() => {\n const cell = queryScrollCell();\n syncActiveDescendant();\n if (cell || targetRowIndex == null || !rowCount) {\n scrollTdIntoView(cell);\n return;\n }\n // Virtualization: the jump target is not mounted, so there is no td\n // to scroll to. The spacer rows keep scrollHeight proportional to\n // the row count, so estimate the offset, let the virtualizer mount\n // the region, then finish with a precise nearest-scroll.\n let scroller: HTMLElement | null = viewport;\n while (scroller && scroller.scrollHeight <= scroller.clientHeight) {\n scroller = scroller.parentElement;\n }\n if (!scroller) return;\n scroller.scrollTop =\n ((targetRowIndex + 0.5) / rowCount) * scroller.scrollHeight - scroller.clientHeight / 2;\n requestAnimationFrame(() => {\n scrollTdIntoView(queryScrollCell());\n syncActiveDescendant();\n });\n });\n };\n\n // Opens an editor for the focused writable cell: the grid's own overlay\n // for a column with a built-in `control`, the consumer's via\n // `onCellEditRequest` otherwise, and as a last resort the cell's own\n // interactive content (activated the way a mouse would). Returns false\n // when nothing can open so the caller falls back to plain navigation.\n const requestCellEdit = (initialText?: string): boolean => {\n const table = getTable();\n const cell = table.getFocusedCell();\n if (!cell) return false;\n const cellEdit = getDataGridWritableCellEdit<TData>(cell.column, cell.row.original);\n if (cellEdit?.control) {\n const baseline = cellEdit.format\n ? cellEdit.format(cell.getValue(), cell.row.original)\n : String(cell.getValue() ?? \"\");\n const headerTitle = cell.column.columnDef.meta?.headerTitle;\n const header = cell.column.columnDef.header;\n setEditorSession({\n rowId: cell.row.id,\n columnId: cell.column.id,\n control: cellEdit.control,\n initialValue: initialText ?? baseline,\n baseline,\n label:\n typeof headerTitle === \"string\"\n ? headerTitle\n : typeof header === \"string\"\n ? header\n : cell.column.id,\n });\n return true;\n }\n const onCellEditRequest = context.props.onCellEditRequest;\n if (cellEdit && onCellEditRequest) {\n onCellEditRequest({\n rowId: cell.row.id,\n columnId: cell.column.id,\n row: cell.row.original,\n previousValue: cell.getValue(),\n initialText,\n });\n return true;\n }\n // Generic activation: a custom control rendered in the cell (a\n // select trigger, a combobox input, a button) toggles from the\n // keyboard without any consumer wiring - focus it and click it,\n // the same gesture the mouse performs. The lookup is ORDERED so an\n // incidental button (a chip's remove button before a combobox\n // input) never outranks the cell's primary control.\n // Deliberate activation only (Enter, F2, double-click): typing a\n // printable character must never toggle a control it cannot type\n // into, and there is nowhere to put the character.\n if (initialText !== undefined) return false;\n const focusedCell = viewport.querySelector(\"td[data-cell-focused]\");\n const control = focusedCell\n ? [\n '[role=\"combobox\"]',\n \"select\",\n \"input, textarea\",\n 'button, a, [role=\"checkbox\"], [tabindex]:not([tabindex=\"-1\"])',\n ]\n .map((candidate) => focusedCell.querySelector<HTMLElement>(candidate))\n .find(Boolean)\n : null;\n if (!control) return false;\n control.focus();\n control.click();\n return true;\n };\n\n // The imperative surface. A consumer that creates a row cannot focus\n // its cell through state alone: setFocusedCell needs the row in the\n // table model, DOM focus needs the focus target, and both race the\n // commit that mounts the row. One bounded timer retry (timers, unlike\n // animation frames, run in background tabs) settles all of it in order.\n let focusRetryTimer: ReturnType<typeof setTimeout> | undefined;\n const focusCell: DataGridCellSelectionApi[\"focusCell\"] = (rowId, columnId, options) => {\n // A newer call supersedes any chain still polling for an older row.\n clearTimeout(focusRetryTimer);\n let attempts = 12;\n const attempt = () => {\n // The grid can unmount mid-retry; a stale timer must go quiet.\n if (!viewport.isConnected) return;\n const cell = viewport.querySelector<HTMLElement>(\n `tr[data-row-id=\"${CSS.escape(rowId)}\"] td[data-col-id=\"${CSS.escape(columnId)}\"]`,\n );\n if (!cell) {\n if (attempts-- > 0) focusRetryTimer = setTimeout(attempt, 32);\n return;\n }\n getTable().setFocusedCell(rowId, columnId);\n focusTarget.focus();\n // The cell's id is static, so assistive tech can point at it ahead\n // of the data-cell-focused commit the rAF sync waits for.\n if (cell.id) focusTarget.setAttribute(\"aria-activedescendant\", cell.id);\n scrollTdIntoView(cell);\n if (!options?.edit) return;\n // The built-in overlay measures td[data-cell-focused], so the edit\n // request waits for that attribute to land.\n let editAttempts = 12;\n const attemptEdit = () => {\n if (!cell.isConnected) return;\n if (cell.hasAttribute(\"data-cell-focused\")) requestCellEdit();\n else if (editAttempts-- > 0) {\n focusRetryTimer = setTimeout(attemptEdit, 32);\n }\n };\n attemptEdit();\n };\n attempt();\n };\n const clearSelection = () => {\n getTable().resetCellSelection(true);\n requestAnimationFrame(syncActiveDescendant);\n };\n const scrollToCell = (rowId: string, columnId: string) => {\n scrollTdIntoView(\n viewport.querySelector(\n `tr[data-row-id=\"${CSS.escape(rowId)}\"] td[data-col-id=\"${CSS.escape(columnId)}\"]`,\n ),\n );\n };\n if (apiRef) apiRef.current = { focusCell, clearSelection, scrollToCell };\n\n // Resolves jump targets (Home, End, Ctrl+Arrows, PageUp/PageDown) in the\n // feature's display-index space and lands them through the range API:\n // plain jumps collapse to the target cell, Shift jumps keep the active\n // range's opposite corner as the anchor, the Excel model.\n const jumpFocus = (\n rowTarget: \"first\" | \"last\" | \"same\" | { delta: number },\n columnTarget: \"first\" | \"last\" | \"same\",\n extend: boolean,\n ): boolean => {\n const table = getTable();\n const focused = table.getFocusedCell();\n if (!focused) return false;\n const rows = table.getRowsInDisplayOrder();\n const allColumns = getDataGridDisplayOrderedColumns(table);\n const selectable = allColumns.filter(\n (column) => column.columnDef.enableCellSelection !== false,\n );\n if (!rows.length || !selectable.length) return false;\n const rowIndex = focused.row.getDisplayIndex();\n const targetRowIndex =\n rowTarget === \"first\"\n ? 0\n : rowTarget === \"last\"\n ? rows.length - 1\n : rowTarget === \"same\"\n ? rowIndex\n : Math.min(rows.length - 1, Math.max(0, rowIndex + rowTarget.delta));\n // Pagination renders a window of the display order; walk the target\n // back toward the focus until it lands on a rendered row, so a jump\n // can never focus an off-page row the view cannot show. DOM rows\n // join the set so pinned rows outside the page slice stay reachable.\n let clampedRowIndex = targetRowIndex;\n // With the whole display order in the page slice nothing is off-page\n // and the clamp cannot move, so skip building the id set.\n if (table.getRowModel().rows.length !== rows.length) {\n const rendered = new Set<string | null>(\n table.getRowModel().rows.map((row: { id: string }) => row.id),\n );\n for (const rowEl of Array.from(viewport.querySelectorAll(\"tbody tr[data-row-id]\"))) {\n rendered.add(rowEl.getAttribute(\"data-row-id\"));\n }\n const step = clampedRowIndex >= rowIndex ? -1 : 1;\n while (\n clampedRowIndex !== rowIndex &&\n rows[clampedRowIndex] &&\n !rendered.has(rows[clampedRowIndex].id)\n ) {\n clampedRowIndex += step;\n }\n }\n const targetRow = rows[clampedRowIndex];\n const targetColumn =\n columnTarget === \"first\"\n ? selectable[0]\n : columnTarget === \"last\"\n ? selectable[selectable.length - 1]\n : focused.column;\n if (!targetRow || !targetColumn) return false;\n if (extend) {\n const bound = getDataGridActiveBound(table);\n const columnIndex = allColumns.findIndex((column) => column.id === focused.column.id);\n let anchorRowId = focused.row.id;\n let anchorColumnId = focused.column.id;\n if (bound) {\n anchorRowId =\n rows[rowIndex === bound.minRowIndex ? bound.maxRowIndex : bound.minRowIndex]?.id ??\n anchorRowId;\n anchorColumnId =\n allColumns[\n columnIndex === bound.minColumnIndex ? bound.maxColumnIndex : bound.minColumnIndex\n ]?.id ?? anchorColumnId;\n }\n table.selectCellRange(\n {\n anchorRowId,\n anchorColumnId,\n focusRowId: targetRow.id,\n focusColumnId: targetColumn.id,\n },\n { mode: \"replace\" },\n );\n } else {\n table.setFocusedCell(targetRow.id, targetColumn.id);\n }\n scrollFocusedIntoView(\n clampedRowIndex,\n rows.length,\n // The extend keeps focus on the anchor; follow the jump target.\n extend ? { rowId: targetRow.id, columnId: targetColumn.id } : undefined,\n );\n return true;\n };\n\n // One visual-space focus step with the feature's move as the fallback\n // for unresolvable positions; at an edge the focus stays put.\n const moveFocusVisual = (direction: \"up\" | \"down\" | \"left\" | \"right\"): void => {\n const table = getTable();\n const focused = table.getFocusedCell();\n const target = focused\n ? getDataGridStepTarget(\n table,\n viewport,\n { rowId: focused.row.id, columnId: focused.column.id },\n direction,\n )\n : null;\n if (target === \"edge\") return;\n if (target) {\n table.setFocusedCell(target.rowId, target.columnId);\n return;\n }\n table.moveCellSelection(direction);\n };\n\n // One viewport's worth of rows for PageUp/PageDown, measured from the\n // live layout; 10 when nothing is measurable (jsdom). Data rows only:\n // the virtual table's spacer rows carry the whole scroll offset as\n // height and would collapse the page size to a single row.\n const getPageJumpSize = (): number => {\n const row = viewport.querySelector(\"tbody tr[data-row-id]\");\n // The nearest ancestor that actually scrolls; in the scroll-area\n // layout the viewport's parent is a full-height content wrapper\n // whose clientHeight would make the page span the whole table.\n let scroller: HTMLElement | null = viewport;\n while (scroller && scroller.scrollHeight <= scroller.clientHeight) {\n scroller = scroller.parentElement;\n }\n const rowHeight = row?.getBoundingClientRect().height || 0;\n const viewHeight = scroller?.clientHeight || viewport.clientHeight;\n if (!rowHeight || !viewHeight) return 10;\n return Math.max(1, Math.floor(viewHeight / rowHeight) - 1);\n };\n\n // The rows appended after the data rows: the add-row affordance and a\n // consumer appendRow draft. Positional, because an id-less tr is not\n // enough - expanded-detail rows interleave BETWEEN data rows and the\n // empty-state row stands alone, and neither belongs to this region.\n // Virtual spacer rows are aria-hidden and never match.\n const getAppendedRows = (): HTMLElement[] => {\n const body = viewport.querySelector(\"tbody\");\n const appended: HTMLElement[] = [];\n // Backwards from the end, stopping at the first data row: O(appended)\n // instead of an array of every rendered row per keystroke.\n let rowEl = body?.lastElementChild;\n while (rowEl && !rowEl.hasAttribute(\"data-row-id\")) {\n if (rowEl instanceof HTMLElement && !rowEl.hasAttribute(\"aria-hidden\")) {\n appended.unshift(rowEl);\n }\n rowEl = rowEl.previousElementSibling;\n }\n return appended;\n };\n\n const focusFirstIn = (row: HTMLElement | undefined): boolean => {\n const focusable = row?.querySelector<HTMLElement>(\n 'button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])',\n );\n if (!focusable) return false;\n focusable.focus();\n // A control that refuses focus (hidden, inert) must not report\n // success, or the arrow key that called this dead-ends.\n return row!.ownerDocument.activeElement === focusable;\n };\n\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.defaultPrevented) return;\n\n // Unified keyboard for the appended region: ArrowDown/ArrowUp walk\n // between its rows, and ArrowUp from its first row returns to the\n // grid's cell navigation. Every other key stays native there.\n const appendedRow =\n event.target instanceof Element\n ? (event.target.closest(\"tbody > tr:not([data-row-id])\") as HTMLElement | null)\n : null;\n if (appendedRow && viewport.contains(appendedRow)) {\n const appended = getAppendedRows();\n const index = appended.indexOf(appendedRow);\n // An id-less row that is NOT appended (expanded detail content,\n // the empty-state row) keeps every key native.\n if (index === -1) return;\n if (event.key !== \"ArrowUp\" && event.key !== \"ArrowDown\") return;\n if (event.key === \"ArrowDown\") {\n if (focusFirstIn(appended[index + 1])) event.preventDefault();\n return;\n }\n if (index > 0 && focusFirstIn(appended[index - 1])) {\n event.preventDefault();\n return;\n }\n // Back into the grid, on whatever cell was focused last.\n focusTarget.focus();\n syncActiveDescendant();\n event.preventDefault();\n return;\n }\n\n if (isDataGridInteractiveKeyTarget(event.target)) {\n // The ARIA grid pattern's exit gesture: Escape on an in-cell\n // control hands DOM focus back to the grid so navigation resumes.\n // A control that consumed the key first (closing its own popup)\n // never lets it reach here unprevented, and portal-rendered\n // popups keep their Escape entirely outside the viewport.\n if (event.key === \"Escape\") {\n const cell = (event.target as Element).closest?.(\"td[data-col-id]\");\n if (cell && viewport.contains(cell)) {\n event.preventDefault();\n event.stopPropagation();\n focusTarget.focus();\n syncActiveDescendant();\n }\n }\n return;\n }\n const table = getTable();\n const rtl = getComputedStyle(viewport).direction === \"rtl\";\n const horizontal = (direction: \"left\" | \"right\") =>\n rtl ? (direction === \"left\" ? \"right\" : \"left\") : direction;\n\n // Ahead of the switch so plain letters still reach the type-to-edit\n // fall-through below. Matched by code as well as key, so non-Latin\n // layouts (where the key is the layout's own character) still work.\n if (\n (event.key === \"a\" || event.key === \"A\" || event.code === \"KeyA\") &&\n (event.metaKey || event.ctrlKey) &&\n // AltGr arrives as Ctrl+Alt; that chord types a character on\n // central-European layouts and is not a select-all.\n !event.altKey\n ) {\n if (isRangeSelectionEnabled()) {\n table.selectAllCells();\n // Select-all moves the feature's focus to the range corner,\n // which can sit off-page; keep assistive tech pointed right.\n requestAnimationFrame(syncActiveDescendant);\n }\n event.preventDefault();\n return;\n }\n\n // Explicit copy and cut chords; see writeSelectionToClipboard for\n // why the native copy event cannot carry these. Paste stays on the\n // native event, which browsers do fire at the focused element.\n if ((event.metaKey || event.ctrlKey) && !event.altKey && clipboard) {\n const isCopy = event.key === \"c\" || event.key === \"C\" || event.code === \"KeyC\";\n const isCut = event.key === \"x\" || event.key === \"X\" || event.code === \"KeyX\";\n if (isCopy || isCut) {\n event.preventDefault();\n void writeSelectionToClipboard().then((written) => {\n if (!written) return;\n context.props.onCellsCopy?.({ ...written, cut: isCut });\n if (!isCut) return;\n const onCellsChange = getOnCellsChange();\n if (!onCellsChange) return;\n const details = buildDataGridClearDetails<TData>(getTable(), \"cut\", true, viewport);\n if (details) onCellsChange(details);\n });\n return;\n }\n }\n\n switch (event.key) {\n case \"ArrowUp\":\n case \"ArrowDown\":\n case \"ArrowLeft\":\n case \"ArrowRight\": {\n const direction =\n event.key === \"ArrowUp\"\n ? (\"up\" as const)\n : event.key === \"ArrowDown\"\n ? (\"down\" as const)\n : horizontal(event.key === \"ArrowLeft\" ? \"left\" : \"right\");\n if (event.metaKey || event.ctrlKey) {\n // Ctrl/Cmd+Arrow jumps to the grid edge in that direction.\n const jumped =\n direction === \"up\"\n ? jumpFocus(\"first\", \"same\", event.shiftKey && isRangeSelectionEnabled())\n : direction === \"down\"\n ? jumpFocus(\"last\", \"same\", event.shiftKey && isRangeSelectionEnabled())\n : jumpFocus(\n \"same\",\n direction === \"left\" ? \"first\" : \"last\",\n event.shiftKey && isRangeSelectionEnabled(),\n );\n if (jumped) event.preventDefault();\n return;\n }\n // ArrowDown on the last rendered row steps into the appended\n // region (a draft row, or the add-row affordance), keeping one\n // keyboard model across the whole table.\n if (direction === \"down\" && !event.shiftKey) {\n const focused = table.getFocusedCell();\n const renderedRows = viewport.querySelectorAll(\"tbody tr[data-row-id]\");\n const lastRenderedId =\n renderedRows[renderedRows.length - 1]?.getAttribute(\"data-row-id\");\n if (\n focused &&\n lastRenderedId &&\n focused.row.id === lastRenderedId &&\n focusFirstIn(getAppendedRows()[0])\n ) {\n event.preventDefault();\n return;\n }\n }\n if (event.shiftKey && isRangeSelectionEnabled()) {\n const corner = extendDataGridSelection(table, viewport, direction);\n event.preventDefault();\n scrollFocusedIntoView(undefined, undefined, corner ?? undefined);\n return;\n }\n // Plain arrows step in visual space so navigation crosses\n // pinned rows and pagination windows the feature's own move\n // cannot resolve; at a visual edge the focus stays put.\n const focused = table.getFocusedCell();\n const target = focused\n ? getDataGridStepTarget(\n table,\n viewport,\n { rowId: focused.row.id, columnId: focused.column.id },\n direction,\n )\n : null;\n if (target === \"edge\") {\n event.preventDefault();\n return;\n }\n if (target) {\n table.setFocusedCell(target.rowId, target.columnId);\n event.preventDefault();\n scrollFocusedIntoView();\n return;\n }\n table.moveCellSelection(direction);\n event.preventDefault();\n scrollFocusedIntoView();\n return;\n }\n case \"Home\":\n case \"End\": {\n // Home/End: row start or end; with Ctrl/Cmd, the grid's corners.\n const edge = event.key === \"Home\" ? (\"first\" as const) : (\"last\" as const);\n const jumped =\n event.metaKey || event.ctrlKey\n ? jumpFocus(edge, edge, event.shiftKey && isRangeSelectionEnabled())\n : jumpFocus(\"same\", edge, event.shiftKey && isRangeSelectionEnabled());\n if (jumped) event.preventDefault();\n return;\n }\n case \"PageUp\":\n case \"PageDown\": {\n const delta = (event.key === \"PageUp\" ? -1 : 1) * getPageJumpSize();\n if (jumpFocus({ delta }, \"same\", event.shiftKey && isRangeSelectionEnabled())) {\n event.preventDefault();\n }\n return;\n }\n case \"Enter\": {\n // The Notion/Airtable flow: Enter opens the editor when one is\n // wired; the Excel move-down stays the fallback.\n if (!event.shiftKey && requestCellEdit()) {\n event.preventDefault();\n return;\n }\n moveFocusVisual(event.shiftKey ? \"up\" : \"down\");\n event.preventDefault();\n scrollFocusedIntoView();\n return;\n }\n case \"F2\": {\n if (requestCellEdit()) event.preventDefault();\n return;\n }\n case \"Tab\": {\n const before = table.getFocusedCell();\n // Logical directions, no RTL swap: Tab means \"next cell\" in both\n // reading directions, exactly like DOM tab order.\n moveFocusVisual(event.shiftKey ? \"left\" : \"right\");\n const after = table.getFocusedCell();\n // Trap Tab only while it moved; at the edges focus leaves the grid,\n // which keyboard users need to escape it at all.\n if (after && after.id !== before?.id) {\n event.preventDefault();\n scrollFocusedIntoView();\n }\n return;\n }\n case \"Delete\":\n case \"Backspace\": {\n const onCellsChange = getOnCellsChange();\n if (!onCellsChange) return;\n const details = buildDataGridClearDetails<TData>(table, \"clear\", false, viewport);\n if (details) onCellsChange(details);\n event.preventDefault();\n return;\n }\n case \"Escape\": {\n // Consume the key only while it has a selection to clear, so a\n // grid inside a dialog still lets Escape close the dialog.\n if (table.getCellSelectionBounds().length) {\n table.resetCellSelection(true);\n // The focused-cell attribute is gone after the commit;\n // aria-activedescendant must not keep naming it.\n requestAnimationFrame(syncActiveDescendant);\n event.preventDefault();\n event.stopPropagation();\n }\n return;\n }\n }\n\n // Space on a cell whose content is a checkbox toggles it, the\n // row-select idiom, so the selection column works by keyboard too.\n if (event.key === \" \") {\n const checkbox = viewport\n .querySelector(\"td[data-cell-focused]\")\n ?.querySelector<HTMLElement>('[role=\"checkbox\"], input[type=\"checkbox\"]');\n if (checkbox) {\n checkbox.click();\n event.preventDefault();\n return;\n }\n }\n\n // Type-to-edit: a printable character on the focused cell opens the\n // editor seeded with it, replacing the value the way Notion and\n // Airtable do. Plain Ctrl/Cmd chords stay shortcuts, but Ctrl+Alt is\n // AltGr and bare Alt is the macOS Option layer - both type characters.\n if (\n event.key.length === 1 &&\n !event.metaKey &&\n !(event.ctrlKey && !event.altKey) &&\n requestCellEdit(event.key)\n ) {\n event.preventDefault();\n return;\n }\n\n // Space that opened nothing (read-only cell) must not scroll the page\n // out from under the focused cell.\n if (event.key === \" \" && table.getFocusedCell()) {\n event.preventDefault();\n }\n };\n\n // Writes the active region to the system clipboard in both flavors.\n // Needed because a native copy event only fires for a text selection\n // or an editable target, and a focused grid is neither - Cmd/Ctrl+C\n // would silently do nothing on macOS, Windows and Linux alike. The\n // async API needs a secure context; the execCommand fallback covers\n // the rest with the TSV flavor alone.\n const writeSelectionToClipboard = async (): Promise<{\n text: string;\n grid: string[][];\n } | null> => {\n const grid = getDataGridActiveRegionGrid(getTable(), viewport);\n if (!grid) return null;\n const text = serializeDataGridClipboardText(grid);\n try {\n if (typeof ClipboardItem !== \"undefined\" && navigator.clipboard?.write) {\n await navigator.clipboard.write([\n new ClipboardItem({\n \"text/plain\": new Blob([text], { type: \"text/plain\" }),\n \"text/html\": new Blob([renderDataGridClipboardHtml(grid)], {\n type: \"text/html\",\n }),\n }),\n ]);\n return { text, grid };\n }\n if (navigator.clipboard?.writeText) {\n await navigator.clipboard.writeText(text);\n return { text, grid };\n }\n } catch {\n // Denied or unavailable; the legacy path below still applies.\n }\n const doc = viewport.ownerDocument;\n const scratch = doc.createElement(\"textarea\");\n scratch.value = text;\n scratch.style.position = \"fixed\";\n scratch.style.opacity = \"0\";\n doc.body.appendChild(scratch);\n scratch.select();\n let copied = false;\n try {\n copied = doc.execCommand(\"copy\");\n } catch {\n copied = false;\n }\n scratch.remove();\n focusTarget.focus();\n return copied ? { text, grid } : null;\n };\n\n const copySelection = (event: ClipboardEvent, cut: boolean): boolean => {\n const grid = getDataGridActiveRegionGrid(getTable(), viewport);\n if (!grid || !event.clipboardData) return false;\n event.preventDefault();\n const text = serializeDataGridClipboardText(grid);\n event.clipboardData.setData(\"text/plain\", text);\n event.clipboardData.setData(\"text/html\", renderDataGridClipboardHtml(grid));\n context.props.onCellsCopy?.({ text, grid, cut });\n return true;\n };\n\n const handleCopy = (event: ClipboardEvent) => {\n if (isDataGridEditableTarget(event.target)) return;\n copySelection(event, false);\n };\n\n const handleCut = (event: ClipboardEvent) => {\n if (isDataGridEditableTarget(event.target)) return;\n if (!copySelection(event, true)) return;\n const onCellsChange = getOnCellsChange();\n if (!onCellsChange) return;\n const details = buildDataGridClearDetails<TData>(getTable(), \"cut\", true, viewport);\n if (details) onCellsChange(details);\n };\n\n const handlePaste = (event: ClipboardEvent) => {\n if (isDataGridEditableTarget(event.target)) return;\n const onCellsChange = getOnCellsChange();\n if (!onCellsChange) return;\n const text = event.clipboardData?.getData(\"text/plain\");\n if (!text) return;\n event.preventDefault();\n const table = getTable();\n const result = buildDataGridPasteDetails<TData>(\n table,\n parseDataGridClipboardText(text),\n viewport,\n );\n if (!result) return;\n onCellsChange(result.details);\n // The pasted region becomes the selection, the documented contract;\n // single mode keeps just the focused cell instead.\n if (isRangeSelectionEnabled()) {\n selectDataGridRegion(table, result.target);\n }\n };\n\n // Custom-control cells follow the same two-step gesture as editor\n // cells: the first click on an UNFOCUSED cell only focuses it, the\n // second activates the control, so moving the focus around can never\n // fire actions. Radix triggers open on pointerdown and Base UI ones\n // on click, so the press is intercepted at both; checkboxes keep\n // their one-click toggle (the row-select idiom), data-cell-interactive\n // widgets own all their gestures, and single-click edit mode skips\n // the interception outright.\n let pressedUnfocusedControl = false;\n const getTwoStepControl = (target: EventTarget | null): Element | null => {\n if (!(target instanceof Element)) return null;\n if (target.closest(\"[data-cell-interactive]\")) return null;\n if (target.closest('[role=\"checkbox\"], input[type=\"checkbox\"]')) {\n return null;\n }\n // Opt-in for widgets whose ACTIVE surface is bigger than any generic\n // selector can know - a combobox whose whole blank chips strip opens\n // it, a canvas editor. Marking the wrapper data-cell-control makes a\n // press anywhere on it two-step, exactly like a bare button.\n const marked = target.closest(\"[data-cell-control]\");\n if (marked) return marked;\n return target.closest(\n 'button, a, select, input, textarea, [contenteditable], [role=\"combobox\"]',\n );\n };\n const handleControlPointerDown = (event: PointerEvent) => {\n pressedUnfocusedControl = false;\n if (event.button !== 0) return;\n if (event.shiftKey || event.ctrlKey || event.metaKey) return;\n if (context.props.tableLayout?.cellEditMode === \"click\") return;\n const control = getTwoStepControl(event.target);\n const cell = control?.closest(\"td[data-col-id]\");\n if (!control || !cell || !viewport.contains(cell)) return;\n if (cell.hasAttribute(\"data-cell-focused\")) return;\n const column = getTable().getColumn(cell.getAttribute(\"data-col-id\") ?? \"\");\n if (!column || column.columnDef.enableCellSelection === false) return;\n pressedUnfocusedControl = true;\n // Stops a Radix trigger's pointerdown open before React's root\n // delegation sees it; the mouse events that focus the cell ride on.\n event.stopPropagation();\n };\n const handleControlClick = (event: MouseEvent) => {\n if (!pressedUnfocusedControl) return;\n pressedUnfocusedControl = false;\n // Swallows the activation click a Base UI trigger listens for.\n event.preventDefault();\n event.stopPropagation();\n };\n const handleControlMouseDown = (event: MouseEvent) => {\n if (!pressedUnfocusedControl) return;\n // A Base UI trigger opens on the React-delegated mousedown, and all\n // root-delegated handlers die together when the event stops here -\n // including the td's own focus logic, so the selection start runs\n // imperatively: same feature handler, same drag session.\n event.stopPropagation();\n event.preventDefault();\n const cell = (event.target as Element | null)?.closest?.(\"td[data-col-id]\");\n const rowId = cell?.closest(\"tr[data-row-id]\")?.getAttribute(\"data-row-id\");\n const columnId = cell?.getAttribute(\"data-col-id\");\n if (!rowId || !columnId) return;\n const tableNow = getTable();\n const cellApi = tableNow\n .getRowsInDisplayOrder()\n .find((row) => row.id === rowId)\n ?.getAllCellsByColumnId()[columnId];\n if (!cellApi) return;\n if (isRangeSelectionEnabled()) {\n cellApi.getSelectionStartHandler()(event);\n } else {\n tableNow.setFocusedCell(rowId, columnId);\n }\n focusTarget.focus();\n requestAnimationFrame(syncActiveDescendant);\n };\n\n // Drag-to-select outranks in-cell controls: when a drag grew the\n // range, the click that fires on release is swallowed in capture so a\n // trigger under the pointer never opens. The selection key comparison\n // is what distinguishes a drag from a motionless click made while a\n // multi-cell selection already exists (a press on \"+ Add row\" or an\n // in-cell control changes nothing, and its click must go through).\n let dragStartedOnCell = false;\n let dragStartSelectionKey = \"\";\n const getSelectionKey = () => {\n const table = getTable();\n const bounds = table.getCellSelectionBounds();\n const bound = bounds[bounds.length - 1];\n return `${table.getSelectedCellCount()}:${bounds.length}:${\n bound\n ? `${bound.minRowIndex},${bound.minColumnIndex},${bound.maxRowIndex},${bound.maxColumnIndex}`\n : \"\"\n }`;\n };\n const handleDragMouseUp = () => {\n const wasDrag =\n dragStartedOnCell &&\n getTable().getSelectedCellCount() > 1 &&\n getSelectionKey() !== dragStartSelectionKey;\n dragStartedOnCell = false;\n viewport.removeAttribute(\"data-cell-selecting\");\n if (!wasDrag) return;\n const squelch = (clickEvent: MouseEvent) => {\n clickEvent.stopPropagation();\n clickEvent.preventDefault();\n };\n viewport.addEventListener(\"click\", squelch, { capture: true });\n setTimeout(() => viewport.removeEventListener(\"click\", squelch, true), 0);\n };\n\n const handleMouseDown = (event: MouseEvent) => {\n if (event.button !== 0) return;\n // The cell a click focuses reaches assistive tech once React commits.\n requestAnimationFrame(syncActiveDescendant);\n const target = event.target as Element | null;\n // A modifier press is a selection gesture all the way through, the\n // Sheets contract: extending must not hand the keyboard to whatever\n // control sits under the pointer, or the follow-up Shift+arrows land\n // in a date button or a combobox input instead of growing the range.\n // The extension itself runs through the cell's own React handlers, so\n // the event must NOT be defaultPrevented - the delegated handlers\n // treat that as consumed and the extension never happens. Only the\n // browser's focus default is unwanted; it runs after the listeners,\n // so the grid reclaims focus one task later.\n if (\n (event.shiftKey || event.metaKey || event.ctrlKey) &&\n isRangeSelectionEnabled() &&\n target?.closest?.(\"td[data-col-id]\")\n ) {\n setTimeout(() => focusTarget.focus(), 0);\n }\n // Any td press can become a drag; the squelch only arms when the\n // range actually grew by release time. The attribute hides the fill\n // handle for the session, so its overhang never sits in the drag\n // path or churns from cell to cell while the range grows.\n dragStartedOnCell = !!target?.closest?.(\"td\");\n if (dragStartedOnCell) {\n dragStartSelectionKey = getSelectionKey();\n viewport.setAttribute(\"data-cell-selecting\", \"\");\n }\n if (!target?.closest?.('[data-slot=\"data-grid-cell-fill-handle\"]')) return;\n // Ahead of React's root delegation, so the td underneath never starts a\n // plain range drag from the handle.\n event.preventDefault();\n event.stopPropagation();\n startDataGridFillSession<TData>({\n table: getTable(),\n viewport,\n onCellsChange: getOnCellsChange(),\n });\n };\n\n // Single-click editing, the opt-in mode: a plain click that landed\n // on the (now) focused cell opens its editor immediately. Drags were\n // squelched in capture before this bubble listener, and modifier\n // clicks are selection gestures.\n const handleClickToEdit = (event: MouseEvent) => {\n if (context.props.tableLayout?.cellEditMode !== \"click\") return;\n if (event.shiftKey || event.ctrlKey || event.metaKey) return;\n if (isDataGridInteractiveKeyTarget(event.target)) return;\n const cell = (event.target as HTMLElement | null)?.closest?.(\"td\");\n if (!cell?.hasAttribute(\"data-cell-focused\")) return;\n requestCellEdit();\n };\n\n // Double-click opens the editor on the cell the first click focused,\n // matching Sheets. Interactive content keeps its own double-clicks, and\n // the clicked cell must BE the focused one, or a double-click on a\n // non-selectable cell would edit whichever cell held focus before.\n const handleDoubleClick = (event: MouseEvent) => {\n if (isDataGridInteractiveKeyTarget(event.target)) return;\n const target = event.target as HTMLElement | null;\n const cell = target?.closest?.(\"td\");\n if (!cell?.hasAttribute(\"data-cell-focused\")) return;\n requestCellEdit();\n };\n\n const previousTabIndex = focusTarget.getAttribute(\"tabindex\");\n const previousOutline = focusTarget.style.outline;\n if (keyboard) {\n focusTarget.tabIndex = 0;\n // The focused CELL ring is the indicator; the browser's outline around\n // the whole grid on focus() would double it.\n focusTarget.style.outline = \"none\";\n viewport.addEventListener(\"keydown\", handleKeyDown);\n }\n if (clipboard) {\n viewport.addEventListener(\"copy\", handleCopy);\n viewport.addEventListener(\"cut\", handleCut);\n viewport.addEventListener(\"paste\", handlePaste);\n }\n viewport.addEventListener(\"pointerdown\", handleControlPointerDown);\n viewport.addEventListener(\"mousedown\", handleControlMouseDown);\n viewport.addEventListener(\"click\", handleControlClick);\n viewport.addEventListener(\"mousedown\", handleMouseDown);\n viewport.addEventListener(\"click\", handleClickToEdit);\n viewport.addEventListener(\"dblclick\", handleDoubleClick);\n viewport.ownerDocument.addEventListener(\"mouseup\", handleDragMouseUp);\n // Selection-change notifications, read through the context getter so\n // the latest callback fires without re-running this effect. The\n // snapshot is only built when a callback is actually wired.\n const toBound = (bound: {\n minRowIndex: number;\n maxRowIndex: number;\n minColumnIndex: number;\n maxColumnIndex: number;\n }) => ({\n minRowIndex: bound.minRowIndex,\n maxRowIndex: bound.maxRowIndex,\n minColumnIndex: bound.minColumnIndex,\n maxColumnIndex: bound.maxColumnIndex,\n });\n const selectionSubscription = table.atoms.cellSelection?.subscribe(() => {\n const onCellSelectionChange = context.props.onCellSelectionChange;\n if (!onCellSelectionChange) return;\n const tableNow = getTable();\n const focusedCell = tableNow.getFocusedCell();\n const activeBound = getDataGridActiveBound(tableNow);\n onCellSelectionChange({\n focused: focusedCell\n ? { rowId: focusedCell.row.id, columnId: focusedCell.column.id }\n : null,\n bounds: tableNow.getCellSelectionBounds().map(toBound),\n activeBound: activeBound ? toBound(activeBound) : null,\n visibleCellCount: getDataGridVisibleSelectedCellCount(tableNow, viewport),\n });\n });\n setViewportEl(viewport);\n\n return () => {\n if (keyboard) {\n if (previousTabIndex === null) focusTarget.removeAttribute(\"tabindex\");\n else focusTarget.setAttribute(\"tabindex\", previousTabIndex);\n focusTarget.style.outline = previousOutline;\n focusTarget.removeAttribute(\"aria-activedescendant\");\n viewport.removeEventListener(\"keydown\", handleKeyDown);\n }\n if (clipboard) {\n viewport.removeEventListener(\"copy\", handleCopy);\n viewport.removeEventListener(\"cut\", handleCut);\n viewport.removeEventListener(\"paste\", handlePaste);\n }\n viewport.removeEventListener(\"pointerdown\", handleControlPointerDown);\n viewport.removeEventListener(\"mousedown\", handleControlMouseDown);\n viewport.removeEventListener(\"click\", handleControlClick);\n viewport.removeEventListener(\"mousedown\", handleMouseDown);\n viewport.removeEventListener(\"click\", handleClickToEdit);\n viewport.removeEventListener(\"dblclick\", handleDoubleClick);\n viewport.ownerDocument.removeEventListener(\"mouseup\", handleDragMouseUp);\n viewport.removeAttribute(\"data-cell-selecting\");\n selectionSubscription?.unsubscribe();\n clearTimeout(focusRetryTimer);\n if (apiRef) apiRef.current = null;\n setViewportEl(null);\n setEditorSession(null);\n };\n // Context getters serve fresh table/props inside every handler, so the\n // effect re-runs only when the table itself is replaced. apiRef is only\n // read and written here: keeping it out of the deps means an inline ref\n // object cannot tear the listeners down every render.\n }, [\n enabled,\n keyboard,\n clipboard,\n table.atoms.cellSelection?.subscribe,\n context.props.tableLayout?.cellEditMode,\n context.table,\n context.props.onCellsCopy,\n context.props.onCellEditRequest,\n context.props.tableLayout?.cellSelectionMode,\n context.props.onCellsChange,\n context.props.onCellSelectionChange,\n apiRef,\n ]);\n\n // The editor overlay covers the cell but not the fill handle's\n // straddling half, which would poke out beneath it; the viewport flags\n // the session so the handle hides, as it does during a drag.\n useEffect(() => {\n if (!viewportEl || !editorSession) return;\n viewportEl.setAttribute(\"data-cell-editing\", \"\");\n return () => viewportEl.removeAttribute(\"data-cell-editing\");\n }, [viewportEl, editorSession]);\n\n // Closing an editor the user finished with keys hands focus back to the\n // viewport so navigation continues where the edit left off; a commit can\n // advance first (Tab across, and Enter down or up when\n // cellEditEnterAdvance opts into the Sheets flow). A blur-initiated close\n // must NOT refocus: the browser already moved focus where the user\n // clicked, and yanking it back would reroute their next keystrokes into\n // the grid.\n const closeEditorSession = (advance: DataGridEditorAdvance, refocus = true) => {\n setEditorSession(null);\n if (advance) {\n // Same visual-space step as keyboard navigation, so a commit on a\n // pinned row advances like any other row.\n const tableNow = context.table;\n const focused = tableNow.getFocusedCell();\n const target =\n focused && viewportEl\n ? getDataGridStepTarget(\n tableNow,\n viewportEl,\n { rowId: focused.row.id, columnId: focused.column.id },\n advance,\n )\n : null;\n if (target && target !== \"edge\") {\n tableNow.setFocusedCell(target.rowId, target.columnId);\n } else if (!target) {\n tableNow.moveCellSelection(advance);\n }\n }\n if (!refocus) return;\n requestAnimationFrame(() => {\n const focusEl =\n viewportEl?.querySelector<HTMLElement>('table[data-slot=\"data-grid-table\"]') ?? viewportEl;\n focusEl?.focus();\n const cell = viewportEl?.querySelector<HTMLElement>(\"td[data-cell-focused]\");\n if (cell?.id) focusEl?.setAttribute(\"aria-activedescendant\", cell.id);\n cell?.scrollIntoView?.({\n block: \"nearest\",\n inline: \"nearest\",\n behavior: \"instant\",\n });\n });\n };\n\n // An unchanged commit dispatches nothing, the Excel model; a parse\n // rejection reports through the batch's rejected list instead of writing.\n const commitEditorSession = (raw: string, advance: DataGridEditorAdvance, refocus = true) => {\n const session = editorSession;\n closeEditorSession(advance, refocus);\n const onCellsChange = context.props.onCellsChange;\n if (!session || !onCellsChange || raw === session.baseline) return;\n const tableNow = context.table;\n const row = tableNow\n .getRowsInDisplayOrder()\n .find((candidate) => candidate.id === session.rowId);\n const column = tableNow.getColumn(session.columnId);\n const cellEdit =\n column && row ? getDataGridWritableCellEdit<TData>(column, row.original) : null;\n if (!row || !column || !cellEdit) return;\n const previousValue = row.getAllCellsByColumnId()[column.id]?.getValue();\n let value: unknown = raw;\n if (cellEdit.parse) {\n const parsed = cellEdit.parse(raw, row.original);\n if (parsed === undefined) {\n onCellsChange({\n source: \"edit\",\n changes: [],\n rejected: [\n {\n rowId: session.rowId,\n columnId: session.columnId,\n raw,\n reason: \"invalid\",\n },\n ],\n });\n return;\n }\n value = parsed;\n }\n onCellsChange({\n source: \"edit\",\n changes: [\n {\n rowId: session.rowId,\n columnId: session.columnId,\n row: row.original,\n previousValue,\n value,\n },\n ],\n rejected: [],\n });\n };\n\n return (\n <>\n <span ref={anchorRef} hidden data-slot=\"data-grid-cell-selection\" />\n {enabled && viewportEl && editorSession ? (\n <DataGridCellEditorOverlay\n key={`${editorSession.rowId}:${editorSession.columnId}`}\n viewport={viewportEl}\n session={editorSession}\n enterAdvance={context.props.tableLayout?.cellEditEnterAdvance === true}\n onCommit={commitEditorSession}\n onCancel={() => closeEditorSession(null)}\n />\n ) : null}\n </>\n );\n}\n\n/**\n * The built-in free-text editor: a portal into the body viewport, positioned\n * flush over the focused cell with the cell's own font, alignment and\n * padding, so the text keeps its exact place - the Sheets model. The\n * `textarea` control grows downward over the rows below as the text wraps.\n */\nfunction measureDataGridCellEditorStyle(viewport: HTMLElement): CSSProperties | null {\n const cell = viewport.querySelector<HTMLElement>(\"td[data-cell-focused]\");\n if (!cell) return null;\n const cellRect = cell.getBoundingClientRect();\n const viewportRect = viewport.getBoundingClientRect();\n const cellStyle = getComputedStyle(cell);\n // The td centers its one line vertically (align-middle); the editor must\n // put the text in exactly the same place or opening it shifts the value.\n // Symmetric block padding sized to center one line does that for the\n // textarea too, and keeps holding as it grows line by line.\n const lineHeight =\n Number.parseFloat(cellStyle.lineHeight) || Number.parseFloat(cellStyle.fontSize) * 1.5 || 20;\n const centeredBlockPadding = Math.max(\n Number.parseFloat(cellStyle.paddingTop) || 0,\n (cellRect.height - lineHeight) / 2,\n );\n return {\n // Rect deltas are visual; when the viewport itself is the scroll\n // container (the standalone virtual layout), absolute children live in\n // content coordinates, so the scroll offset must be added back. The box\n // matches the cell exactly - editing must not change the cell's\n // geometry - and the cell's own overlay chrome hides for the session\n // (data-cell-editing), so the editor's outline is the ONE border.\n left: cellRect.left - viewportRect.left + viewport.scrollLeft,\n top: cellRect.top - viewportRect.top + viewport.scrollTop,\n width: cellRect.width,\n minHeight: cellRect.height,\n // The font shorthand can serialize empty (Firefox); the longhands after\n // it win where set and cover that case.\n font: cellStyle.font || undefined,\n fontFamily: cellStyle.fontFamily,\n fontSize: cellStyle.fontSize,\n fontWeight: cellStyle.fontWeight,\n fontStyle: cellStyle.fontStyle,\n lineHeight: cellStyle.lineHeight,\n letterSpacing: cellStyle.letterSpacing,\n textAlign: cellStyle.textAlign as CSSProperties[\"textAlign\"],\n paddingLeft: cellStyle.paddingLeft,\n paddingRight: cellStyle.paddingRight,\n paddingTop: centeredBlockPadding,\n paddingBottom: centeredBlockPadding,\n };\n}\n\nfunction DataGridCellEditorOverlay({\n viewport,\n session,\n enterAdvance,\n onCommit,\n onCancel,\n}: {\n viewport: HTMLElement;\n session: DataGridEditorSession;\n enterAdvance: boolean;\n onCommit: (raw: string, advance: DataGridEditorAdvance, refocus?: boolean) => void;\n onCancel: () => void;\n}) {\n // Measured lazily at first render: the focused td was committed before the\n // session opened, and the overlay remounts per cell via its key, so one\n // measurement holds for the editor's lifetime.\n const [style] = useState<CSSProperties | null>(() => measureDataGridCellEditorStyle(viewport));\n const finishedRef = useRef(false);\n\n // The caret belongs at the END of the value (the Excel F2 convention);\n // a textarea would otherwise open with it at position 0. Set on mount,\n // before autoFocus lands, so the stored selection is already right.\n const placeCaretAtEnd = (element: HTMLInputElement | HTMLTextAreaElement | null) => {\n if (!element) return;\n const end = element.value.length;\n element.setSelectionRange?.(end, end);\n };\n\n useEffect(() => {\n if (!style) onCancel();\n }, [style, onCancel]);\n\n // External row changes mid-edit (a live update, a re-sort) move or remove\n // the cell underneath the overlay; the measured position is then a lie and\n // a commit could land visually elsewhere. Cancel instead: predictable, and\n // nothing is written that the user cannot see.\n useEffect(() => {\n const body = viewport.querySelector(\"tbody\");\n if (!body) return;\n const observer = new MutationObserver(() => {\n if (!finishedRef.current) onCancel();\n });\n observer.observe(body, { childList: true, subtree: true });\n return () => observer.disconnect();\n }, [viewport, onCancel]);\n\n if (!style) return null;\n\n const finish = (\n element: HTMLInputElement | HTMLTextAreaElement,\n commit: boolean,\n advance: DataGridEditorAdvance = null,\n refocus = true,\n ) => {\n // One finish per session: an Enter commit can be chased by the blur the\n // unmount produces, and a doubled commit would write twice.\n if (finishedRef.current) return;\n finishedRef.current = true;\n if (commit) onCommit(element.value, advance, refocus);\n else onCancel();\n };\n\n const handleKeyDown = (event: ReactKeyboardEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n const element = event.currentTarget;\n if (event.key === \"Escape\") {\n event.preventDefault();\n event.stopPropagation();\n finish(element, false);\n return;\n }\n if (event.key === \"Tab\") {\n event.preventDefault();\n finish(element, true, event.shiftKey ? \"left\" : \"right\");\n return;\n }\n if (event.key !== \"Enter\") return;\n // A textarea keeps Shift/Alt+Enter as a newline, the Sheets convention.\n if (session.control === \"textarea\" && (event.shiftKey || event.altKey)) {\n return;\n }\n event.preventDefault();\n // The default keeps focus on the edited cell, so a corrected value can\n // be reviewed in place; enterAdvance restores the Sheets move-down.\n finish(element, true, enterAdvance ? (event.shiftKey ? \"up\" : \"down\") : null);\n };\n\n // z-[35]: above the sticky pinned cells (zIndex 30), or editing a pinned\n // cell renders invisibly underneath them; below the sticky header (z-40).\n // Primary outline at the same 1px weight as the focused cell's box: with\n // the overlay covering that box, opening the editor reads as the same\n // border becoming editable.\n const sharedClassName =\n \"text-foreground bg-background outline-primary absolute z-[35] box-border resize-none outline-1 outline-solid -outline-offset-1\";\n\n return createPortal(\n session.control === \"textarea\" ? (\n <textarea\n data-slot=\"data-grid-cell-editor\"\n ref={placeCaretAtEnd}\n autoFocus\n aria-label={session.label}\n defaultValue={session.initialValue}\n rows={1}\n style={style}\n className={cn(sharedClassName, \"field-sizing-content overflow-hidden\")}\n onKeyDown={handleKeyDown}\n onBlur={(event) => finish(event.currentTarget, true, null, false)}\n />\n ) : (\n <input\n data-slot=\"data-grid-cell-editor\"\n ref={placeCaretAtEnd}\n autoFocus\n aria-label={session.label}\n defaultValue={session.initialValue}\n style={style}\n className={sharedClassName}\n onKeyDown={handleKeyDown}\n onBlur={(event) => finish(event.currentTarget, true, null, false)}\n />\n ),\n viewport,\n );\n}\n\n/* ------------------------------------------------------------------------- *\n * Bulk edit bar.\n * ------------------------------------------------------------------------- */\n\n/**\n * Thin shell over row selection for bulk actions: selected count, a slot for\n * the consumer's controls, and a clear action. Hidden while nothing is\n * selected. What the controls do stays consumer-owned.\n *\n * Presented as a floating toolbar, the Google Sheets way: auto width,\n * centered, elevated, and sticky to the viewport bottom with breathing room,\n * so bulk actions stay reachable while the grid scrolls.\n */\nfunction DataGridSelectionBar({\n children,\n className,\n label,\n clearLabel = \"Clear\",\n onClear,\n}: {\n children?: ReactNode;\n className?: string;\n label?: (count: number) => ReactNode;\n clearLabel?: ReactNode;\n onClear?: () => void;\n}) {\n const context = useDataGrid();\n const rowSelectionAtom = context.table.atoms.rowSelection;\n if (rowSelectionAtom == null) return null;\n\n return (\n <Subscribe source={rowSelectionAtom}>\n {() => {\n // Read through the context getter: this closure re-runs on atom\n // writes without re-rendering the component, and a captured v9\n // wrapper would keep reporting the state it was built with.\n const table = context.table;\n const count = table.getSelectedRowModel().rows.length;\n if (count === 0) return null;\n return (\n <div\n data-slot=\"data-grid-selection-bar\"\n className={cn(\n \"sticky inset-x-0 bottom-4 z-40 mx-auto flex w-fit max-w-[calc(100%-2rem)] flex-wrap items-center gap-3 rounded-lg border bg-background px-4 py-2.5 shadow-lg\",\n className,\n )}\n >\n <span className=\"font-medium text-foreground text-sm\">\n {label ? label(count) : `${count} selected`}\n </span>\n <div className=\"flex flex-1 flex-wrap items-center justify-end gap-2.5\">\n {children}\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => {\n context.table.resetRowSelection();\n onClear?.();\n }}\n >\n {clearLabel}\n </Button>\n </div>\n </div>\n );\n }}\n </Subscribe>\n );\n}\n\nexport type { DataGridCellSelectionApi, DataGridFocusCellOptions, DataGridPasteTarget };\nexport {\n buildDataGridClearDetails,\n buildDataGridPasteDetails,\n DataGridCellSelection,\n DataGridSelectionBar,\n getDataGridActiveRegionGrid,\n getDataGridVisibleSelectedCellCount,\n invertDataGridCellsChange,\n parseDataGridClipboardText,\n serializeDataGridClipboardText,\n tileDataGridClipboardBlock,\n};\n"],"mappings":";;;;;;;;;;AAmEA,SAAS,gCAAgC,OAAuB;CAG9D,OAAO,YAAY,KAAK,KAAK,IAAI,IAAI,MAAM,WAAW,MAAK,MAAI,EAAE,KAAK;AACxE;;AAGA,SAAS,+BAA+B,MAA0B;CAChE,OAAO,KAAK,KAAK,SAAS,KAAK,IAAI,+BAA+B,CAAC,CAAC,KAAK,GAAI,CAAC,CAAC,CAAC,KAAK,MAAM;AAC7F;;;;;;AAOA,SAAS,2BAA2B,MAA0B;CAC5D,MAAM,OAAmB,CAAC;CAC1B,IAAI,MAAgB,CAAC;CACrB,IAAI,QAAQ;CACZ,IAAI,SAAS;CACb,IAAI,IAAI;CAER,OAAO,IAAI,KAAK,QAAQ;EACtB,MAAM,KAAK,KAAK;EAChB,IAAI,QAAQ;GACV,IAAI,OAAO,MAAK;IACd,IAAI,KAAK,IAAI,OAAO,MAAK;KACvB,SAAS;KACT,KAAK;KACL;IACF;IACA,SAAS;IACT,KAAK;IACL;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