@kumix/ui 0.3.9 → 0.3.11

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 (169) hide show
  1. package/README.md +15 -14
  2. package/dist/components/motion/adaptive-stepper.d.ts +32 -0
  3. package/dist/components/motion/adaptive-stepper.d.ts.map +1 -0
  4. package/dist/components/motion/adaptive-stepper.js +302 -0
  5. package/dist/components/motion/adaptive-stepper.js.map +1 -0
  6. package/dist/components/motion/animated-sidebar.d.ts.map +1 -1
  7. package/dist/components/motion/animated-sidebar.js.map +1 -1
  8. package/dist/components/motion/availability-scheduler/copy-menu.js +1 -1
  9. package/dist/components/motion/availability-scheduler/day-row.d.ts.map +1 -1
  10. package/dist/components/motion/availability-scheduler/day-row.js +15 -7
  11. package/dist/components/motion/availability-scheduler/day-row.js.map +1 -1
  12. package/dist/components/motion/availability-scheduler/index.js +1 -1
  13. package/dist/components/motion/button/index.d.ts +2 -1
  14. package/dist/components/motion/button/index.js +2 -1
  15. package/dist/components/motion/button/metallic.d.ts +10 -0
  16. package/dist/components/motion/button/metallic.d.ts.map +1 -0
  17. package/dist/components/motion/button/metallic.js +71 -0
  18. package/dist/components/motion/button/metallic.js.map +1 -0
  19. package/dist/components/motion/combobox/content.js +1 -1
  20. package/dist/components/motion/combobox/context.js +216 -1
  21. package/dist/components/motion/combobox/context.js.map +1 -0
  22. package/dist/components/motion/combobox/list.js +1 -1
  23. package/dist/components/motion/combobox/trigger.js +1 -1
  24. package/dist/components/motion/combobox.js +1 -1
  25. package/dist/components/motion/expandable-control.d.ts +28 -0
  26. package/dist/components/motion/expandable-control.d.ts.map +1 -0
  27. package/dist/components/motion/expandable-control.js +149 -0
  28. package/dist/components/motion/expandable-control.js.map +1 -0
  29. package/dist/components/motion/expanding-arrow-button.d.ts +12 -0
  30. package/dist/components/motion/expanding-arrow-button.d.ts.map +1 -0
  31. package/dist/components/motion/expanding-arrow-button.js +142 -0
  32. package/dist/components/motion/expanding-arrow-button.js.map +1 -0
  33. package/dist/components/motion/file-tree.d.ts +42 -0
  34. package/dist/components/motion/file-tree.d.ts.map +1 -0
  35. package/dist/components/motion/file-tree.js +272 -0
  36. package/dist/components/motion/file-tree.js.map +1 -0
  37. package/dist/components/motion/input.d.ts +2 -0
  38. package/dist/components/motion/input.d.ts.map +1 -1
  39. package/dist/components/motion/input.js +28 -25
  40. package/dist/components/motion/input.js.map +1 -1
  41. package/dist/components/motion/liquid.d.ts +30 -0
  42. package/dist/components/motion/liquid.d.ts.map +1 -0
  43. package/dist/components/motion/liquid.js +248 -0
  44. package/dist/components/motion/liquid.js.map +1 -0
  45. package/dist/components/motion/multi-select/content.d.ts +16 -0
  46. package/dist/components/motion/multi-select/content.d.ts.map +1 -0
  47. package/dist/components/motion/multi-select/content.js +91 -0
  48. package/dist/components/motion/multi-select/content.js.map +1 -0
  49. package/dist/components/motion/multi-select/context.d.ts +64 -0
  50. package/dist/components/motion/multi-select/context.d.ts.map +1 -0
  51. package/dist/{context-BizvUNZv.js → components/motion/multi-select/context.js} +44 -114
  52. package/dist/components/motion/multi-select/context.js.map +1 -0
  53. package/dist/components/motion/multi-select/index.d.ts +5 -0
  54. package/dist/components/motion/multi-select/index.js +6 -0
  55. package/dist/components/motion/multi-select/list.d.ts +40 -0
  56. package/dist/components/motion/multi-select/list.d.ts.map +1 -0
  57. package/dist/components/motion/multi-select/list.js +144 -0
  58. package/dist/components/motion/multi-select/list.js.map +1 -0
  59. package/dist/components/motion/multi-select/trigger.d.ts +22 -0
  60. package/dist/components/motion/multi-select/trigger.d.ts.map +1 -0
  61. package/dist/components/motion/multi-select/trigger.js +185 -0
  62. package/dist/components/motion/multi-select/trigger.js.map +1 -0
  63. package/dist/components/motion/signup-form.js +6 -2
  64. package/dist/components/motion/signup-form.js.map +1 -1
  65. package/dist/components/motion/table/index.js.map +1 -1
  66. package/dist/components/reui/alert.d.ts +1 -1
  67. package/dist/components/reui/badge.d.ts +1 -1
  68. package/dist/components/reui/cascader/cascader-async.d.ts.map +1 -1
  69. package/dist/components/reui/cascader/cascader-async.js.map +1 -1
  70. package/dist/components/reui/cascader/cascader-virtual.d.ts.map +1 -1
  71. package/dist/components/reui/cascader/cascader-virtual.js.map +1 -1
  72. package/dist/components/reui/cascader/cascader.d.ts.map +1 -1
  73. package/dist/components/reui/cascader/cascader.js.map +1 -1
  74. package/dist/components/reui/code-block/code-block-highlight.d.ts +216 -0
  75. package/dist/components/reui/code-block/code-block-highlight.d.ts.map +1 -0
  76. package/dist/components/reui/code-block/code-block-highlight.js +792 -0
  77. package/dist/components/reui/code-block/code-block-highlight.js.map +1 -0
  78. package/dist/components/reui/code-block/code-block.d.ts +197 -0
  79. package/dist/components/reui/code-block/code-block.d.ts.map +1 -0
  80. package/dist/components/reui/code-block/code-block.js +1150 -0
  81. package/dist/components/reui/code-block/code-block.js.map +1 -0
  82. package/dist/components/reui/data-grid/data-grid-cell-selection.d.ts +117 -0
  83. package/dist/components/reui/data-grid/data-grid-cell-selection.d.ts.map +1 -0
  84. package/dist/components/reui/data-grid/data-grid-cell-selection.js +1554 -0
  85. package/dist/components/reui/data-grid/data-grid-cell-selection.js.map +1 -0
  86. package/dist/components/reui/data-grid/data-grid-column-filter.d.ts.map +1 -1
  87. package/dist/components/reui/data-grid/data-grid-column-filter.js +6 -4
  88. package/dist/components/reui/data-grid/data-grid-column-filter.js.map +1 -1
  89. package/dist/components/reui/data-grid/data-grid-column-header.d.ts.map +1 -1
  90. package/dist/components/reui/data-grid/data-grid-column-header.js +10 -7
  91. package/dist/components/reui/data-grid/data-grid-column-header.js.map +1 -1
  92. package/dist/components/reui/data-grid/data-grid-column-visibility.js +3 -2
  93. package/dist/components/reui/data-grid/data-grid-column-visibility.js.map +1 -1
  94. package/dist/components/reui/data-grid/data-grid-i18n.d.ts +2 -0
  95. package/dist/components/reui/data-grid/data-grid-i18n.js +53 -0
  96. package/dist/components/reui/data-grid/data-grid-i18n.js.map +1 -0
  97. package/dist/components/reui/data-grid/data-grid-pagination.js +14 -8
  98. package/dist/components/reui/data-grid/data-grid-pagination.js.map +1 -1
  99. package/dist/components/reui/data-grid/data-grid-scroll-area.d.ts.map +1 -1
  100. package/dist/components/reui/data-grid/data-grid-scroll-area.js +3 -3
  101. package/dist/components/reui/data-grid/data-grid-scroll-area.js.map +1 -1
  102. package/dist/components/reui/data-grid/data-grid-table-dnd-rows.d.ts.map +1 -1
  103. package/dist/components/reui/data-grid/data-grid-table-dnd-rows.js +6 -4
  104. package/dist/components/reui/data-grid/data-grid-table-dnd-rows.js.map +1 -1
  105. package/dist/components/reui/data-grid/data-grid-table-dnd.js +2 -2
  106. package/dist/components/reui/data-grid/data-grid-table-dnd.js.map +1 -1
  107. package/dist/components/reui/data-grid/data-grid-table-virtual.d.ts +17 -1
  108. package/dist/components/reui/data-grid/data-grid-table-virtual.d.ts.map +1 -1
  109. package/dist/components/reui/data-grid/data-grid-table-virtual.js +146 -50
  110. package/dist/components/reui/data-grid/data-grid-table-virtual.js.map +1 -1
  111. package/dist/components/reui/data-grid/data-grid-table.d.ts +23 -4
  112. package/dist/components/reui/data-grid/data-grid-table.d.ts.map +1 -1
  113. package/dist/components/reui/data-grid/data-grid-table.js +215 -68
  114. package/dist/components/reui/data-grid/data-grid-table.js.map +1 -1
  115. package/dist/components/reui/data-grid/data-grid.d.ts +276 -6
  116. package/dist/components/reui/data-grid/data-grid.d.ts.map +1 -1
  117. package/dist/components/reui/data-grid/data-grid.js +150 -15
  118. package/dist/components/reui/data-grid/data-grid.js.map +1 -1
  119. package/dist/components/reui/filters/filters-advanced.js.map +1 -1
  120. package/dist/components/reui/filters/filters-chip.js.map +1 -1
  121. package/dist/components/reui/filters/filters.d.ts.map +1 -1
  122. package/dist/components/reui/filters/filters.js.map +1 -1
  123. package/dist/components/reui/frame.d.ts +1 -1
  124. package/dist/components/reui/gantt/gantt-bar.js +42 -12
  125. package/dist/components/reui/gantt/gantt-bar.js.map +1 -1
  126. package/dist/components/reui/gantt/gantt-dnd.d.ts.map +1 -1
  127. package/dist/components/reui/gantt/gantt-dnd.js +22 -7
  128. package/dist/components/reui/gantt/gantt-dnd.js.map +1 -1
  129. package/dist/components/reui/gantt/gantt-i18n.d.ts +8 -0
  130. package/dist/components/reui/gantt/gantt-i18n.d.ts.map +1 -1
  131. package/dist/components/reui/gantt/gantt-i18n.js +6 -1
  132. package/dist/components/reui/gantt/gantt-i18n.js.map +1 -1
  133. package/dist/components/reui/gantt/gantt-lib.d.ts +59 -2
  134. package/dist/components/reui/gantt/gantt-lib.d.ts.map +1 -1
  135. package/dist/components/reui/gantt/gantt-lib.js +67 -2
  136. package/dist/components/reui/gantt/gantt-lib.js.map +1 -1
  137. package/dist/components/reui/gantt/gantt-recurrence.js +3 -3
  138. package/dist/components/reui/gantt/gantt-recurrence.js.map +1 -1
  139. package/dist/components/reui/gantt/gantt-types.d.ts +32 -1
  140. package/dist/components/reui/gantt/gantt-types.d.ts.map +1 -1
  141. package/dist/components/reui/gantt/gantt-view.d.ts.map +1 -1
  142. package/dist/components/reui/gantt/gantt-view.js +324 -35
  143. package/dist/components/reui/gantt/gantt-view.js.map +1 -1
  144. package/dist/components/reui/gantt/gantt.d.ts +71 -2
  145. package/dist/components/reui/gantt/gantt.d.ts.map +1 -1
  146. package/dist/components/reui/gantt/gantt.js +8 -0
  147. package/dist/components/reui/gantt/gantt.js.map +1 -1
  148. package/dist/components/reui/icon-tile.d.ts +1 -1
  149. package/dist/components/ui/attachment.d.ts +1 -1
  150. package/dist/components/ui/badge.d.ts +1 -1
  151. package/dist/components/ui/bubble.d.ts +1 -1
  152. package/dist/components/ui/button-group.d.ts +1 -1
  153. package/dist/components/ui/button.d.ts +1 -1
  154. package/dist/components/ui/field.d.ts +1 -1
  155. package/dist/components/ui/item.d.ts +1 -1
  156. package/dist/components/ui/message-scroller.js +1 -1
  157. package/dist/components/ui/message-scroller.js.map +1 -1
  158. package/dist/components/ui/sidebar.d.ts +1 -1
  159. package/dist/components/ui/toggle.d.ts +1 -1
  160. package/dist/{copy-menu-1FKoMc9o.js → copy-menu-C5GaT4Z-.js} +67 -2
  161. package/dist/copy-menu-C5GaT4Z-.js.map +1 -0
  162. package/dist/data-grid-i18n-52UUYPbr.d.ts +66 -0
  163. package/dist/data-grid-i18n-52UUYPbr.d.ts.map +1 -0
  164. package/dist/types-smkWN_7x.d.ts.map +1 -1
  165. package/dist/use-active-option-CmX6Z-4S.js +86 -0
  166. package/dist/use-active-option-CmX6Z-4S.js.map +1 -0
  167. package/package.json +7 -13
  168. package/dist/context-BizvUNZv.js.map +0 -1
  169. package/dist/copy-menu-1FKoMc9o.js.map +0 -1
@@ -0,0 +1,1554 @@
1
+ "use client";
2
+ import { Button } from "../../ui/button.js";
3
+ import { useDataGrid } from "./data-grid.js";
4
+ import { useEffect, useRef, useState } from "react";
5
+ import { cn } from "@kumix/utils";
6
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
7
+ import { createPortal } from "react-dom";
8
+ import { Subscribe } from "@tanstack/react-table";
9
+ //#region src/components/reui/data-grid/data-grid-cell-selection.tsx
10
+ function serializeDataGridClipboardField(field) {
11
+ return /[\t\n\r"]/.test(field) ? `"${field.replaceAll("\"", "\"\"")}"` : field;
12
+ }
13
+ /** Row-major grid to TSV, CRLF rows, Excel-style quoting. */
14
+ function serializeDataGridClipboardText(grid) {
15
+ return grid.map((line) => line.map(serializeDataGridClipboardField).join(" ")).join("\r\n");
16
+ }
17
+ /**
18
+ * TSV to a row-major grid. A stateful scan, not a split: a quoted field may
19
+ * contain tabs, quotes and both newline flavors, which is exactly what Excel
20
+ * emits for a multi-line cell.
21
+ */
22
+ function parseDataGridClipboardText(text) {
23
+ const rows = [];
24
+ let row = [];
25
+ let field = "";
26
+ let quoted = false;
27
+ let i = 0;
28
+ while (i < text.length) {
29
+ const ch = text[i];
30
+ if (quoted) {
31
+ if (ch === "\"") {
32
+ if (text[i + 1] === "\"") {
33
+ field += "\"";
34
+ i += 2;
35
+ continue;
36
+ }
37
+ quoted = false;
38
+ i += 1;
39
+ continue;
40
+ }
41
+ field += ch;
42
+ i += 1;
43
+ continue;
44
+ }
45
+ if (ch === "\"" && field === "") {
46
+ quoted = true;
47
+ i += 1;
48
+ continue;
49
+ }
50
+ if (ch === " ") {
51
+ row.push(field);
52
+ field = "";
53
+ i += 1;
54
+ continue;
55
+ }
56
+ if (ch === "\r" || ch === "\n") {
57
+ if (ch === "\r" && text[i + 1] === "\n") i += 1;
58
+ row.push(field);
59
+ rows.push(row);
60
+ row = [];
61
+ field = "";
62
+ i += 1;
63
+ continue;
64
+ }
65
+ field += ch;
66
+ i += 1;
67
+ }
68
+ row.push(field);
69
+ rows.push(row);
70
+ const last = rows[rows.length - 1];
71
+ if (rows.length > 1 && last?.length === 1 && last[0] === "") rows.pop();
72
+ return rows;
73
+ }
74
+ /** Repeats a block cyclically to fill rowCount x columnCount. */
75
+ function tileDataGridClipboardBlock(block, rowCount, columnCount) {
76
+ const tiled = [];
77
+ for (let r = 0; r < rowCount; r++) {
78
+ const source = block[r % block.length] ?? [];
79
+ const line = [];
80
+ for (let c = 0; c < columnCount; c++) line.push(source[c % (source.length || 1)] ?? "");
81
+ tiled.push(line);
82
+ }
83
+ return tiled;
84
+ }
85
+ function escapeDataGridClipboardHtml(value) {
86
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
87
+ }
88
+ function renderDataGridClipboardHtml(grid) {
89
+ return `<table><tbody>${grid.map((line) => "<tr>" + line.map((field) => `<td>${escapeDataGridClipboardHtml(field).replace(/\r\n|\r|\n/g, "<br>")}</td>`).join("") + "</tr>").join("")}</tbody></table>`;
90
+ }
91
+ /**
92
+ * Columns in render order, the same [start, center, end] space
93
+ * cellSelectionFeature resolves its bounds against.
94
+ */
95
+ function getDataGridDisplayOrderedColumns(table) {
96
+ return [
97
+ ...table.getStartVisibleLeafColumns(),
98
+ ...table.getCenterVisibleLeafColumns(),
99
+ ...table.getEndVisibleLeafColumns()
100
+ ];
101
+ }
102
+ function getDataGridWritableCellEdit(column, row) {
103
+ const cellEdit = column.columnDef.meta?.cellEdit;
104
+ if (!cellEdit || cellEdit.editable === false) return null;
105
+ if (typeof cellEdit.editable === "function" && row !== void 0 && !cellEdit.editable(row)) return null;
106
+ return cellEdit;
107
+ }
108
+ /**
109
+ * Ids of the rows the view can actually show: the page slice plus rows the
110
+ * DOM renders outside it (pinned rows under keepPinnedRows). Selection
111
+ * bounds live in pre-paginated display order, so a range whose corners are
112
+ * both visible can still span off-page rows in between - a page-boundary
113
+ * range to a bottom-pinned draft is the standing example. Every batch walk
114
+ * (copy, clear, paste, fill) filters rows through this set so the cells a
115
+ * batch touches are exactly the cells the selection paints.
116
+ */
117
+ function getDataGridRenderedRowIds(table, viewport) {
118
+ if (!viewport) return null;
119
+ if (table.getRowModel().rows.length === table.getRowsInDisplayOrder().length) return null;
120
+ const rendered = new Set(table.getRowModel().rows.map((row) => row.id));
121
+ for (const rowEl of Array.from(viewport.querySelectorAll("tbody tr[data-row-id]"))) {
122
+ const id = rowEl.getAttribute("data-row-id");
123
+ if (id) rendered.add(id);
124
+ }
125
+ return rendered;
126
+ }
127
+ /**
128
+ * Cells of the current selection the view can actually show, under the
129
+ * same row filter the batch builders use, so a count shown next to the
130
+ * selection always matches what is painted and what a batch will touch.
131
+ * The feature's own getSelectedCellCount spans off-page rows instead.
132
+ */
133
+ function getDataGridVisibleSelectedCellCount(table, viewport) {
134
+ const bounds = table.getCellSelectionBounds();
135
+ if (!bounds.length) return 0;
136
+ const rows = table.getRowsInDisplayOrder();
137
+ const columns = getDataGridDisplayOrderedColumns(table);
138
+ const rendered = getDataGridRenderedRowIds(table, viewport);
139
+ let count = 0;
140
+ for (const bound of bounds) {
141
+ let rowCount = 0;
142
+ for (let r = bound.minRowIndex; r <= bound.maxRowIndex; r++) {
143
+ const row = rows[r];
144
+ if (row && (!rendered || rendered.has(row.id))) rowCount += 1;
145
+ }
146
+ let columnCount = 0;
147
+ for (let c = bound.minColumnIndex; c <= bound.maxColumnIndex; c++) {
148
+ const column = columns[c];
149
+ if (column && column.columnDef.enableCellSelection !== false) columnCount += 1;
150
+ }
151
+ count += rowCount * columnCount;
152
+ }
153
+ return count;
154
+ }
155
+ /**
156
+ * The bound of the ACTIVE (most recent) region. getCellSelectionBounds()
157
+ * sorts geometrically, so its last entry is merely the bottom-right
158
+ * rectangle; the focused cell anchors the newest range, so the bound
159
+ * containing it is the active one. Falls back to the geometric last when
160
+ * the focused cell sits in no bound (the newest range was an exclude).
161
+ */
162
+ function getDataGridActiveBound(table) {
163
+ const bounds = table.getCellSelectionBounds();
164
+ if (!bounds.length) return null;
165
+ const focused = table.getFocusedCell();
166
+ if (focused) {
167
+ const rowIndex = focused.row.getDisplayIndex();
168
+ const columnIndex = getDataGridDisplayOrderedColumns(table).findIndex((column) => column.id === focused.column.id);
169
+ const containing = bounds.find((bound) => rowIndex >= bound.minRowIndex && rowIndex <= bound.maxRowIndex && columnIndex >= bound.minColumnIndex && columnIndex <= bound.maxColumnIndex);
170
+ if (containing) return containing;
171
+ }
172
+ return bounds[bounds.length - 1] ?? null;
173
+ }
174
+ /**
175
+ * Resolves the cell one visual step away from a given cell: selectable
176
+ * columns for horizontal, RENDERED row order for vertical. The feature's
177
+ * own move/extend resolve rows through the page slice and stall on pinned
178
+ * rows (a bottom-pinned draft), while id-addressed cells work everywhere.
179
+ * "edge" means the step is at the grid boundary; null means the position
180
+ * is not resolvable here and the caller should use the feature's move.
181
+ */
182
+ function getDataGridStepTarget(table, viewport, from, direction) {
183
+ if (direction === "left" || direction === "right") {
184
+ const selectable = getDataGridDisplayOrderedColumns(table).filter((column) => column.columnDef.enableCellSelection !== false);
185
+ const index = selectable.findIndex((column) => column.id === from.columnId);
186
+ if (index === -1) return null;
187
+ const next = selectable[index + (direction === "right" ? 1 : -1)];
188
+ return next ? {
189
+ rowId: from.rowId,
190
+ columnId: next.id
191
+ } : "edge";
192
+ }
193
+ const renderedIds = Array.from(viewport.querySelectorAll("tbody tr[data-row-id]")).map((row) => row.getAttribute("data-row-id"));
194
+ const index = renderedIds.indexOf(from.rowId);
195
+ if (index === -1) return null;
196
+ const nextId = renderedIds[index + (direction === "down" ? 1 : -1)];
197
+ return nextId ? {
198
+ rowId: nextId,
199
+ columnId: from.columnId
200
+ } : "edge";
201
+ }
202
+ /**
203
+ * Shift+Arrow: the feature keeps focus on the anchor and grows the range
204
+ * from its active corner. When its own extend cannot resolve the step
205
+ * (the active corner sits on a pinned row, or the next visual row is a
206
+ * pinned row outside the page slice), re-derive the active corner from
207
+ * the bounds and step it in visual space through selectCellRange.
208
+ */
209
+ function extendDataGridSelection(table, viewport, direction) {
210
+ const activeCorner = () => {
211
+ const focused = table.getFocusedCell();
212
+ if (!focused) return null;
213
+ const bound = getDataGridActiveBound(table);
214
+ if (!bound) return null;
215
+ const rows = table.getRowsInDisplayOrder();
216
+ const allColumns = getDataGridDisplayOrderedColumns(table);
217
+ const rowIndex = focused.row.getDisplayIndex();
218
+ const columnIndex = allColumns.findIndex((column) => column.id === focused.column.id);
219
+ return {
220
+ rowId: rows[rowIndex === bound.minRowIndex ? bound.maxRowIndex : bound.minRowIndex]?.id ?? focused.row.id,
221
+ columnId: allColumns[columnIndex === bound.minColumnIndex ? bound.maxColumnIndex : bound.minColumnIndex]?.id ?? focused.column.id
222
+ };
223
+ };
224
+ const boundKey = () => {
225
+ const bounds = table.getCellSelectionBounds();
226
+ const bound = bounds[bounds.length - 1];
227
+ return bound ? `${bounds.length}:${bound.minRowIndex}-${bound.maxRowIndex}:${bound.minColumnIndex}-${bound.maxColumnIndex}` : "none";
228
+ };
229
+ const before = boundKey();
230
+ table.extendCellSelection(direction);
231
+ if (boundKey() !== before) return activeCorner();
232
+ const focused = table.getFocusedCell();
233
+ if (!focused) return null;
234
+ const target = getDataGridStepTarget(table, viewport, activeCorner() ?? {
235
+ rowId: focused.row.id,
236
+ columnId: focused.column.id
237
+ }, direction);
238
+ if (!target || target === "edge") return null;
239
+ table.selectCellRange({
240
+ anchorRowId: focused.row.id,
241
+ anchorColumnId: focused.column.id,
242
+ focusRowId: target.rowId,
243
+ focusColumnId: target.columnId
244
+ }, { mode: "replace" });
245
+ return target;
246
+ }
247
+ /**
248
+ * The active region as formatted strings, row-major. Columns opted out of
249
+ * selection are compacted away, matching the feature's own ranges-data
250
+ * behavior, and rows the view cannot show are skipped when a viewport is
251
+ * given. Null when nothing is selected.
252
+ */
253
+ function getDataGridActiveRegionGrid(table, viewport) {
254
+ const bound = getDataGridActiveBound(table);
255
+ if (!bound) return null;
256
+ const rows = table.getRowsInDisplayOrder();
257
+ const columns = getDataGridDisplayOrderedColumns(table);
258
+ const rendered = getDataGridRenderedRowIds(table, viewport);
259
+ const grid = [];
260
+ for (let r = bound.minRowIndex; r <= bound.maxRowIndex; r++) {
261
+ const row = rows[r];
262
+ if (!row || rendered && !rendered.has(row.id)) continue;
263
+ const cells = row.getAllCellsByColumnId();
264
+ const line = [];
265
+ for (let c = bound.minColumnIndex; c <= bound.maxColumnIndex; c++) {
266
+ const column = columns[c];
267
+ if (!column || column.columnDef.enableCellSelection === false) continue;
268
+ const value = cells[column.id]?.getValue();
269
+ const format = column.columnDef.meta?.cellEdit?.format;
270
+ line.push(format ? format(value, row.original) : String(value ?? ""));
271
+ }
272
+ grid.push(line);
273
+ }
274
+ return grid.length ? grid : null;
275
+ }
276
+ /**
277
+ * A clear/cut batch over the selection's writable cells. Non-writable columns
278
+ * are skipped silently: clearing is an intent over what the grid owns, and a
279
+ * rejection per read-only cell would be noise. Null when nothing clears.
280
+ */
281
+ function buildDataGridClearDetails(table, source, activeRegionOnly, viewport) {
282
+ const allBounds = table.getCellSelectionBounds();
283
+ const activeBound = getDataGridActiveBound(table);
284
+ const bounds = activeRegionOnly ? activeBound ? [activeBound] : [] : allBounds;
285
+ if (!bounds.length) return null;
286
+ const rows = table.getRowsInDisplayOrder();
287
+ const columns = getDataGridDisplayOrderedColumns(table);
288
+ const rendered = getDataGridRenderedRowIds(table, viewport);
289
+ const changes = [];
290
+ for (const bound of bounds) for (let r = bound.minRowIndex; r <= bound.maxRowIndex; r++) {
291
+ const row = rows[r];
292
+ if (!row || rendered && !rendered.has(row.id)) continue;
293
+ const cells = row.getAllCellsByColumnId();
294
+ for (let c = bound.minColumnIndex; c <= bound.maxColumnIndex; c++) {
295
+ const column = columns[c];
296
+ if (!column || column.columnDef.enableCellSelection === false) continue;
297
+ const cellEdit = getDataGridWritableCellEdit(column, row.original);
298
+ if (!cellEdit) continue;
299
+ changes.push({
300
+ rowId: row.id,
301
+ columnId: column.id,
302
+ row: row.original,
303
+ previousValue: cells[column.id]?.getValue(),
304
+ value: cellEdit.clearValue ?? null
305
+ });
306
+ }
307
+ }
308
+ return changes.length ? {
309
+ source,
310
+ changes,
311
+ rejected: []
312
+ } : null;
313
+ }
314
+ /**
315
+ * Resolves a parsed clipboard block into a paste batch, Excel semantics:
316
+ * a 1x1 block fills the whole selected region; a block tiles when the region
317
+ * is an exact multiple of it; otherwise it pastes once from the region's
318
+ * top-left, clamped at the grid edges (rows are never grown).
319
+ */
320
+ function buildDataGridPasteDetails(table, block, viewport) {
321
+ if (!block.length) return null;
322
+ const bound = getDataGridActiveBound(table);
323
+ if (!bound) return null;
324
+ const rows = table.getRowsInDisplayOrder();
325
+ const columns = getDataGridDisplayOrderedColumns(table);
326
+ const rendered = getDataGridRenderedRowIds(table, viewport);
327
+ const targetColumns = [];
328
+ let regionColumns = 0;
329
+ for (let c = bound.minColumnIndex; c < columns.length; c++) {
330
+ const column = columns[c];
331
+ if (!column || column.columnDef.enableCellSelection === false) continue;
332
+ targetColumns.push({
333
+ column,
334
+ displayIndex: c
335
+ });
336
+ if (c <= bound.maxColumnIndex) regionColumns += 1;
337
+ }
338
+ if (!regionColumns) return null;
339
+ const blockRows = block.length;
340
+ const blockColumns = block.reduce((max, line) => Math.max(max, line.length), 1);
341
+ const regionRows = bound.maxRowIndex - bound.minRowIndex + 1;
342
+ let rowCount;
343
+ let columnCount;
344
+ if (blockRows === 1 && blockColumns === 1) {
345
+ rowCount = regionRows;
346
+ columnCount = regionColumns;
347
+ } else if (regionRows % blockRows === 0 && regionColumns % blockColumns === 0) {
348
+ rowCount = regionRows;
349
+ columnCount = regionColumns;
350
+ } else {
351
+ rowCount = blockRows;
352
+ columnCount = blockColumns;
353
+ }
354
+ const tiled = tileDataGridClipboardBlock(block, rowCount, columnCount);
355
+ const startRowIndex = bound.minRowIndex;
356
+ const targetRows = [];
357
+ for (let r = startRowIndex; r < rows.length; r++) {
358
+ if (targetRows.length === rowCount) break;
359
+ const row = rows[r];
360
+ if (!row || rendered && !rendered.has(row.id)) continue;
361
+ targetRows.push({
362
+ row,
363
+ displayIndex: r
364
+ });
365
+ }
366
+ const changes = [];
367
+ const rejected = [];
368
+ for (let r = 0; r < targetRows.length; r++) {
369
+ const row = targetRows[r].row;
370
+ const cells = row.getAllCellsByColumnId();
371
+ for (let c = 0; c < columnCount; c++) {
372
+ const column = targetColumns[c]?.column;
373
+ if (!column) continue;
374
+ const raw = tiled[r]?.[c] ?? "";
375
+ const cellEdit = getDataGridWritableCellEdit(column, row.original);
376
+ if (!cellEdit) {
377
+ rejected.push({
378
+ rowId: row.id,
379
+ columnId: column.id,
380
+ raw,
381
+ reason: "readonly"
382
+ });
383
+ continue;
384
+ }
385
+ const value = cellEdit.parse ? cellEdit.parse(raw, row.original) : raw;
386
+ if (value === void 0) {
387
+ rejected.push({
388
+ rowId: row.id,
389
+ columnId: column.id,
390
+ raw,
391
+ reason: "invalid"
392
+ });
393
+ continue;
394
+ }
395
+ changes.push({
396
+ rowId: row.id,
397
+ columnId: column.id,
398
+ row: row.original,
399
+ previousValue: cells[column.id]?.getValue(),
400
+ value
401
+ });
402
+ }
403
+ }
404
+ if (!changes.length && !rejected.length) return null;
405
+ const lastTarget = targetColumns[Math.min(columnCount, targetColumns.length) - 1];
406
+ return {
407
+ details: {
408
+ source: "paste",
409
+ changes,
410
+ rejected
411
+ },
412
+ target: {
413
+ startRowIndex,
414
+ endRowIndex: targetRows[targetRows.length - 1]?.displayIndex ?? startRowIndex,
415
+ rowCount: targetRows.length,
416
+ startColumnIndex: targetColumns[0].displayIndex,
417
+ endColumnIndex: lastTarget.displayIndex
418
+ }
419
+ };
420
+ }
421
+ /**
422
+ * The inverse batch: every change's value and previousValue swapped and
423
+ * rejections dropped. Feed it through the same state update onCellsChange
424
+ * uses to implement undo; inverting the inverse is redo.
425
+ */
426
+ function invertDataGridCellsChange(details) {
427
+ return {
428
+ source: details.source,
429
+ changes: details.changes.map((change) => ({
430
+ ...change,
431
+ value: change.previousValue,
432
+ previousValue: change.value
433
+ })),
434
+ rejected: []
435
+ };
436
+ }
437
+ function selectDataGridRegion(table, target) {
438
+ const rows = table.getRowsInDisplayOrder();
439
+ const columns = getDataGridDisplayOrderedColumns(table);
440
+ const anchorRow = rows[target.startRowIndex];
441
+ const anchorColumn = columns[target.startColumnIndex];
442
+ const focusRow = rows[Math.min(target.endRowIndex, rows.length - 1)];
443
+ const focusColumn = columns[target.endColumnIndex];
444
+ if (!anchorRow || !anchorColumn || !focusRow || !focusColumn) return;
445
+ table.selectCellRange({
446
+ anchorRowId: anchorRow.id,
447
+ anchorColumnId: anchorColumn.id,
448
+ focusRowId: focusRow.id,
449
+ focusColumnId: focusColumn.id
450
+ }, { mode: "replace" });
451
+ }
452
+ /**
453
+ * Imperative document-level session, the column-resize pattern: preview state
454
+ * is written as `data-cell-fill-target` attributes outside React, so the drag
455
+ * costs zero re-renders until release. v1 fills down or right (dominant axis)
456
+ * by repeating the source region's values; rows outside the rendered
457
+ * viewport of a virtualized body cannot be targeted mid-drag.
458
+ *
459
+ * Vertical distance is measured over the rows the view can show, so a drag
460
+ * onto a pinned draft fills exactly the rows the preview marked and never
461
+ * the off-page rows between. A cross-column fill round-trips through the
462
+ * source's format and the target's parse - the paste contract - because
463
+ * adjacent grid columns are heterogeneous; a parse rejection lands in the
464
+ * batch's rejected list, while cells that cannot be written are skipped
465
+ * and never tinted by the preview.
466
+ */
467
+ const dataGridGestureOutlineClasses = "outline-primary pointer-events-none absolute z-[35] outline-1 outline-dashed -outline-offset-1";
468
+ function startDataGridFillSession(options) {
469
+ const { table, viewport, onCellsChange } = options;
470
+ if (table.getCellSelectionBounds().length > 1) return;
471
+ const bound = getDataGridActiveBound(table);
472
+ if (!bound) return;
473
+ const rows = table.getRowsInDisplayOrder();
474
+ const columns = getDataGridDisplayOrderedColumns(table);
475
+ const domRowIds = /* @__PURE__ */ new Set();
476
+ for (const rowEl of Array.from(viewport.querySelectorAll("tbody tr[data-row-id]"))) {
477
+ const id = rowEl.getAttribute("data-row-id");
478
+ if (id) domRowIds.add(id);
479
+ }
480
+ const visibleRows = [];
481
+ for (let i = 0; i < rows.length; i++) {
482
+ const row = rows[i];
483
+ if (domRowIds.has(row.id)) visibleRows.push({
484
+ row,
485
+ displayIndex: i
486
+ });
487
+ }
488
+ const visibleIndexById = new Map(visibleRows.map((entry, index) => [entry.row.id, index]));
489
+ const sourceRows = visibleRows.filter(({ displayIndex }) => displayIndex >= bound.minRowIndex && displayIndex <= bound.maxRowIndex);
490
+ const sourceEndVisibleIndex = sourceRows.length ? visibleIndexById.get(sourceRows[sourceRows.length - 1].row.id) : -1;
491
+ if (sourceEndVisibleIndex === -1) return;
492
+ const columnIndexById = new Map(columns.map((column, index) => [column.id, index]));
493
+ const isFillableColumn = (column) => column.columnDef.enableCellSelection !== false && !!getDataGridWritableCellEdit(column);
494
+ let extension = null;
495
+ let previewCells = [];
496
+ const previewOutline = viewport.ownerDocument.createElement("div");
497
+ previewOutline.setAttribute("data-slot", "data-grid-cell-fill-preview");
498
+ previewOutline.className = dataGridGestureOutlineClasses;
499
+ previewOutline.style.display = "none";
500
+ viewport.appendChild(previewOutline);
501
+ viewport.setAttribute("data-cell-filling", "");
502
+ const sourceCorner = (rowId, columnId) => columnId ? viewport.querySelector(`tr[data-row-id="${CSS.escape(rowId)}"] td[data-col-id="${CSS.escape(columnId)}"]`) : null;
503
+ const positionPreviewOutline = () => {
504
+ const first = sourceRows.length ? sourceCorner(sourceRows[0].row.id, columns[bound.minColumnIndex]?.id) : null;
505
+ const lastSource = sourceRows.length ? sourceCorner(sourceRows[sourceRows.length - 1].row.id, columns[bound.maxColumnIndex]?.id) : null;
506
+ const far = previewCells.length ? previewCells[previewCells.length - 1] : lastSource;
507
+ if (!first || !far) {
508
+ previewOutline.style.display = "none";
509
+ return;
510
+ }
511
+ const firstRect = first.getBoundingClientRect();
512
+ const farRect = far.getBoundingClientRect();
513
+ const viewportRect = viewport.getBoundingClientRect();
514
+ const left = Math.min(firstRect.left, farRect.left);
515
+ const top = Math.min(firstRect.top, farRect.top);
516
+ previewOutline.style.display = "block";
517
+ previewOutline.style.left = `${left - viewportRect.left + viewport.scrollLeft}px`;
518
+ previewOutline.style.top = `${top - viewportRect.top + viewport.scrollTop}px`;
519
+ previewOutline.style.width = `${Math.max(firstRect.right, farRect.right) - left}px`;
520
+ previewOutline.style.height = `${Math.max(firstRect.bottom, farRect.bottom) - top}px`;
521
+ };
522
+ const clearPreview = () => {
523
+ for (const cell of previewCells) cell.removeAttribute("data-cell-fill-target");
524
+ previewCells = [];
525
+ positionPreviewOutline();
526
+ };
527
+ const getExtensionTargets = () => {
528
+ if (!extension) return null;
529
+ const columnEntries = columns.map((column, displayIndex) => ({
530
+ column,
531
+ displayIndex
532
+ }));
533
+ return extension.axis === "row" ? {
534
+ rowEntries: visibleRows.slice(sourceEndVisibleIndex + 1, sourceEndVisibleIndex + 1 + extension.count),
535
+ columnEntries: columnEntries.slice(bound.minColumnIndex, bound.maxColumnIndex + 1).filter(({ column }) => isFillableColumn(column))
536
+ } : {
537
+ rowEntries: sourceRows,
538
+ columnEntries: columnEntries.slice(bound.maxColumnIndex + 1, bound.maxColumnIndex + 1 + extension.count).filter(({ column }) => isFillableColumn(column))
539
+ };
540
+ };
541
+ const applyPreview = () => {
542
+ clearPreview();
543
+ const targets = getExtensionTargets();
544
+ if (!targets) return;
545
+ for (const { row } of targets.rowEntries) {
546
+ const rowElement = viewport.querySelector(`tr[data-row-id="${CSS.escape(row.id)}"]`);
547
+ if (!rowElement) continue;
548
+ for (const { column } of targets.columnEntries) {
549
+ if (!getDataGridWritableCellEdit(column, row.original)) continue;
550
+ const cellElement = rowElement.querySelector(`td[data-col-id="${CSS.escape(column.id)}"]`);
551
+ if (!cellElement) continue;
552
+ cellElement.setAttribute("data-cell-fill-target", "true");
553
+ previewCells.push(cellElement);
554
+ }
555
+ }
556
+ positionPreviewOutline();
557
+ };
558
+ const handleMove = (event) => {
559
+ const cellElement = document.elementFromPoint(event.clientX, event.clientY)?.closest?.("td[data-col-id]");
560
+ const rowElement = cellElement?.closest?.("tr[data-row-id]");
561
+ if (!cellElement || !rowElement || !viewport.contains(cellElement)) return;
562
+ const rowVisibleIndex = visibleIndexById.get(rowElement.getAttribute("data-row-id") ?? "");
563
+ const columnIndex = columnIndexById.get(cellElement.getAttribute("data-col-id") ?? "");
564
+ if (rowVisibleIndex === void 0 || columnIndex === void 0) return;
565
+ const rowsDelta = Math.max(0, rowVisibleIndex - sourceEndVisibleIndex);
566
+ const columnsDelta = Math.max(0, columnIndex - bound.maxColumnIndex);
567
+ const next = rowsDelta === 0 && columnsDelta === 0 ? null : rowsDelta >= columnsDelta ? {
568
+ axis: "row",
569
+ count: rowsDelta
570
+ } : {
571
+ axis: "column",
572
+ count: columnsDelta
573
+ };
574
+ if (next?.axis === extension?.axis && next?.count === extension?.count) return;
575
+ extension = next;
576
+ applyPreview();
577
+ };
578
+ const finish = (commit) => {
579
+ document.removeEventListener("mousemove", handleMove);
580
+ document.removeEventListener("mouseup", handleUp);
581
+ document.removeEventListener("keydown", handleKey, true);
582
+ clearPreview();
583
+ previewOutline.remove();
584
+ viewport.removeAttribute("data-cell-filling");
585
+ if (!commit || !extension || !onCellsChange) return;
586
+ const targets = getExtensionTargets();
587
+ if (!targets?.rowEntries.length) return;
588
+ const changes = [];
589
+ const rejected = [];
590
+ if (extension.axis === "row") for (let offset = 0; offset < targets.rowEntries.length; offset++) {
591
+ const targetRow = targets.rowEntries[offset].row;
592
+ const sourceRow = sourceRows[offset % sourceRows.length].row;
593
+ const targetCells = targetRow.getAllCellsByColumnId();
594
+ const sourceCells = sourceRow.getAllCellsByColumnId();
595
+ for (const { column } of targets.columnEntries) {
596
+ if (!getDataGridWritableCellEdit(column, targetRow.original)) continue;
597
+ changes.push({
598
+ rowId: targetRow.id,
599
+ columnId: column.id,
600
+ row: targetRow.original,
601
+ previousValue: targetCells[column.id]?.getValue(),
602
+ value: sourceCells[column.id]?.getValue()
603
+ });
604
+ }
605
+ }
606
+ else {
607
+ const regionColumns = bound.maxColumnIndex - bound.minColumnIndex + 1;
608
+ for (const { row } of targets.rowEntries) {
609
+ const cells = row.getAllCellsByColumnId();
610
+ for (const { column: targetColumn, displayIndex } of targets.columnEntries) {
611
+ const offset = displayIndex - (bound.maxColumnIndex + 1);
612
+ const sourceColumn = columns[bound.minColumnIndex + offset % regionColumns];
613
+ if (!sourceColumn) continue;
614
+ const targetEdit = getDataGridWritableCellEdit(targetColumn, row.original);
615
+ if (!targetEdit) continue;
616
+ const sourceValue = cells[sourceColumn.id]?.getValue();
617
+ let value = sourceValue;
618
+ if (targetColumn.id !== sourceColumn.id && targetEdit.parse) {
619
+ const sourceFormat = sourceColumn.columnDef.meta?.cellEdit?.format;
620
+ const raw = sourceFormat ? sourceFormat(sourceValue, row.original) : String(sourceValue ?? "");
621
+ const parsed = targetEdit.parse(raw, row.original);
622
+ if (parsed === void 0) {
623
+ rejected.push({
624
+ rowId: row.id,
625
+ columnId: targetColumn.id,
626
+ raw,
627
+ reason: "invalid"
628
+ });
629
+ continue;
630
+ }
631
+ value = parsed;
632
+ }
633
+ changes.push({
634
+ rowId: row.id,
635
+ columnId: targetColumn.id,
636
+ row: row.original,
637
+ previousValue: cells[targetColumn.id]?.getValue(),
638
+ value
639
+ });
640
+ }
641
+ }
642
+ }
643
+ if (changes.length || rejected.length) onCellsChange({
644
+ source: "fill",
645
+ changes,
646
+ rejected
647
+ });
648
+ selectDataGridRegion(table, {
649
+ startRowIndex: bound.minRowIndex,
650
+ endRowIndex: extension.axis === "row" ? targets.rowEntries[targets.rowEntries.length - 1].displayIndex : bound.maxRowIndex,
651
+ startColumnIndex: bound.minColumnIndex,
652
+ endColumnIndex: bound.maxColumnIndex + (extension.axis === "column" ? extension.count : 0)
653
+ });
654
+ };
655
+ const handleUp = () => finish(true);
656
+ const handleKey = (event) => {
657
+ if (event.key !== "Escape") return;
658
+ event.stopPropagation();
659
+ finish(false);
660
+ };
661
+ document.addEventListener("mousemove", handleMove);
662
+ document.addEventListener("mouseup", handleUp);
663
+ document.addEventListener("keydown", handleKey, true);
664
+ }
665
+ function isDataGridEditableTarget(target) {
666
+ return target instanceof Element && target.closest("input, textarea, select, [contenteditable], [data-cell-interactive]") != null;
667
+ }
668
+ function isDataGridInteractiveKeyTarget(target) {
669
+ return isDataGridEditableTarget(target) || target instanceof Element && target.closest("button, a, [role=\"checkbox\"]") != null;
670
+ }
671
+ /**
672
+ * Headless spreadsheet controller: keyboard navigation, clipboard, clear and
673
+ * the fill-handle drag. Mount once inside `<DataGrid>`, next to the table.
674
+ * Renders only a hidden anchor; the real listeners attach to the grid's own
675
+ * body viewport, which also receives focus (container-focus model), so a
676
+ * virtualized row unmounting can never strand `document.activeElement`.
677
+ */
678
+ function DataGridCellSelection({ apiRef, clipboard = true, keyboard = true }) {
679
+ const context = useDataGrid();
680
+ const anchorRef = useRef(null);
681
+ const [viewportEl, setViewportEl] = useState(null);
682
+ const [editorSession, setEditorSession] = useState(null);
683
+ const { table } = context;
684
+ const enabled = !!context.props.tableLayout?.cellSelection && table.atoms.cellSelection != null;
685
+ useEffect(() => {
686
+ if (!enabled) return;
687
+ const anchor = anchorRef.current;
688
+ if (!anchor) return;
689
+ const root = anchor.closest("[data-slot=\"data-grid\"]") ?? anchor.parentElement;
690
+ if (!root) return;
691
+ const viewports = Array.from(root.querySelectorAll("[data-slot=\"data-grid-table-viewport\"]"));
692
+ const viewport = viewports.find((node) => node.querySelector("[data-slot=\"data-grid-table-body\"]")) ?? viewports[0];
693
+ if (!viewport) return;
694
+ const getTable = () => context.table;
695
+ const getOnCellsChange = () => context.props.onCellsChange ?? null;
696
+ const isRangeSelectionEnabled = () => context.props.tableLayout?.cellSelectionMode !== "single";
697
+ const focusTarget = viewport.querySelector("table[data-slot=\"data-grid-table\"]") ?? viewport;
698
+ const scrollTdIntoView = (cell) => cell?.scrollIntoView?.({
699
+ block: "nearest",
700
+ inline: "nearest",
701
+ behavior: "instant"
702
+ });
703
+ const syncActiveDescendant = () => {
704
+ const cell = viewport.querySelector("td[data-cell-focused]");
705
+ if (cell?.id) focusTarget.setAttribute("aria-activedescendant", cell.id);
706
+ else focusTarget.removeAttribute("aria-activedescendant");
707
+ };
708
+ const scrollFocusedIntoView = (targetRowIndex, rowCount, explicitCell) => {
709
+ const queryScrollCell = () => explicitCell ? viewport.querySelector(`tr[data-row-id="${CSS.escape(explicitCell.rowId)}"] td[data-col-id="${CSS.escape(explicitCell.columnId)}"]`) : viewport.querySelector("td[data-cell-focused]");
710
+ requestAnimationFrame(() => {
711
+ const cell = queryScrollCell();
712
+ syncActiveDescendant();
713
+ if (cell || targetRowIndex == null || !rowCount) {
714
+ scrollTdIntoView(cell);
715
+ return;
716
+ }
717
+ let scroller = viewport;
718
+ while (scroller && scroller.scrollHeight <= scroller.clientHeight) scroller = scroller.parentElement;
719
+ if (!scroller) return;
720
+ scroller.scrollTop = (targetRowIndex + .5) / rowCount * scroller.scrollHeight - scroller.clientHeight / 2;
721
+ requestAnimationFrame(() => {
722
+ scrollTdIntoView(queryScrollCell());
723
+ syncActiveDescendant();
724
+ });
725
+ });
726
+ };
727
+ const requestCellEdit = (initialText) => {
728
+ const cell = getTable().getFocusedCell();
729
+ if (!cell) return false;
730
+ const cellEdit = getDataGridWritableCellEdit(cell.column, cell.row.original);
731
+ if (cellEdit?.control) {
732
+ const baseline = cellEdit.format ? cellEdit.format(cell.getValue(), cell.row.original) : String(cell.getValue() ?? "");
733
+ const headerTitle = cell.column.columnDef.meta?.headerTitle;
734
+ const header = cell.column.columnDef.header;
735
+ setEditorSession({
736
+ rowId: cell.row.id,
737
+ columnId: cell.column.id,
738
+ control: cellEdit.control,
739
+ initialValue: initialText ?? baseline,
740
+ baseline,
741
+ label: typeof headerTitle === "string" ? headerTitle : typeof header === "string" ? header : cell.column.id
742
+ });
743
+ return true;
744
+ }
745
+ const onCellEditRequest = context.props.onCellEditRequest;
746
+ if (cellEdit && onCellEditRequest) {
747
+ onCellEditRequest({
748
+ rowId: cell.row.id,
749
+ columnId: cell.column.id,
750
+ row: cell.row.original,
751
+ previousValue: cell.getValue(),
752
+ initialText
753
+ });
754
+ return true;
755
+ }
756
+ if (initialText !== void 0) return false;
757
+ const focusedCell = viewport.querySelector("td[data-cell-focused]");
758
+ const control = focusedCell ? [
759
+ "[role=\"combobox\"]",
760
+ "select",
761
+ "input, textarea",
762
+ "button, a, [role=\"checkbox\"], [tabindex]:not([tabindex=\"-1\"])"
763
+ ].map((candidate) => focusedCell.querySelector(candidate)).find(Boolean) : null;
764
+ if (!control) return false;
765
+ control.focus();
766
+ control.click();
767
+ return true;
768
+ };
769
+ let focusRetryTimer;
770
+ const focusCell = (rowId, columnId, options) => {
771
+ clearTimeout(focusRetryTimer);
772
+ let attempts = 12;
773
+ const attempt = () => {
774
+ if (!viewport.isConnected) return;
775
+ const cell = viewport.querySelector(`tr[data-row-id="${CSS.escape(rowId)}"] td[data-col-id="${CSS.escape(columnId)}"]`);
776
+ if (!cell) {
777
+ if (attempts-- > 0) focusRetryTimer = setTimeout(attempt, 32);
778
+ return;
779
+ }
780
+ getTable().setFocusedCell(rowId, columnId);
781
+ focusTarget.focus();
782
+ if (cell.id) focusTarget.setAttribute("aria-activedescendant", cell.id);
783
+ scrollTdIntoView(cell);
784
+ if (!options?.edit) return;
785
+ let editAttempts = 12;
786
+ const attemptEdit = () => {
787
+ if (!cell.isConnected) return;
788
+ if (cell.hasAttribute("data-cell-focused")) requestCellEdit();
789
+ else if (editAttempts-- > 0) focusRetryTimer = setTimeout(attemptEdit, 32);
790
+ };
791
+ attemptEdit();
792
+ };
793
+ attempt();
794
+ };
795
+ const clearSelection = () => {
796
+ getTable().resetCellSelection(true);
797
+ requestAnimationFrame(syncActiveDescendant);
798
+ };
799
+ const scrollToCell = (rowId, columnId) => {
800
+ scrollTdIntoView(viewport.querySelector(`tr[data-row-id="${CSS.escape(rowId)}"] td[data-col-id="${CSS.escape(columnId)}"]`));
801
+ };
802
+ if (apiRef) apiRef.current = {
803
+ focusCell,
804
+ clearSelection,
805
+ scrollToCell
806
+ };
807
+ const jumpFocus = (rowTarget, columnTarget, extend) => {
808
+ const table = getTable();
809
+ const focused = table.getFocusedCell();
810
+ if (!focused) return false;
811
+ const rows = table.getRowsInDisplayOrder();
812
+ const allColumns = getDataGridDisplayOrderedColumns(table);
813
+ const selectable = allColumns.filter((column) => column.columnDef.enableCellSelection !== false);
814
+ if (!rows.length || !selectable.length) return false;
815
+ const rowIndex = focused.row.getDisplayIndex();
816
+ let clampedRowIndex = rowTarget === "first" ? 0 : rowTarget === "last" ? rows.length - 1 : rowTarget === "same" ? rowIndex : Math.min(rows.length - 1, Math.max(0, rowIndex + rowTarget.delta));
817
+ if (table.getRowModel().rows.length !== rows.length) {
818
+ const rendered = new Set(table.getRowModel().rows.map((row) => row.id));
819
+ for (const rowEl of Array.from(viewport.querySelectorAll("tbody tr[data-row-id]"))) rendered.add(rowEl.getAttribute("data-row-id"));
820
+ const step = clampedRowIndex >= rowIndex ? -1 : 1;
821
+ while (clampedRowIndex !== rowIndex && rows[clampedRowIndex] && !rendered.has(rows[clampedRowIndex].id)) clampedRowIndex += step;
822
+ }
823
+ const targetRow = rows[clampedRowIndex];
824
+ const targetColumn = columnTarget === "first" ? selectable[0] : columnTarget === "last" ? selectable[selectable.length - 1] : focused.column;
825
+ if (!targetRow || !targetColumn) return false;
826
+ if (extend) {
827
+ const bound = getDataGridActiveBound(table);
828
+ const columnIndex = allColumns.findIndex((column) => column.id === focused.column.id);
829
+ let anchorRowId = focused.row.id;
830
+ let anchorColumnId = focused.column.id;
831
+ if (bound) {
832
+ anchorRowId = rows[rowIndex === bound.minRowIndex ? bound.maxRowIndex : bound.minRowIndex]?.id ?? anchorRowId;
833
+ anchorColumnId = allColumns[columnIndex === bound.minColumnIndex ? bound.maxColumnIndex : bound.minColumnIndex]?.id ?? anchorColumnId;
834
+ }
835
+ table.selectCellRange({
836
+ anchorRowId,
837
+ anchorColumnId,
838
+ focusRowId: targetRow.id,
839
+ focusColumnId: targetColumn.id
840
+ }, { mode: "replace" });
841
+ } else table.setFocusedCell(targetRow.id, targetColumn.id);
842
+ scrollFocusedIntoView(clampedRowIndex, rows.length, extend ? {
843
+ rowId: targetRow.id,
844
+ columnId: targetColumn.id
845
+ } : void 0);
846
+ return true;
847
+ };
848
+ const moveFocusVisual = (direction) => {
849
+ const table = getTable();
850
+ const focused = table.getFocusedCell();
851
+ const target = focused ? getDataGridStepTarget(table, viewport, {
852
+ rowId: focused.row.id,
853
+ columnId: focused.column.id
854
+ }, direction) : null;
855
+ if (target === "edge") return;
856
+ if (target) {
857
+ table.setFocusedCell(target.rowId, target.columnId);
858
+ return;
859
+ }
860
+ table.moveCellSelection(direction);
861
+ };
862
+ const getPageJumpSize = () => {
863
+ const row = viewport.querySelector("tbody tr[data-row-id]");
864
+ let scroller = viewport;
865
+ while (scroller && scroller.scrollHeight <= scroller.clientHeight) scroller = scroller.parentElement;
866
+ const rowHeight = row?.getBoundingClientRect().height || 0;
867
+ const viewHeight = scroller?.clientHeight || viewport.clientHeight;
868
+ if (!rowHeight || !viewHeight) return 10;
869
+ return Math.max(1, Math.floor(viewHeight / rowHeight) - 1);
870
+ };
871
+ const getAppendedRows = () => {
872
+ const body = viewport.querySelector("tbody");
873
+ const appended = [];
874
+ let rowEl = body?.lastElementChild;
875
+ while (rowEl && !rowEl.hasAttribute("data-row-id")) {
876
+ if (rowEl instanceof HTMLElement && !rowEl.hasAttribute("aria-hidden")) appended.unshift(rowEl);
877
+ rowEl = rowEl.previousElementSibling;
878
+ }
879
+ return appended;
880
+ };
881
+ const focusFirstIn = (row) => {
882
+ const focusable = row?.querySelector("button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])");
883
+ if (!focusable) return false;
884
+ focusable.focus();
885
+ return row.ownerDocument.activeElement === focusable;
886
+ };
887
+ const handleKeyDown = (event) => {
888
+ if (event.defaultPrevented) return;
889
+ const appendedRow = event.target instanceof Element ? event.target.closest("tbody > tr:not([data-row-id])") : null;
890
+ if (appendedRow && viewport.contains(appendedRow)) {
891
+ const appended = getAppendedRows();
892
+ const index = appended.indexOf(appendedRow);
893
+ if (index === -1) return;
894
+ if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
895
+ if (event.key === "ArrowDown") {
896
+ if (focusFirstIn(appended[index + 1])) event.preventDefault();
897
+ return;
898
+ }
899
+ if (index > 0 && focusFirstIn(appended[index - 1])) {
900
+ event.preventDefault();
901
+ return;
902
+ }
903
+ focusTarget.focus();
904
+ syncActiveDescendant();
905
+ event.preventDefault();
906
+ return;
907
+ }
908
+ if (isDataGridInteractiveKeyTarget(event.target)) {
909
+ if (event.key === "Escape") {
910
+ const cell = event.target.closest?.("td[data-col-id]");
911
+ if (cell && viewport.contains(cell)) {
912
+ event.preventDefault();
913
+ event.stopPropagation();
914
+ focusTarget.focus();
915
+ syncActiveDescendant();
916
+ }
917
+ }
918
+ return;
919
+ }
920
+ const table = getTable();
921
+ const rtl = getComputedStyle(viewport).direction === "rtl";
922
+ const horizontal = (direction) => rtl ? direction === "left" ? "right" : "left" : direction;
923
+ if ((event.key === "a" || event.key === "A" || event.code === "KeyA") && (event.metaKey || event.ctrlKey) && !event.altKey) {
924
+ if (isRangeSelectionEnabled()) {
925
+ table.selectAllCells();
926
+ requestAnimationFrame(syncActiveDescendant);
927
+ }
928
+ event.preventDefault();
929
+ return;
930
+ }
931
+ if ((event.metaKey || event.ctrlKey) && !event.altKey && clipboard) {
932
+ const isCopy = event.key === "c" || event.key === "C" || event.code === "KeyC";
933
+ const isCut = event.key === "x" || event.key === "X" || event.code === "KeyX";
934
+ if (isCopy || isCut) {
935
+ event.preventDefault();
936
+ writeSelectionToClipboard().then((written) => {
937
+ if (!written) return;
938
+ context.props.onCellsCopy?.({
939
+ ...written,
940
+ cut: isCut
941
+ });
942
+ if (!isCut) return;
943
+ const onCellsChange = getOnCellsChange();
944
+ if (!onCellsChange) return;
945
+ const details = buildDataGridClearDetails(getTable(), "cut", true, viewport);
946
+ if (details) onCellsChange(details);
947
+ });
948
+ return;
949
+ }
950
+ }
951
+ switch (event.key) {
952
+ case "ArrowUp":
953
+ case "ArrowDown":
954
+ case "ArrowLeft":
955
+ case "ArrowRight": {
956
+ const direction = event.key === "ArrowUp" ? "up" : event.key === "ArrowDown" ? "down" : horizontal(event.key === "ArrowLeft" ? "left" : "right");
957
+ if (event.metaKey || event.ctrlKey) {
958
+ if (direction === "up" ? jumpFocus("first", "same", event.shiftKey && isRangeSelectionEnabled()) : direction === "down" ? jumpFocus("last", "same", event.shiftKey && isRangeSelectionEnabled()) : jumpFocus("same", direction === "left" ? "first" : "last", event.shiftKey && isRangeSelectionEnabled())) event.preventDefault();
959
+ return;
960
+ }
961
+ if (direction === "down" && !event.shiftKey) {
962
+ const focused = table.getFocusedCell();
963
+ const renderedRows = viewport.querySelectorAll("tbody tr[data-row-id]");
964
+ const lastRenderedId = renderedRows[renderedRows.length - 1]?.getAttribute("data-row-id");
965
+ if (focused && lastRenderedId && focused.row.id === lastRenderedId && focusFirstIn(getAppendedRows()[0])) {
966
+ event.preventDefault();
967
+ return;
968
+ }
969
+ }
970
+ if (event.shiftKey && isRangeSelectionEnabled()) {
971
+ const corner = extendDataGridSelection(table, viewport, direction);
972
+ event.preventDefault();
973
+ scrollFocusedIntoView(void 0, void 0, corner ?? void 0);
974
+ return;
975
+ }
976
+ const focused = table.getFocusedCell();
977
+ const target = focused ? getDataGridStepTarget(table, viewport, {
978
+ rowId: focused.row.id,
979
+ columnId: focused.column.id
980
+ }, direction) : null;
981
+ if (target === "edge") {
982
+ event.preventDefault();
983
+ return;
984
+ }
985
+ if (target) {
986
+ table.setFocusedCell(target.rowId, target.columnId);
987
+ event.preventDefault();
988
+ scrollFocusedIntoView();
989
+ return;
990
+ }
991
+ table.moveCellSelection(direction);
992
+ event.preventDefault();
993
+ scrollFocusedIntoView();
994
+ return;
995
+ }
996
+ case "Home":
997
+ case "End": {
998
+ const edge = event.key === "Home" ? "first" : "last";
999
+ if (event.metaKey || event.ctrlKey ? jumpFocus(edge, edge, event.shiftKey && isRangeSelectionEnabled()) : jumpFocus("same", edge, event.shiftKey && isRangeSelectionEnabled())) event.preventDefault();
1000
+ return;
1001
+ }
1002
+ case "PageUp":
1003
+ case "PageDown": {
1004
+ const delta = (event.key === "PageUp" ? -1 : 1) * getPageJumpSize();
1005
+ if (jumpFocus({ delta }, "same", event.shiftKey && isRangeSelectionEnabled())) event.preventDefault();
1006
+ return;
1007
+ }
1008
+ case "Enter":
1009
+ if (!event.shiftKey && requestCellEdit()) {
1010
+ event.preventDefault();
1011
+ return;
1012
+ }
1013
+ moveFocusVisual(event.shiftKey ? "up" : "down");
1014
+ event.preventDefault();
1015
+ scrollFocusedIntoView();
1016
+ return;
1017
+ case "F2":
1018
+ if (requestCellEdit()) event.preventDefault();
1019
+ return;
1020
+ case "Tab": {
1021
+ const before = table.getFocusedCell();
1022
+ moveFocusVisual(event.shiftKey ? "left" : "right");
1023
+ const after = table.getFocusedCell();
1024
+ if (after && after.id !== before?.id) {
1025
+ event.preventDefault();
1026
+ scrollFocusedIntoView();
1027
+ }
1028
+ return;
1029
+ }
1030
+ case "Delete":
1031
+ case "Backspace": {
1032
+ const onCellsChange = getOnCellsChange();
1033
+ if (!onCellsChange) return;
1034
+ const details = buildDataGridClearDetails(table, "clear", false, viewport);
1035
+ if (details) onCellsChange(details);
1036
+ event.preventDefault();
1037
+ return;
1038
+ }
1039
+ case "Escape":
1040
+ if (table.getCellSelectionBounds().length) {
1041
+ table.resetCellSelection(true);
1042
+ requestAnimationFrame(syncActiveDescendant);
1043
+ event.preventDefault();
1044
+ event.stopPropagation();
1045
+ }
1046
+ return;
1047
+ }
1048
+ if (event.key === " ") {
1049
+ const checkbox = viewport.querySelector("td[data-cell-focused]")?.querySelector("[role=\"checkbox\"], input[type=\"checkbox\"]");
1050
+ if (checkbox) {
1051
+ checkbox.click();
1052
+ event.preventDefault();
1053
+ return;
1054
+ }
1055
+ }
1056
+ if (event.key.length === 1 && !event.metaKey && !(event.ctrlKey && !event.altKey) && requestCellEdit(event.key)) {
1057
+ event.preventDefault();
1058
+ return;
1059
+ }
1060
+ if (event.key === " " && table.getFocusedCell()) event.preventDefault();
1061
+ };
1062
+ const writeSelectionToClipboard = async () => {
1063
+ const grid = getDataGridActiveRegionGrid(getTable(), viewport);
1064
+ if (!grid) return null;
1065
+ const text = serializeDataGridClipboardText(grid);
1066
+ try {
1067
+ if (typeof ClipboardItem !== "undefined" && navigator.clipboard?.write) {
1068
+ await navigator.clipboard.write([new ClipboardItem({
1069
+ "text/plain": new Blob([text], { type: "text/plain" }),
1070
+ "text/html": new Blob([renderDataGridClipboardHtml(grid)], { type: "text/html" })
1071
+ })]);
1072
+ return {
1073
+ text,
1074
+ grid
1075
+ };
1076
+ }
1077
+ if (navigator.clipboard?.writeText) {
1078
+ await navigator.clipboard.writeText(text);
1079
+ return {
1080
+ text,
1081
+ grid
1082
+ };
1083
+ }
1084
+ } catch {}
1085
+ const doc = viewport.ownerDocument;
1086
+ const scratch = doc.createElement("textarea");
1087
+ scratch.value = text;
1088
+ scratch.style.position = "fixed";
1089
+ scratch.style.opacity = "0";
1090
+ doc.body.appendChild(scratch);
1091
+ scratch.select();
1092
+ let copied = false;
1093
+ try {
1094
+ copied = doc.execCommand("copy");
1095
+ } catch {
1096
+ copied = false;
1097
+ }
1098
+ scratch.remove();
1099
+ focusTarget.focus();
1100
+ return copied ? {
1101
+ text,
1102
+ grid
1103
+ } : null;
1104
+ };
1105
+ const copySelection = (event, cut) => {
1106
+ const grid = getDataGridActiveRegionGrid(getTable(), viewport);
1107
+ if (!grid || !event.clipboardData) return false;
1108
+ event.preventDefault();
1109
+ const text = serializeDataGridClipboardText(grid);
1110
+ event.clipboardData.setData("text/plain", text);
1111
+ event.clipboardData.setData("text/html", renderDataGridClipboardHtml(grid));
1112
+ context.props.onCellsCopy?.({
1113
+ text,
1114
+ grid,
1115
+ cut
1116
+ });
1117
+ return true;
1118
+ };
1119
+ const handleCopy = (event) => {
1120
+ if (isDataGridEditableTarget(event.target)) return;
1121
+ copySelection(event, false);
1122
+ };
1123
+ const handleCut = (event) => {
1124
+ if (isDataGridEditableTarget(event.target)) return;
1125
+ if (!copySelection(event, true)) return;
1126
+ const onCellsChange = getOnCellsChange();
1127
+ if (!onCellsChange) return;
1128
+ const details = buildDataGridClearDetails(getTable(), "cut", true, viewport);
1129
+ if (details) onCellsChange(details);
1130
+ };
1131
+ const handlePaste = (event) => {
1132
+ if (isDataGridEditableTarget(event.target)) return;
1133
+ const onCellsChange = getOnCellsChange();
1134
+ if (!onCellsChange) return;
1135
+ const text = event.clipboardData?.getData("text/plain");
1136
+ if (!text) return;
1137
+ event.preventDefault();
1138
+ const table = getTable();
1139
+ const result = buildDataGridPasteDetails(table, parseDataGridClipboardText(text), viewport);
1140
+ if (!result) return;
1141
+ onCellsChange(result.details);
1142
+ if (isRangeSelectionEnabled()) selectDataGridRegion(table, result.target);
1143
+ };
1144
+ let pressedUnfocusedControl = false;
1145
+ const getTwoStepControl = (target) => {
1146
+ if (!(target instanceof Element)) return null;
1147
+ if (target.closest("[data-cell-interactive]")) return null;
1148
+ if (target.closest("[role=\"checkbox\"], input[type=\"checkbox\"]")) return null;
1149
+ const marked = target.closest("[data-cell-control]");
1150
+ if (marked) return marked;
1151
+ return target.closest("button, a, select, input, textarea, [contenteditable], [role=\"combobox\"]");
1152
+ };
1153
+ const handleControlPointerDown = (event) => {
1154
+ pressedUnfocusedControl = false;
1155
+ if (event.button !== 0) return;
1156
+ if (event.shiftKey || event.ctrlKey || event.metaKey) return;
1157
+ if (context.props.tableLayout?.cellEditMode === "click") return;
1158
+ const control = getTwoStepControl(event.target);
1159
+ const cell = control?.closest("td[data-col-id]");
1160
+ if (!control || !cell || !viewport.contains(cell)) return;
1161
+ if (cell.hasAttribute("data-cell-focused")) return;
1162
+ const column = getTable().getColumn(cell.getAttribute("data-col-id") ?? "");
1163
+ if (!column || column.columnDef.enableCellSelection === false) return;
1164
+ pressedUnfocusedControl = true;
1165
+ event.stopPropagation();
1166
+ };
1167
+ const handleControlClick = (event) => {
1168
+ if (!pressedUnfocusedControl) return;
1169
+ pressedUnfocusedControl = false;
1170
+ event.preventDefault();
1171
+ event.stopPropagation();
1172
+ };
1173
+ const handleControlMouseDown = (event) => {
1174
+ if (!pressedUnfocusedControl) return;
1175
+ event.stopPropagation();
1176
+ event.preventDefault();
1177
+ const cell = event.target?.closest?.("td[data-col-id]");
1178
+ const rowId = cell?.closest("tr[data-row-id]")?.getAttribute("data-row-id");
1179
+ const columnId = cell?.getAttribute("data-col-id");
1180
+ if (!rowId || !columnId) return;
1181
+ const tableNow = getTable();
1182
+ const cellApi = tableNow.getRowsInDisplayOrder().find((row) => row.id === rowId)?.getAllCellsByColumnId()[columnId];
1183
+ if (!cellApi) return;
1184
+ if (isRangeSelectionEnabled()) cellApi.getSelectionStartHandler()(event);
1185
+ else tableNow.setFocusedCell(rowId, columnId);
1186
+ focusTarget.focus();
1187
+ requestAnimationFrame(syncActiveDescendant);
1188
+ };
1189
+ let dragStartedOnCell = false;
1190
+ let dragStartSelectionKey = "";
1191
+ const getSelectionKey = () => {
1192
+ const table = getTable();
1193
+ const bounds = table.getCellSelectionBounds();
1194
+ const bound = bounds[bounds.length - 1];
1195
+ return `${table.getSelectedCellCount()}:${bounds.length}:${bound ? `${bound.minRowIndex},${bound.minColumnIndex},${bound.maxRowIndex},${bound.maxColumnIndex}` : ""}`;
1196
+ };
1197
+ const handleDragMouseUp = () => {
1198
+ const wasDrag = dragStartedOnCell && getTable().getSelectedCellCount() > 1 && getSelectionKey() !== dragStartSelectionKey;
1199
+ dragStartedOnCell = false;
1200
+ viewport.removeAttribute("data-cell-selecting");
1201
+ if (!wasDrag) return;
1202
+ const squelch = (clickEvent) => {
1203
+ clickEvent.stopPropagation();
1204
+ clickEvent.preventDefault();
1205
+ };
1206
+ viewport.addEventListener("click", squelch, { capture: true });
1207
+ setTimeout(() => viewport.removeEventListener("click", squelch, true), 0);
1208
+ };
1209
+ const handleMouseDown = (event) => {
1210
+ if (event.button !== 0) return;
1211
+ requestAnimationFrame(syncActiveDescendant);
1212
+ const target = event.target;
1213
+ if ((event.shiftKey || event.metaKey || event.ctrlKey) && isRangeSelectionEnabled() && target?.closest?.("td[data-col-id]")) setTimeout(() => focusTarget.focus(), 0);
1214
+ dragStartedOnCell = !!target?.closest?.("td");
1215
+ if (dragStartedOnCell) {
1216
+ dragStartSelectionKey = getSelectionKey();
1217
+ viewport.setAttribute("data-cell-selecting", "");
1218
+ }
1219
+ if (!target?.closest?.("[data-slot=\"data-grid-cell-fill-handle\"]")) return;
1220
+ event.preventDefault();
1221
+ event.stopPropagation();
1222
+ startDataGridFillSession({
1223
+ table: getTable(),
1224
+ viewport,
1225
+ onCellsChange: getOnCellsChange()
1226
+ });
1227
+ };
1228
+ const handleClickToEdit = (event) => {
1229
+ if (context.props.tableLayout?.cellEditMode !== "click") return;
1230
+ if (event.shiftKey || event.ctrlKey || event.metaKey) return;
1231
+ if (isDataGridInteractiveKeyTarget(event.target)) return;
1232
+ if (!(event.target?.closest?.("td"))?.hasAttribute("data-cell-focused")) return;
1233
+ requestCellEdit();
1234
+ };
1235
+ const handleDoubleClick = (event) => {
1236
+ if (isDataGridInteractiveKeyTarget(event.target)) return;
1237
+ if (!(event.target?.closest?.("td"))?.hasAttribute("data-cell-focused")) return;
1238
+ requestCellEdit();
1239
+ };
1240
+ const previousTabIndex = focusTarget.getAttribute("tabindex");
1241
+ const previousOutline = focusTarget.style.outline;
1242
+ if (keyboard) {
1243
+ focusTarget.tabIndex = 0;
1244
+ focusTarget.style.outline = "none";
1245
+ viewport.addEventListener("keydown", handleKeyDown);
1246
+ }
1247
+ if (clipboard) {
1248
+ viewport.addEventListener("copy", handleCopy);
1249
+ viewport.addEventListener("cut", handleCut);
1250
+ viewport.addEventListener("paste", handlePaste);
1251
+ }
1252
+ viewport.addEventListener("pointerdown", handleControlPointerDown);
1253
+ viewport.addEventListener("mousedown", handleControlMouseDown);
1254
+ viewport.addEventListener("click", handleControlClick);
1255
+ viewport.addEventListener("mousedown", handleMouseDown);
1256
+ viewport.addEventListener("click", handleClickToEdit);
1257
+ viewport.addEventListener("dblclick", handleDoubleClick);
1258
+ viewport.ownerDocument.addEventListener("mouseup", handleDragMouseUp);
1259
+ const toBound = (bound) => ({
1260
+ minRowIndex: bound.minRowIndex,
1261
+ maxRowIndex: bound.maxRowIndex,
1262
+ minColumnIndex: bound.minColumnIndex,
1263
+ maxColumnIndex: bound.maxColumnIndex
1264
+ });
1265
+ const selectionSubscription = table.atoms.cellSelection?.subscribe(() => {
1266
+ const onCellSelectionChange = context.props.onCellSelectionChange;
1267
+ if (!onCellSelectionChange) return;
1268
+ const tableNow = getTable();
1269
+ const focusedCell = tableNow.getFocusedCell();
1270
+ const activeBound = getDataGridActiveBound(tableNow);
1271
+ onCellSelectionChange({
1272
+ focused: focusedCell ? {
1273
+ rowId: focusedCell.row.id,
1274
+ columnId: focusedCell.column.id
1275
+ } : null,
1276
+ bounds: tableNow.getCellSelectionBounds().map(toBound),
1277
+ activeBound: activeBound ? toBound(activeBound) : null,
1278
+ visibleCellCount: getDataGridVisibleSelectedCellCount(tableNow, viewport)
1279
+ });
1280
+ });
1281
+ setViewportEl(viewport);
1282
+ return () => {
1283
+ if (keyboard) {
1284
+ if (previousTabIndex === null) focusTarget.removeAttribute("tabindex");
1285
+ else focusTarget.setAttribute("tabindex", previousTabIndex);
1286
+ focusTarget.style.outline = previousOutline;
1287
+ focusTarget.removeAttribute("aria-activedescendant");
1288
+ viewport.removeEventListener("keydown", handleKeyDown);
1289
+ }
1290
+ if (clipboard) {
1291
+ viewport.removeEventListener("copy", handleCopy);
1292
+ viewport.removeEventListener("cut", handleCut);
1293
+ viewport.removeEventListener("paste", handlePaste);
1294
+ }
1295
+ viewport.removeEventListener("pointerdown", handleControlPointerDown);
1296
+ viewport.removeEventListener("mousedown", handleControlMouseDown);
1297
+ viewport.removeEventListener("click", handleControlClick);
1298
+ viewport.removeEventListener("mousedown", handleMouseDown);
1299
+ viewport.removeEventListener("click", handleClickToEdit);
1300
+ viewport.removeEventListener("dblclick", handleDoubleClick);
1301
+ viewport.ownerDocument.removeEventListener("mouseup", handleDragMouseUp);
1302
+ viewport.removeAttribute("data-cell-selecting");
1303
+ selectionSubscription?.unsubscribe();
1304
+ clearTimeout(focusRetryTimer);
1305
+ if (apiRef) apiRef.current = null;
1306
+ setViewportEl(null);
1307
+ setEditorSession(null);
1308
+ };
1309
+ }, [
1310
+ enabled,
1311
+ keyboard,
1312
+ clipboard,
1313
+ table.atoms.cellSelection?.subscribe,
1314
+ context.props.tableLayout?.cellEditMode,
1315
+ context.table,
1316
+ context.props.onCellsCopy,
1317
+ context.props.onCellEditRequest,
1318
+ context.props.tableLayout?.cellSelectionMode,
1319
+ context.props.onCellsChange,
1320
+ context.props.onCellSelectionChange,
1321
+ apiRef
1322
+ ]);
1323
+ useEffect(() => {
1324
+ if (!viewportEl || !editorSession) return;
1325
+ viewportEl.setAttribute("data-cell-editing", "");
1326
+ return () => viewportEl.removeAttribute("data-cell-editing");
1327
+ }, [viewportEl, editorSession]);
1328
+ const closeEditorSession = (advance, refocus = true) => {
1329
+ setEditorSession(null);
1330
+ if (advance) {
1331
+ const tableNow = context.table;
1332
+ const focused = tableNow.getFocusedCell();
1333
+ const target = focused && viewportEl ? getDataGridStepTarget(tableNow, viewportEl, {
1334
+ rowId: focused.row.id,
1335
+ columnId: focused.column.id
1336
+ }, advance) : null;
1337
+ if (target && target !== "edge") tableNow.setFocusedCell(target.rowId, target.columnId);
1338
+ else if (!target) tableNow.moveCellSelection(advance);
1339
+ }
1340
+ if (!refocus) return;
1341
+ requestAnimationFrame(() => {
1342
+ const focusEl = viewportEl?.querySelector("table[data-slot=\"data-grid-table\"]") ?? viewportEl;
1343
+ focusEl?.focus();
1344
+ const cell = viewportEl?.querySelector("td[data-cell-focused]");
1345
+ if (cell?.id) focusEl?.setAttribute("aria-activedescendant", cell.id);
1346
+ cell?.scrollIntoView?.({
1347
+ block: "nearest",
1348
+ inline: "nearest",
1349
+ behavior: "instant"
1350
+ });
1351
+ });
1352
+ };
1353
+ const commitEditorSession = (raw, advance, refocus = true) => {
1354
+ const session = editorSession;
1355
+ closeEditorSession(advance, refocus);
1356
+ const onCellsChange = context.props.onCellsChange;
1357
+ if (!session || !onCellsChange || raw === session.baseline) return;
1358
+ const tableNow = context.table;
1359
+ const row = tableNow.getRowsInDisplayOrder().find((candidate) => candidate.id === session.rowId);
1360
+ const column = tableNow.getColumn(session.columnId);
1361
+ const cellEdit = column && row ? getDataGridWritableCellEdit(column, row.original) : null;
1362
+ if (!row || !column || !cellEdit) return;
1363
+ const previousValue = row.getAllCellsByColumnId()[column.id]?.getValue();
1364
+ let value = raw;
1365
+ if (cellEdit.parse) {
1366
+ const parsed = cellEdit.parse(raw, row.original);
1367
+ if (parsed === void 0) {
1368
+ onCellsChange({
1369
+ source: "edit",
1370
+ changes: [],
1371
+ rejected: [{
1372
+ rowId: session.rowId,
1373
+ columnId: session.columnId,
1374
+ raw,
1375
+ reason: "invalid"
1376
+ }]
1377
+ });
1378
+ return;
1379
+ }
1380
+ value = parsed;
1381
+ }
1382
+ onCellsChange({
1383
+ source: "edit",
1384
+ changes: [{
1385
+ rowId: session.rowId,
1386
+ columnId: session.columnId,
1387
+ row: row.original,
1388
+ previousValue,
1389
+ value
1390
+ }],
1391
+ rejected: []
1392
+ });
1393
+ };
1394
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("span", {
1395
+ ref: anchorRef,
1396
+ hidden: true,
1397
+ "data-slot": "data-grid-cell-selection"
1398
+ }), enabled && viewportEl && editorSession ? /* @__PURE__ */ jsx(DataGridCellEditorOverlay, {
1399
+ viewport: viewportEl,
1400
+ session: editorSession,
1401
+ enterAdvance: context.props.tableLayout?.cellEditEnterAdvance === true,
1402
+ onCommit: commitEditorSession,
1403
+ onCancel: () => closeEditorSession(null)
1404
+ }, `${editorSession.rowId}:${editorSession.columnId}`) : null] });
1405
+ }
1406
+ /**
1407
+ * The built-in free-text editor: a portal into the body viewport, positioned
1408
+ * flush over the focused cell with the cell's own font, alignment and
1409
+ * padding, so the text keeps its exact place - the Sheets model. The
1410
+ * `textarea` control grows downward over the rows below as the text wraps.
1411
+ */
1412
+ function measureDataGridCellEditorStyle(viewport) {
1413
+ const cell = viewport.querySelector("td[data-cell-focused]");
1414
+ if (!cell) return null;
1415
+ const cellRect = cell.getBoundingClientRect();
1416
+ const viewportRect = viewport.getBoundingClientRect();
1417
+ const cellStyle = getComputedStyle(cell);
1418
+ const lineHeight = Number.parseFloat(cellStyle.lineHeight) || Number.parseFloat(cellStyle.fontSize) * 1.5 || 20;
1419
+ const centeredBlockPadding = Math.max(Number.parseFloat(cellStyle.paddingTop) || 0, (cellRect.height - lineHeight) / 2);
1420
+ return {
1421
+ left: cellRect.left - viewportRect.left + viewport.scrollLeft,
1422
+ top: cellRect.top - viewportRect.top + viewport.scrollTop,
1423
+ width: cellRect.width,
1424
+ minHeight: cellRect.height,
1425
+ font: cellStyle.font || void 0,
1426
+ fontFamily: cellStyle.fontFamily,
1427
+ fontSize: cellStyle.fontSize,
1428
+ fontWeight: cellStyle.fontWeight,
1429
+ fontStyle: cellStyle.fontStyle,
1430
+ lineHeight: cellStyle.lineHeight,
1431
+ letterSpacing: cellStyle.letterSpacing,
1432
+ textAlign: cellStyle.textAlign,
1433
+ paddingLeft: cellStyle.paddingLeft,
1434
+ paddingRight: cellStyle.paddingRight,
1435
+ paddingTop: centeredBlockPadding,
1436
+ paddingBottom: centeredBlockPadding
1437
+ };
1438
+ }
1439
+ function DataGridCellEditorOverlay({ viewport, session, enterAdvance, onCommit, onCancel }) {
1440
+ const [style] = useState(() => measureDataGridCellEditorStyle(viewport));
1441
+ const finishedRef = useRef(false);
1442
+ const placeCaretAtEnd = (element) => {
1443
+ if (!element) return;
1444
+ const end = element.value.length;
1445
+ element.setSelectionRange?.(end, end);
1446
+ };
1447
+ useEffect(() => {
1448
+ if (!style) onCancel();
1449
+ }, [style, onCancel]);
1450
+ useEffect(() => {
1451
+ const body = viewport.querySelector("tbody");
1452
+ if (!body) return;
1453
+ const observer = new MutationObserver(() => {
1454
+ if (!finishedRef.current) onCancel();
1455
+ });
1456
+ observer.observe(body, {
1457
+ childList: true,
1458
+ subtree: true
1459
+ });
1460
+ return () => observer.disconnect();
1461
+ }, [viewport, onCancel]);
1462
+ if (!style) return null;
1463
+ const finish = (element, commit, advance = null, refocus = true) => {
1464
+ if (finishedRef.current) return;
1465
+ finishedRef.current = true;
1466
+ if (commit) onCommit(element.value, advance, refocus);
1467
+ else onCancel();
1468
+ };
1469
+ const handleKeyDown = (event) => {
1470
+ const element = event.currentTarget;
1471
+ if (event.key === "Escape") {
1472
+ event.preventDefault();
1473
+ event.stopPropagation();
1474
+ finish(element, false);
1475
+ return;
1476
+ }
1477
+ if (event.key === "Tab") {
1478
+ event.preventDefault();
1479
+ finish(element, true, event.shiftKey ? "left" : "right");
1480
+ return;
1481
+ }
1482
+ if (event.key !== "Enter") return;
1483
+ if (session.control === "textarea" && (event.shiftKey || event.altKey)) return;
1484
+ event.preventDefault();
1485
+ finish(element, true, enterAdvance ? event.shiftKey ? "up" : "down" : null);
1486
+ };
1487
+ const sharedClassName = "text-foreground bg-background outline-primary absolute z-[35] box-border resize-none outline-1 outline-solid -outline-offset-1";
1488
+ return createPortal(session.control === "textarea" ? /* @__PURE__ */ jsx("textarea", {
1489
+ "data-slot": "data-grid-cell-editor",
1490
+ ref: placeCaretAtEnd,
1491
+ autoFocus: true,
1492
+ "aria-label": session.label,
1493
+ defaultValue: session.initialValue,
1494
+ rows: 1,
1495
+ style,
1496
+ className: cn(sharedClassName, "field-sizing-content overflow-hidden"),
1497
+ onKeyDown: handleKeyDown,
1498
+ onBlur: (event) => finish(event.currentTarget, true, null, false)
1499
+ }) : /* @__PURE__ */ jsx("input", {
1500
+ "data-slot": "data-grid-cell-editor",
1501
+ ref: placeCaretAtEnd,
1502
+ autoFocus: true,
1503
+ "aria-label": session.label,
1504
+ defaultValue: session.initialValue,
1505
+ style,
1506
+ className: sharedClassName,
1507
+ onKeyDown: handleKeyDown,
1508
+ onBlur: (event) => finish(event.currentTarget, true, null, false)
1509
+ }), viewport);
1510
+ }
1511
+ /**
1512
+ * Thin shell over row selection for bulk actions: selected count, a slot for
1513
+ * the consumer's controls, and a clear action. Hidden while nothing is
1514
+ * selected. What the controls do stays consumer-owned.
1515
+ *
1516
+ * Presented as a floating toolbar, the Google Sheets way: auto width,
1517
+ * centered, elevated, and sticky to the viewport bottom with breathing room,
1518
+ * so bulk actions stay reachable while the grid scrolls.
1519
+ */
1520
+ function DataGridSelectionBar({ children, className, label, clearLabel = "Clear", onClear }) {
1521
+ const context = useDataGrid();
1522
+ const rowSelectionAtom = context.table.atoms.rowSelection;
1523
+ if (rowSelectionAtom == null) return null;
1524
+ return /* @__PURE__ */ jsx(Subscribe, {
1525
+ source: rowSelectionAtom,
1526
+ children: () => {
1527
+ const count = context.table.getSelectedRowModel().rows.length;
1528
+ if (count === 0) return null;
1529
+ return /* @__PURE__ */ jsxs("div", {
1530
+ "data-slot": "data-grid-selection-bar",
1531
+ className: cn("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", className),
1532
+ children: [/* @__PURE__ */ jsx("span", {
1533
+ className: "font-medium text-foreground text-sm",
1534
+ children: label ? label(count) : `${count} selected`
1535
+ }), /* @__PURE__ */ jsxs("div", {
1536
+ className: "flex flex-1 flex-wrap items-center justify-end gap-2.5",
1537
+ children: [children, /* @__PURE__ */ jsx(Button, {
1538
+ variant: "ghost",
1539
+ size: "sm",
1540
+ onClick: () => {
1541
+ context.table.resetRowSelection();
1542
+ onClear?.();
1543
+ },
1544
+ children: clearLabel
1545
+ })]
1546
+ })]
1547
+ });
1548
+ }
1549
+ });
1550
+ }
1551
+ //#endregion
1552
+ export { DataGridCellSelection, DataGridSelectionBar, buildDataGridClearDetails, buildDataGridPasteDetails, getDataGridActiveRegionGrid, getDataGridVisibleSelectedCellCount, invertDataGridCellsChange, parseDataGridClipboardText, serializeDataGridClipboardText, tileDataGridClipboardBlock };
1553
+
1554
+ //# sourceMappingURL=data-grid-cell-selection.js.map